示例#1
0
        public override void intelligentSystemCalculateWeights(PerceptParams pp, float t)
        {
            //ФАЗА СОЗДАНИЯ ПРИМЕРОВ
            foreach ( KeyValuePair<state,double> measure in measures)
            {
                coordpair tile = new coordpair{ x = measure.Key.x, y = measure.Key.y};
                measureHistory[measure.Key] = measure.Value;
                if (photos.ContainsKey(tile))
                {
                    feedSample(photos[tile],tile, measure.Value);
                }
            }
            measures = new Dictionary<state, double>();//да-да, они обнуляются
            if (pythonerLaunched)
            {
                if (!pythoner.IsAlive)
                {
                    tree = system.tree;
                    //работает прямо очень часто. Мб приоритет понизить?
                    dataWnd.treeVisualisationLabel.Text = ((string)tree.visualise(enc)).Replace("takeValue","").Replace("takeConstant","");
                    dataWnd.encbox.Text = enc.visualise();
                    launchComposeThread();
                }
            }
            //конец фазы создания примеров

            //именно здесь происходит обновление весов силами ССИУ
            if (t - tlast > dt)
                tlast = t;
            else return;
            pplast = pp;
            DateTime atStart = DateTime.Now;
            Random picker = new Random();

            for (int itr = 0; itr < classificationsPerCall;itr++ )
            {
                if (tiles.Count == 0)
                {
                    tiles = getVisibleTiles();
                    continue;//in case there are none
                }

                int ind = picker.Next(tiles.Count);
                coordpair tile = tiles[ind];

                tiles.RemoveAt(ind);

                double dist = (getTileCoords(tile.x, tile.y) - new Vec2(pos.xc, pos.yc)).Length();
                if ((dist < 3) || !visible(tile) || measureHistory.ContainsKey(pr.states[orientation.down][tile.x, tile.y])) continue;

                {
                    Bitmap bmp = photos[tile];

                    dynamic sample = wrapper.sampleFromBitmap(bmp);
                    dynamic rsltlist = tree.classify(sample);
                    try
                    {
                        dynamic cost = enc.decode(rsltlist);
                        pr.setCost(tile.x, tile.y, cost);
                        if (cost == double.PositiveInfinity)
                            obsts[pr.states[orientation.down][tile.x, tile.y]] = System.Drawing.Color.Crimson;
                        else if (cost > 2)
                            obsts[pr.states[orientation.down][tile.x, tile.y]] = System.Drawing.Color.DarkGray;
                        else
                        {
                            if (obsts.ContainsKey(pr.states[orientation.down][tile.x, tile.y]))
                                obsts.Remove(pr.states[orientation.down][tile.x, tile.y]);
                            if (infs.Contains(pr.states[orientation.down][tile.x, tile.y]))
                                infs.Remove(pr.states[orientation.down][tile.x, tile.y]);

                        }
                    }
                    catch (Exception e)
                    { };

                }
            }
        }
示例#2
0
        //end of measurements
        public override Control react(PerceptParams pp, float t)
        {
            //ВАЖНО!!! для чистоты эксперимента необходимо, чтобы ОТРАБОТКА траектории, а значит, и
            //параметры регулятора и механизм вывода CarControl, были одинаковые или выбирались на равных
            //условиях во всех 7(план максимум) сериях экспериментов: контрольная, сети по базе, деревья по базе,
            //сети с ходу, деревья с ходу, комбинация по базе, комбинация с ходу.
            //07072014 Ёж: ну как, три пункта мы выполнили :P

            //measures:
            if (!finished)
            {
                if (path.Count <= 1)
                    finished = true;

                numMeasures += 1;
                pathDistance += System.Math.Sqrt(System.Math.Pow(pos.xc - pp.p.xc, 2) + System.Math.Pow(pos.yc - pp.p.yc, 2));//distance of travel.
                sumPassability += System.Math.Min(pp.ksurf, 1000);
                if (pp.velocity > maxSpeed) maxSpeed = pp.velocity;
                if (t - tBack < goBackOnCollisionTimer)
                {
                    if (!goingBack)
                    {
                        goingBack = true;
                        numCollisions++;
                    }
                }
                else
                    goingBack = false;
                dataWnd.TimeLabel.Text = t.ToString("F3");
                dataWnd.PathDistanceLabel.Text = pathDistance.ToString("F3");
                dataWnd.NumCollisionsLabel.Text = numCollisions.ToString();
                dataWnd.AvgSpeedLabel.Text = (pathDistance / t).ToString("F3");
                dataWnd.MaxSpeedLabel.Text = (maxSpeed).ToString("F3");
                dataWnd.AvgPassabilityLabel.Text = (sumPassability / numMeasures).ToString("F3");
            }
            //end of measures

            pos = pp.p;
            return base.react(pp, t);
            //выполняется на каждом тике таймера.
            /* Состав PerceptParams:
             * float lidar_cm, lidar_d; - параметры лидара - включите, если хотите, но заставьте его игнорить щуп.
             * float dist, targ_angle; - расстояние и угол до цели.
             * float light, Color color, int features_angle,features_line,int features_gleam - НЕ(!)реализованые параметры изображения.
             * double kaif - как раз наоборот, мера общей ТРУДНОСТИ перемещения сейчас из-за ПРЕПЯТСТВИЙ.
             * double ksurf - мера трудности сдвижения из-за поверхности.
             * Vec2 nose - координаты щупа в Box2D
             * Pose p - координаты робота в Box2D
             * System.Drawing.Image cameraView - Оно самое - изображение из pictureBox2, точнее его КОПИЯ.
             * double velocity - скорость из Box2d
             *
             * Состав CarControl
             * float u_gas - газ
             * float u_steer - поворот колёс относительно оси "вперёд" машины.
             * float u_brake - тормоза.
             */
        }
        public override void intelligentSystemCalculateWeights(PerceptParams pp, float t)
        {
            //ФАЗА СОЗДАНИЯ ПРИМЕРОВ
            foreach ( KeyValuePair<state,double> measure in measures)
            {
                coordpair tile = new coordpair{ x = measure.Key.x, y = measure.Key.y};
                measureHistory[measure.Key] = measure.Value;
                if (photos.ContainsKey(tile))
                {
                    feedSample(photos[tile],tile, measure.Value);
                }
            }
            measures = new Dictionary<state, double>();//да-да, они обнуляются
            if (pythonerLaunched)//flag for the first single round
            {
                if (!pythoner.IsAlive)
                {
                    dataWnd.treeVisualisationLabel.Text = system.logWriter.readString();
                    dataWnd.encbox.Text = enc.visualise();
                    launchComposeThread();
                }
            }
            //конец фазы создания примеров

            //именно здесь происходит обновление весов силами ССИУ
            if (t - tlast > dt)
                tlast = t;
            else return;
            pplast = pp;
            Random picker = new Random();

            for (int itr = 0; itr < classificationsPerCall; itr++)
            {
                if (tiles.Count == 0)
                {
                    tiles = getActualTiles();
                    continue;//in case there are none
                }

                int ind = picker.Next(tiles.Count);
                coordpair tile = tiles[ind];

                tiles.RemoveAt(ind);

                double dist = distanceFromRobot(tile);
                //don't classify too close,    too far                  , or directly measured
                if ((dist < blindZone) || (dist > classificationRange && !visible(tile)) || measureHistory.ContainsKey(pr.states[orientation.down][tile.x, tile.y])) continue;

                {
                    Bitmap bmp = photos[tile];

                    dynamic sample = wrapper.sampleFromBitmap(bmp);
                    try
                    {//why try: there was chance that some trees got polled while being composed or pruned. If you wanna adjust the learning routine so as it won't cause this error, you may try.
                        dynamic rslt = system.classify(sample, 1, 10);
            #warning adjust
                        double cost = enc.decodeResult(rslt);

                        pr.setCost(tile.x, tile.y, cost);
                        if (cost == double.PositiveInfinity)
                            obsts[pr.states[orientation.down][tile.x, tile.y]] = System.Drawing.Color.Crimson;
                        else if (cost > 2)
                            obsts[pr.states[orientation.down][tile.x, tile.y]] = System.Drawing.Color.DarkGray;
                        else
                        {
                            if (obsts.ContainsKey(pr.states[orientation.down][tile.x, tile.y]))
                                obsts.Remove(pr.states[orientation.down][tile.x, tile.y]);
                            if (infs.Contains(pr.states[orientation.down][tile.x, tile.y]))
                                infs.Remove(pr.states[orientation.down][tile.x, tile.y]);

                        }
                    }
                    catch (Exception e) { }
                    //{ System.Windows.Forms.MessageBox.Show(e.Message); };

                }
            }
        }