Example #1
0
        /// <summary>
        /// Trains and writes a model based on the events in the specified event file.
        /// the name of the model created is based on the event file name.
        /// </summary>
        /// <param name="args"> eventfile [iterations cuttoff] </param>
        /// <exception cref="IOException"> when the eventfile can not be read or the model file can not be written. </exception>
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.Error.WriteLine("Usage: RealValueFileEventStream eventfile [iterations cutoff]");
                Environment.Exit(1);
            }
            int    ai         = 0;
            string eventFile  = args[ai++];
            int    iterations = 100;
            int    cutoff     = 5;

            if (ai < args.Length)
            {
                iterations = Convert.ToInt32(args[ai++]);
                cutoff     = Convert.ToInt32(args[ai++]);
            }
            AbstractModel            model;
            RealValueFileEventStream es = new RealValueFileEventStream(eventFile);

            try
            {
                model = GIS.trainModel(iterations, new OnePassRealValueDataIndexer(es, cutoff));
            }
            finally
            {
                es.close();
            }
            (new SuffixSensitiveGISModelWriter(model, new Jfile(eventFile + ".bin.gz"))).persist();
        }
Example #2
0
        public void GISTest2()
        {
            int   size  = 7;
            Graph graph = new Graph(size);

            graph.AddEdge(1, 2);
            graph.AddEdge(1, 3);
            graph.AddEdge(1, 4);
            graph.AddEdge(1, 5);
            graph.AddEdge(1, 6);
            graph.AddEdge(1, 7);

            graph.AddEdge(2, 3);
            graph.AddEdge(3, 4);
            graph.AddEdge(4, 5);

            graph.AddEdge(5, 6);
            graph.AddEdge(6, 7);
            graph.AddEdge(7, 2);

            GIS gis = new GIS(graph);

            gis.ColorGraph();

            Console.WriteLine(gis.GetGisOutput());
        }
Example #3
0
        /// <summary>
        /// Gets the event trainer.
        /// </summary>
        /// <param name="parameters">The machine learnable parameters.</param>
        /// <param name="reportMap">The report map.</param>
        /// <param name="monitor">A evaluation monitor that can be used to listen the messages during the training or it can cancel the training operation.
        /// This argument can be a <c>null</c> value.</param>
        /// <returns>The <see cref="IEventTrainer" /> trainer object.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// Unable to retrieve the trainer from the training parameters.
        /// or
        /// The constructor of the trainer must have a standard constructor.
        /// </exception>
        public static IEventTrainer GetEventTrainer(TrainingParameters parameters, Dictionary <string, string> reportMap, Monitor monitor)
        {
            var algorithm = parameters.Get(Parameters.Algorithm);

            if (algorithm == null)
            {
                AbstractEventTrainer trainer = new GIS(monitor);
                trainer.Init(parameters, reportMap);
                return(trainer);
            }

            var trainerType = GetTrainerType(parameters);

            if (trainerType.HasValue && trainerType.Value == TrainerType.EventModelTrainer)
            {
                var type = GetTrainer(algorithm);

                if (type == null)
                {
                    throw new InvalidOperationException("Unable to retrieve the trainer from the training parameters.");
                }

                var ctor = type.GetConstructor(new [] { typeof(Monitor) });
                if (ctor == null)
                {
                    throw new InvalidOperationException("The constructor of the trainer must have a standard constructor.");
                }

                var trainer = (IEventTrainer)ctor.Invoke(new object[] { monitor });
                trainer.Init(parameters, reportMap);
                return(trainer);
            }

            return(null);
        }
Example #4
0
        public void TestRealValuedWeightsVsRepeatWeighting()
        {
            var rvfes1 = new RealValueFileEventStream(Tests.OpenFile("opennlp/data/maxent/real-valued-weights-training-data.txt"));
            var rvfes2 = new FileEventStream(Tests.OpenFile("opennlp/data/maxent/repeat-weighting-training-data.txt"));

            var realModel   = GIS.TrainModel(100, new OnePassRealValueDataIndexer(rvfes1, 1));
            var repeatModel = GIS.TrainModel(100, new OnePassRealValueDataIndexer(rvfes2, 1));

            rvfes1.Dispose();
            rvfes2.Dispose();

            Assert.NotNull(realModel);
            Assert.NotNull(repeatModel);

            var features2Classify = new[] { "feature2", "feature5" };
            var realResults       = realModel.Eval(features2Classify);
            var repeatResults     = repeatModel.Eval(features2Classify);

            Assert.AreEqual(realResults.Length, repeatResults.Length);

            for (var i = 0; i < realResults.Length; i++)
            {
                Assert.AreEqual(realResults[i], repeatResults[i], 0.01f);
            }

            features2Classify = new[] { "feature1", "feature2", "feature3", "feature4", "feature5" };
            realResults       = realModel.Eval(features2Classify, new[] { 5.5f, 6.1f, 9.1f, 4.0f, 1.8f });
            repeatResults     = repeatModel.Eval(features2Classify, new[] { 5.5f, 6.1f, 9.1f, 4.0f, 1.8f });

            Assert.AreEqual(realResults.Length, repeatResults.Length);
            for (var i = 0; i < realResults.Length; i++)
            {
                Assert.AreEqual(realResults[i], repeatResults[i], 0.01f);
            }
        }
Example #5
0
        protected void MontarGis(string indicadorProcesoCodificado7365, string calificadorListaCodigosCodificado1131)
        {
            var dtm = new GIS(new IndicadorDeProceso(indicadorProcesoCodificado7365, calificadorListaCodigosCodificado1131,
                                                     null, null));

            Segmentos.Add(dtm);
            Mensaje += dtm.getSegmento();
        }
    void mouseDragOrClick(Vector2 currentFlatMousePos)
    {
        //滑鼠左鍵點下後抓取滑鼠位置,並且開始判斷是拖曳或是點擊
        if (mouseDragging)
        {
            Vector2 diffScreen = currentFlatMousePos - startClipPos;
            if (diffScreen.x + diffScreen.y != 0f) //滑鼠從點下到放開有移動就視為拖曳
            {
                Vector2 diffRelative = new Vector2(diffScreen.x / Screen.width, diffScreen.y / Screen.height);
                Vector2 diff         = startDragingPos - diffRelative * taiwanMap.terrainSize * taiwanMap.rangeScale;
                taiwanMap.newPos = ((int)diff.x, (int)diff.y);
                maybeClick       = false; //如果是拖曳就不是點擊
            }
        }

        if (Input.GetMouseButtonDown(0))
        {
            startDragingPos = new Vector2(taiwanMap.newPos.x, taiwanMap.newPos.y);
            startClipPos    = currentFlatMousePos;
            mouseDragging   = true;
            maybeClick      = true;
        }

        if (Input.GetMouseButtonUp(0))
        {
            if (maybeClick)                          //點擊滑鼠就是放士兵或收士兵
            {
                if (hit.transform.name == "Terrain") //點在圖台上表示放士兵
                {
                    float terrainRatio = taiwanMap.terrainSize * taiwanMap.rangeScale;
                    (int x, int y)terrainRayHit = ((int)(hit.point.x * terrainRatio), (int)(hit.point.z * terrainRatio));
                    (int x, int y)hitTerrainPos = (terrainRayHit.x + taiwanMap.newPos.x, terrainRayHit.y + taiwanMap.newPos.y);
                    var placeLongLat = GIS.TerrainToLonglat(hitTerrainPos);
                    var troopID      = troopManager.TroopMissingID("soldier");
                    // troopManager.TroopMove("soldier", troopID, placeLongLat.lng, placeLongLat.lat);
                    messageBroker.AddTroop("soldier", troopID, placeLongLat.lng, placeLongLat.lat);
                }
                else if (hit.transform.name.StartsWith("ToonSoldier_WW2_demo_model"))  //點到士兵表示收士兵
                {
                    hit.transform.gameObject.tag = "Finish";
                    //使用rayhit只能看到被hit到的Gameobject,但在原本的Troopmanager中採用dictionary進行Gameobject管理。
                    //直接刪除gameobject會造成錯誤。所以必須找到對應的dictionary key,透過管理系統進行刪除。這在士兵量太過
                    //龐大時效能會不好
                    string troopID = troopManager.GetDeletedSelectedTroopID();
                    messageBroker.RemoveTroop("soldier", troopID);
                }
                troopManager.redrawTroops = true;
            }
            maybeClick    = false;
            mouseDragging = false;
        }
    }
Example #7
0
        public void GreedyIndependentSetsTest()
        {
            string filePath = "/home/paul/coding/algorithms-data-structures/NPheuristics/GraphColoring/graph1Data.txt";

            GraphBuilder.GraphBuilder builder = new GraphBuilder.GraphBuilder();
            Graph graph = builder.BuildGraphFromFile(filePath);

            GIS gis = new GIS(graph);

            gis.ColorGraph();

            Console.WriteLine(gis.GetGisOutput());
        }
Example #8
0
        // POST: api/Poi

        public string Post([FromBody] object latLng)
        {
            if (latLng == null)
            {
                return("");
            }
            try {
                Debug.WriteLine(latLng);

                LocFeed currLoc = (LocFeed)Helpers.JsonDesrialize(latLng.ToString(), typeof(LocFeed));
                Grid    grid    = new Grid();
                var     lat     = double.Parse(currLoc.x);
                var     lng     = double.Parse(currLoc.y);
                grid.GetGrid(lat, lng);

                GIS          gis    = new GIS();
                List <Store> stores = db.GetPerimeterStores(grid.Id); // "1296.7764");

                List <StoreLite> feed = new List <StoreLite>();
                foreach (Store store in stores)
                {
                    //store.Distance = Math.Truncate(Helpers.GetStraightDistance(lat, lng, store.Latitude, store.Longitude) * 100) / 100;

                    double dist, dura;
                    var    result = gis.GetDistanceMatrix(lat, lng, store.Latitude, store.Longitude, out dist, out dura);
                    dist = Math.Truncate(dist / 100) / 10;
                    TimeSpan ts = new TimeSpan(0, 0, (int)dura);
                    dura = Math.Round(ts.TotalMinutes);
                    feed.Add(new StoreLite()
                    {
                        I = store.StoreId,      // id
                        N = store.StoreName,    // name
                        X = store.Latitude,     // lat
                        Y = store.Longitude,    // lng
                        G = store.Grid,         // grid
                        D = dist,               // distance
                        T = dura,               // time
                        A = store.Address       // address
                    });
                }

                var output = Helpers.JsonSerialize(feed.OrderBy(s => s.T).ThenBy(s => s.D));
                return(output);
            }
            catch
            {
                return("");
            }
        }
Example #9
0
        public void TestScaleResults()
        {
            const string smallValues = "predA=0.1 predB=0.2 A\n" + "predB=0.3 predA=0.1 B\n";
            const string largeValues = "predA=10 predB=20 A\n" + "predB=30 predA=10 B\n";

            const string smallTest = "predA=0.2 predB=0.2";
            const string largeTest = "predA=20 predB=20";

            var smallReader      = new StringReader(smallValues);
            var smallEventStream = new RealBasicEventStream(new PlainTextByLineStream(smallReader));

            var smallModel = GIS.TrainModel(100, new OnePassRealValueDataIndexer(smallEventStream, 0), false);

            var contexts     = smallTest.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var values       = RealValueFileEventStream.ParseContexts(contexts);
            var smallResults = smallModel.Eval(contexts, values);

            var smallResultString = smallModel.GetAllOutcomes(smallResults);

            Console.Out.WriteLine("smallResults: " + smallResultString);

            var largeReader      = new StringReader(largeValues);
            var largeEventStream = new RealBasicEventStream(new PlainTextByLineStream(largeReader));

            var largeModel = GIS.TrainModel(100, new OnePassRealValueDataIndexer(largeEventStream, 0), false);

            contexts = largeTest.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            values   = RealValueFileEventStream.ParseContexts(contexts);
            var largeResults = largeModel.Eval(contexts, values);

            var largeResultString = smallModel.GetAllOutcomes(largeResults);

            Console.Out.WriteLine("largeResults: " + largeResultString);

            Assert.AreEqual(smallResults.Length, largeResults.Length);
            for (var i = 0; i < smallResults.Length; i++)
            {
                /*
                 * System.out.println(string.format(
                 * "classify with smallModel: %1$s = %2$f", smallModel.getOutcome(i),
                 * smallResults[i]));
                 * System.out.println(string.format(
                 * "classify with largeModel: %1$s = %2$f", largeModel.getOutcome(i),
                 * largeResults[i])); */

                Assert.AreEqual(smallResults[i], largeResults[i], 0.01f);
            }
        }
Example #10
0
        public void ToHexString()
        {
            {
                (double, double)wgs = (39.907333, 116.391083);
                Assert.AreEqual((215825, 99330), GIS.GetGisTileXY(wgs, 18));
            }

            {
                (float, float)ll = (42, 122);

                (double lat, double lon)ll1 = GIS.Gauss_LL(GIS.LL_Gauss(ll, GIS.Coordinate.BJ54), GIS.Coordinate.BJ54);
                Assert.AreEqual(ll, ((float)ll1.lat, (float)ll1.lon));

                (double lat, double lon)ll2 = GIS.Gauss_LL(GIS.LL_Gauss(ll, GIS.Coordinate.WGS84), GIS.Coordinate.WGS84);
                Assert.AreEqual(ll, ((float)ll2.lat, (float)ll2.lon));

                (double lat, double lon)ll3 = GIS.Gauss_LL(GIS.LL_Gauss(ll, GIS.Coordinate.XA80), GIS.Coordinate.XA80);
                Assert.AreEqual(ll, ((float)ll3.lat, (float)ll3.lon));
            }
        }
Example #11
0
        public void ReadAirportAndTrainInfo()
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                while (true)
                {
                    try
                    {
                        string trainplan    = GetHttpUrl("readTrainingPlan");
                        string airport      = GetHttpUrl("readAirportInfo");
                        string conditioncmd = GetHttpUrl("readConditionCommandInfo");
                        //机场信息
                        airport = cla_http.GetHttpData(airport, "{ }");
                        if ("" == airport)
                        {
                            Thread.Sleep(1000);
                            continue;
                        }
                        airportInfoBases = JsonConvert.DeserializeObject <List <airportInfoBase> >(airport);
                        //训练计划
                        trainplan = cla_http.GetHttpData(trainplan, "{ }");
                        if ("" == trainplan)
                        {
                            Thread.Sleep(1000);
                            continue;
                        }
                        trainPlans = JsonConvert.DeserializeObject <List <TrainPlan> >(trainplan);
                        //条件性命令
                        conditioncmd      = cla_http.GetHttpData(conditioncmd, "{ }");
                        conditionCommands = JsonConvert.DeserializeObject <List <ConditionCommandInfo> >(trainplan);

                        GIS.Invoke();
                        break;
                    }
                    catch (Exception err)
                    {
                        Thread.Sleep(1000);
                    }
                }
            });
        }
Example #12
0
        /// <summary>
        /// Gets the event trainer.
        /// </summary>
        /// <param name="parameters">The machine learnable parameters.</param>
        /// <param name="reportMap">The report map.</param>
        /// <param name="monitor">
        /// A evaluation monitor that can be used to listen the messages during the training or it can cancel the training operation.
        /// This argument can be a <c>null</c> value.
        /// </param>
        /// <returns>The <see cref="IEventTrainer"/> trainer object.</returns>
        public static IEventTrainer GetEventTrainer(TrainingParameters parameters, Dictionary <string, string> reportMap, Monitor monitor)
        {
            var algorithm = parameters.Get(Parameters.Algorithm);

            if (algorithm == null)
            {
                AbstractEventTrainer trainer = new GIS(monitor);
                trainer.Init(parameters, reportMap);
                return(trainer);
            }

            var trainerType = GetTrainerType(parameters);

            if (trainerType.HasValue && trainerType.Value == TrainerType.EventModelTrainer)
            {
                var type = GetTrainer(algorithm);

                var trainer = (IEventTrainer)Activator.CreateInstance(type, monitor);
                trainer.Init(parameters, reportMap);
                return(trainer);
            }

            return(null);
        }