Esempio n. 1
0
    //Dijkstra algorithm - go backwards - from goal cell to root cell
    public Distances DijkstraShortestPathTo(MazeCell goal)
    {
        MazeCell currentCell = goal;
        // навигационная цепочка
        Distances breadcrumbTrail = new Distances(this.startingCell);

        breadcrumbTrail[currentCell] = this[currentCell];

        // starightforward algo -  For each cell along the path, the neighboring cell with the lowest distance will be the next step of the solution
        while (currentCell != startingCell)
        {
            foreach (MazeCell neighbourCell in currentCell.Links())  //get all linked cells of current cell
            {
                if (this[neighbourCell] < this[currentCell])         //find linked cell with min distance (closest to the startingCell)
                {
                    if (!breadcrumbTrail.ContainsKey(neighbourCell)) // add to dictionary if not exists in dictionary
                    {
                        breadcrumbTrail.Add(neighbourCell, this[neighbourCell]);
                    }
                    else
                    {
                        breadcrumbTrail[neighbourCell] = this[neighbourCell]; // replace distance if less distance value found
                    }

                    currentCell = neighbourCell;                    // switch current cell to the neighbour
                    break;
                }
            }
        }
        return(breadcrumbTrail);
    }
Esempio n. 2
0
 public void find_dist_to_all_rovers(List <Rover> fidos)
 {
     Distances.Clear();
     for (int i = 0; i < num_rovers; i++)
     {
         Distances.Add(find_dist_to_rover(i, fidos));
     }
 }
Esempio n. 3
0
 public Ship(int id, List <Link> links)
 {
     Id = id;
     foreach (var link in links.Where(l => l.HasFactory(Id)))
     {
         Distances.Add(link.GetOtherId(Id), link.Distance);
     }
 }
Esempio n. 4
0
        public void Deserialize(BinaryReader r)
        {
            Distances.Clear();
            int distances_count = r.ReadInt32();

            for (int i = 0; i < distances_count; ++i)
            {
                Distances.Add(new CellIdPair(r), r.ReadSingle());
            }
        }
        /// <inheritdoc />
        protected override void Initialize()
        {
            base.Initialize();

            // Initialize colors and distances
            double initialDistance = DistanceRelaxer.InitialDistance;

            foreach (TVertex vertex in VisitedGraph.Vertices)
            {
                VerticesColors.Add(vertex, GraphColor.White);
                Distances.Add(vertex, initialDistance);
                OnVertexInitialized(vertex);
            }
        }
Esempio n. 6
0
        private void UpdateDist(int id_1, int id_2, float dist)
        {
            CellIdPair p             = new CellIdPair(id_1, id_2);
            float      existing_dist = 0;

            if (Distances.TryGetValue(p, out existing_dist))
            {
                Distances[p] = Math.Min(existing_dist, dist);
            }
            else
            {
                Distances.Add(p, dist);
            }
        }
        /// <inheritdoc />
        protected override void Initialize()
        {
            base.Initialize();

            double initialDistance = DistanceRelaxer.InitialDistance;

            // Initialize colors and distances
            foreach (TVertex vertex in VisitedGraph.Vertices)
            {
                VerticesColors.Add(vertex, GraphColor.White);
                Distances.Add(vertex, initialDistance);
            }

            _vertexQueue = new FibonacciQueue <TVertex, double>(DistancesIndexGetter());
        }
Esempio n. 8
0
        public void Prerecognize()
        {
            try
            {
                _canvas = new Canvas((Bitmap)_image.Clone(), 8.0d);
                _canvas.RecognizeImage();

                testsparam t = _ge.testsparams.First(tp => tp.idt == _testid);

                t.answersparams.Load();
                IEnumerable <answersparam> answers = t.answersparams.Where(a => a.idt == t.idt);
                foreach (answersparam a in answers)
                {
                    Distances _distances = new Distances();
                    _distances.Add(_canvas.TopLeftMarker, (double)a.toplx, (double)a.toply);
                    _distances.Add(_canvas.TopRightMarker, (double)a.toprx, (double)a.topry);
                    _distances.Add(_canvas.BottomLeftMarker, (double)a.blx, (double)a.bly);
                    _distances.Add(_canvas.BottomRightMarker, (double)a.brx, (double)a.bry);

                    Answer _answer = new Answer(_canvas.CorrectedImage, (int)a.num, (int)a.cellscount, _distances, (int)a.intercellswidth, (int)a.cellswidth, (int)a.cellshight);

                    IEnumerable <cellsparam> cells = a.cellsparams.Where(c => c.ida == a.ida);
                    a.cellsparams.Load();
                    int i = 0;
                    foreach (cellsparam cp in cells)
                    {
                        _answer.Cells[i].ContentDescription = cp.description.Trim();
                        i++;
                    }

                    _canvas.Answers.Add(_answer);
                }
                OnRecItem();
            }
            catch (Exception ex) { throw ex; }
        }
Esempio n. 9
0
        public void Deserialize(BinaryReader r)
        {
            Distances.Clear();
            int distances_count = r.ReadInt32();

            for (int i = 0; i < distances_count; ++i)
            {
                int key1           = r.ReadInt32();
                var distance_table = new Dictionary <int, float>();
                Distances.Add(key1, distance_table);
                int distances2_count = r.ReadInt32();
                for (int j = 0; j < distances2_count; ++j)
                {
                    distance_table.Add(r.ReadInt32(), r.ReadSingle());
                }
            }
        }
Esempio n. 10
0
        public Ferry()
        {
            Directions.Add(0, 'N');
            Directions.Add(90, 'E');
            Directions.Add(180, 'S');
            Directions.Add(270, 'W');

            CurrentDirection = 90;

            Distances.Add('N', 0);
            Distances.Add('E', 0);
            Distances.Add('S', 0);
            Distances.Add('W', 0);

            Waypoints.Add('N', 1);
            Waypoints.Add('E', 10);
            Waypoints.Add('S', 0);
            Waypoints.Add('W', 0);
        }
        /// <inheritdoc />
        protected override void Initialize()
        {
            base.Initialize();

            VerticesColors.Clear();
            _costs = new Dictionary <TVertex, double>(VisitedGraph.VertexCount);

            // Initialize colors and distances
            double initialDistance = DistanceRelaxer.InitialDistance;

            foreach (TVertex vertex in VisitedGraph.Vertices)
            {
                VerticesColors.Add(vertex, GraphColor.White);
                Distances.Add(vertex, initialDistance);
                _costs.Add(vertex, initialDistance);
            }

            _vertexQueue = new FibonacciQueue <TVertex, double>(_costs, DistanceRelaxer.Compare);
        }
Esempio n. 12
0
        private void ParseDistances(XmlReader r)
        {
            r.ReadStartElement();

            while (r.NodeType == XmlNodeType.Element)
            {
                if (r.Name == "Distance")
                {
                    Distances.Add(new GenericPostureDistance(r));
                }
                else
                {
                    string outerXml = r.ReadOuterXml();
                    log.DebugFormat("Unparsed content in XML: {0}", outerXml);
                }
            }

            r.ReadEndElement();
        }
Esempio n. 13
0
    public IEnumerator ShowConnectionsDelayed(List <Connect> Connections)
    {
        float distance = 0;

        for (var i = 0; i < Connections.Count; i++)
        {
            var startPos = Connections[i].Source.transform.position;
            var endPos   = Connections[i].Target.transform.position;
            distance += Connections[i].Distance;

            gameObject.GetComponent <AlgorithmManager>().ConnectPoints(startPos, endPos);

            yield return(new WaitForSeconds(gameObject.GetComponent <AlgorithmManager>().DrawDelay));
        }

        Distances.Add(distance);
        gameObject.GetComponent <AlgorithmManager>().Stopwatch.Stop();
        Debug.Log("Prim distance: " + distance + ", time taken: " + gameObject.GetComponent <AlgorithmManager>().Stopwatch.Elapsed);

        gameObject.GetComponent <AlgorithmManager>().iterationDone = true;
    }
Esempio n. 14
0
        private void UpdateDist(int id_1, int id_2, float dist)
        {
            if (id_1 == id_2)
            {
                dist = 0;
            }

            if (!Distances.ContainsKey(id_1))
            {
                Distances.Add(id_1, new Dictionary <int, float>());
            }

            if (!Distances.ContainsKey(id_2))
            {
                Distances.Add(id_2, new Dictionary <int, float>());
            }

            Distances.TryGetValue(id_1, out var distance_table_1);
            Distances.TryGetValue(id_2, out var distance_table_2);

            if (!distance_table_2.TryGetValue(id_1, out var current_dist))
            {
                distance_table_2.Add(id_1, dist);
            }
            else
            {
                distance_table_2[id_1] = Math.Min(current_dist, dist);
            }


            if (!distance_table_1.TryGetValue(id_2, out current_dist))
            {
                distance_table_1.Add(id_2, dist);
            }
            else
            {
                distance_table_1[id_2] = Math.Min(current_dist, dist);
            }
        }
Esempio n. 15
0
        public Distances CellDistances()
        {
            var distances = new Distances(this);
            var frontier = new List<Cell>() { this };

            while (frontier.Count > 0)
            {
                var newFrontier = new List<Cell>();
                foreach (var cell in frontier)
                {
                    foreach (var linked in cell.Links)
                    {
                        if (!distances.ContainsKey(linked))
                        {
                            distances.Add(linked, distances[cell] + 1);
                            newFrontier.Add(linked);
                        }
                    }
                }
                frontier = newFrontier;
            }
            return distances;
        }
Esempio n. 16
0
        public long GetNextDistance()
        {
            var currentVX = CurrentV.Item1 + CurrentA.Item1;
            var currentVY = CurrentV.Item2 + CurrentA.Item2;
            var currentVZ = CurrentV.Item3 + CurrentA.Item3;

            CurrentV = new Tuple <long, long, long>(currentVX, currentVY, currentVZ);

            var currentPX = CurrentP.Item1 + CurrentV.Item1;
            var currentPY = CurrentP.Item2 + CurrentV.Item2;
            var currentPZ = CurrentP.Item3 + CurrentV.Item3;

            CurrentP = new Tuple <long, long, long>(currentPX, currentPY, currentPZ);

            var result = Math.Abs(CurrentP.Item1) + Math.Abs(CurrentP.Item2) + Math.Abs(CurrentP.Item3);

            if (result < MinValue)
            {
                MinValue = result;
            }

            Distances.Add(result);
            return(result);
        }
Esempio n. 17
0
    public Distances BFSPathTo(MazeCell goal)
    {
        Queue <MazeCell> grayQueue = new Queue <MazeCell>();

        grayQueue.Enqueue(this.startingCell);

        Distances distances = new Distances(startingCell);

        var current = startingCell;

        while (current != goal)
        {
            current = grayQueue.Dequeue();

            foreach (var linkedCell in current.Links())
            {
                if (distances.ContainsKey(linkedCell))
                {
                    continue;
                }
                if (linkedCell == goal)
                {
                    distances.Add(linkedCell, distances[current] + 1);
                    current = linkedCell;
                    break;
                }

                distances.Add(linkedCell, distances[current] + 1);

                if (grayQueue.Contains(linkedCell))
                {
                    continue;
                }
                grayQueue.Enqueue(linkedCell);
            }
        }

        Distances pathToGoal = new Distances(this.startingCell);

        pathToGoal.Add(current, distances[current]);

        while (current != startingCell)
        {
            foreach (MazeCell neighbour in current.Links())
            {
                if (distances[neighbour] < distances[current])
                {
                    if (!pathToGoal.ContainsKey(neighbour))
                    {
                        pathToGoal.Add(neighbour, distances[neighbour]);
                    }
                    else
                    {
                        pathToGoal[neighbour] = distances[neighbour];
                    }
                    current = neighbour;
                    break;
                }
            }
        }

        return(pathToGoal);
    }
Esempio n. 18
0
        public override DiscourseEntity Retain(Mention.MentionContext mention, DiscourseModel discourseModel)
        {
            if (_resolverMode == ResolverMode.Train)
            {
                DiscourseEntity discourseEntity         = null;
                var             referentFound           = false;
                var             hasReferentialCandidate = false;
                var             nonReferentFound        = false;
                for (var entityIndex = 0; entityIndex < GetNumberEntitiesBack(discourseModel); entityIndex++)
                {
                    var currentDiscourseEntity = discourseModel.GetEntity(entityIndex);
                    var entityMention          = currentDiscourseEntity.LastExtent;
                    if (IsOutOfRange(mention, currentDiscourseEntity))
                    {
                        break;
                    }
                    if (IsExcluded(mention, currentDiscourseEntity))
                    {
                        if (ShowExclusions)
                        {
                            if (mention.Id != -1 && entityMention.Id == mention.Id)
                            {
                                Console.Error.WriteLine(this + ".retain: Referent excluded: (" + mention.Id + ") " + mention.ToText() + " " + mention.IndexSpan + " -> (" + entityMention.Id + ") " + entityMention.ToText() + " " + entityMention.Span + " " + this);
                            }
                        }
                    }
                    else
                    {
                        hasReferentialCandidate = true;
                        var useAsDifferentExample = defaultReferent(currentDiscourseEntity);
                        //if (!sampleSelection || (mention.getId() != -1 && entityMention.getId() == mention.getId()) || (!nonReferentFound && useAsDifferentExample)) {
                        var features = GetFeatures(mention, currentDiscourseEntity);

                        //add Event to Model
                        if (DebugOn)
                        {
                            Console.Error.WriteLine(this + ".retain: " + mention.Id + " " + mention.ToText() + " -> " + entityMention.Id + " " + currentDiscourseEntity);
                        }
                        if (mention.Id != -1 && entityMention.Id == mention.Id)
                        {
                            referentFound = true;
                            _events.Add(new SharpEntropy.TrainingEvent(Same, features.ToArray()));
                            discourseEntity = currentDiscourseEntity;
                            Distances.Add(entityIndex);
                        }
                        else if (!PairedSampleSelection || (!nonReferentFound && useAsDifferentExample))
                        {
                            nonReferentFound = true;
                            _events.Add(new SharpEntropy.TrainingEvent(Diff, features.ToArray()));
                        }
                        //}
                    }
                    if (PairedSampleSelection && referentFound && nonReferentFound)
                    {
                        break;
                    }
                    if (PreferFirstReferent && referentFound)
                    {
                        break;
                    }
                }
                // doesn't refer to anything
                if (hasReferentialCandidate)
                {
                    NonReferentialResolver.AddEvent(mention);
                }
                return(discourseEntity);
            }
            else
            {
                return(base.Retain(mention, discourseModel));
            }
        }
Esempio n. 19
0
    public Distances BFSMeetInMiddlePathTo(MazeCell goal)
    {
        Queue <MazeCell> grayQueueWithStartingCell = new Queue <MazeCell>();
        Queue <MazeCell> grayQueueWithGoalCell     = new Queue <MazeCell>();

        grayQueueWithStartingCell.Enqueue(this.startingCell);
        grayQueueWithGoalCell.Enqueue(goal);

        Distances distancesStarting = new Distances(startingCell);
        Distances distancesGoal     = new Distances(goal);

        bool notFound = true;

        var currentCell = startingCell;

        while (notFound)
        {
            currentCell = grayQueueWithStartingCell.Dequeue();

            foreach (var linkedCell in currentCell.Links())
            {
                if (distancesGoal.ContainsKey(linkedCell))
                {
                    notFound = false;
                    if (!distancesStarting.ContainsKey(linkedCell))
                    {
                        distancesStarting.Add(linkedCell, distancesStarting[currentCell] + 1);
                    }
                    currentCell = linkedCell;
                    break;
                }

                if (distancesStarting.ContainsKey(linkedCell))
                {
                    continue;
                }
                distancesStarting.Add(linkedCell, distancesStarting[currentCell] + 1);

                if (grayQueueWithStartingCell.Contains(linkedCell))
                {
                    continue;
                }
                grayQueueWithStartingCell.Enqueue(linkedCell);
            }

            if (!notFound)
            {
                break;
            }

            currentCell = grayQueueWithGoalCell.Dequeue();

            foreach (var linkedCell in currentCell.Links())
            {
                if (distancesStarting.ContainsKey(linkedCell))
                {
                    notFound = false;
                    if (!distancesGoal.ContainsKey(linkedCell))
                    {
                        distancesGoal.Add(linkedCell, distancesGoal[currentCell] + 1);
                    }
                    currentCell = linkedCell;
                    break;
                }

                if (distancesGoal.ContainsKey(linkedCell))
                {
                    continue;
                }
                distancesGoal.Add(linkedCell, distancesGoal[currentCell] + 1);

                if (grayQueueWithGoalCell.Contains(linkedCell))
                {
                    continue;
                }
                grayQueueWithGoalCell.Enqueue(linkedCell);
            }
        }

        Distances breadcrumbs = new Distances(this.startingCell);

        breadcrumbs.Add(currentCell, distancesStarting[currentCell]);

        MazeCell breadcrumbsCurrent = currentCell;

        while (currentCell != startingCell)
        {
            foreach (MazeCell neighbour in currentCell.Links())
            {
                if (!distancesStarting.ContainsKey(neighbour))
                {
                    continue;
                }

                if (distancesStarting[neighbour] < distancesStarting[currentCell])
                {
                    if (!breadcrumbs.ContainsKey(neighbour))
                    {
                        breadcrumbs.Add(neighbour, distancesStarting[neighbour]);
                    }
                    else
                    {
                        breadcrumbs[neighbour] = distancesStarting[neighbour];
                    }

                    currentCell = neighbour;
                    break;
                }
            }
        }

        currentCell = breadcrumbsCurrent;
        Distances breadcrumbsGoal = new Distances(goal);

        while (currentCell != goal)
        {
            foreach (MazeCell neighbour in currentCell.Links())
            {
                if (!distancesGoal.ContainsKey(neighbour))
                {
                    continue;
                }

                if (distancesGoal[neighbour] < distancesGoal[currentCell])
                {
                    if (!breadcrumbsGoal.ContainsKey(neighbour))
                    {
                        breadcrumbsGoal.Add(neighbour, distancesGoal[neighbour]);
                    }
                    else
                    {
                        breadcrumbsGoal[neighbour] = distancesGoal[neighbour];
                    }

                    currentCell = neighbour;
                    break;
                }
            }
        }

        MazeCell maxCell = null;
        MazeCell minCell = null;

        int max = breadcrumbsGoal.MaxDistanceValue();
        int min = breadcrumbsGoal.MinDistanceValue();

        while (max > min)
        {
            foreach (MazeCell cell in breadcrumbsGoal.Keys)
            {
                if (breadcrumbsGoal[cell] == min)
                {
                    minCell = cell;
                }

                if (breadcrumbsGoal[cell] == max)
                {
                    maxCell = cell;
                }
            }

            breadcrumbsGoal[minCell] = max;
            breadcrumbsGoal[maxCell] = min;
            max--;
            min++;
        }

        max = breadcrumbs.MaxDistanceValue();
        max++;

        foreach (MazeCell cell in breadcrumbsGoal.Keys)
        {
            breadcrumbs.Add(cell, breadcrumbsGoal[cell] + max);
        }

        return(breadcrumbs);
    }
Esempio n. 20
0
    public Distances DFSPathTo(MazeCell goal)
    {
        Stack <MazeCell> stack = new Stack <MazeCell>();

        stack.Push(this.startingCell);

        Distances distances = new Distances(startingCell);

        var current = startingCell;

        while (current != goal)
        {
            current = stack.Peek();

            foreach (var linkedCell in current.Links())
            {
                if (distances.ContainsKey(linkedCell))
                {
                    continue;
                }
                distances.Add(linkedCell, distances[current] + 1);

                if (linkedCell == goal)
                {
                    current = linkedCell;
                    break;
                }

                if (stack.Contains(linkedCell))
                {
                    continue;
                }
                stack.Push(linkedCell);
            }
        }

        Distances breadcrumbs = new Distances(this.startingCell);

        breadcrumbs.Add(current, distances[current]);

        while (current != startingCell)
        {
            foreach (MazeCell neighbour in current.Links())
            {
                if (distances[neighbour] < distances[current])
                {
                    if (!breadcrumbs.ContainsKey(neighbour))
                    {
                        breadcrumbs.Add(neighbour, distances[neighbour]);
                    }
                    else
                    {
                        breadcrumbs[neighbour] = distances[neighbour];
                    }
                    current = neighbour;
                    break;
                }
            }
        }

        return(breadcrumbs);
    }
Esempio n. 21
0
        private void button1_Click(object sender, EventArgs e)
        {
            // это необходимо менять
            double startx       = 58.8;
            double starty       = 197;
            int    rowscount    = 31;
            int    colscount    = 9;
            double colsinterval = 86.6;
            double rowsinterval = 27.5;
            //


            pBaseEntities pb = new pBaseEntities();
            testsparam    t  = pb.testsparams.First(tp => tp.idt == (int)EnumPTests.NPNA);

            t.answersparams.Load();

            int    curransverindex = 0;
            double x = startx;

            for (int col = 0; col < colscount; col++)
            {
                double y = starty;

                for (int row = 0; row < rowscount; row++)
                {
                    if (curransverindex <= t.answerscount - 1)
                    {
                        Distances _distances = new Distances();
                        _distances.Add(_canvas.TopLeftMarker, (int)x, (int)y);
                        _distances.Add(_canvas.TopRightMarker, (int)x, (int)y);
                        _distances.Add(_canvas.BottomLeftMarker, (int)x, (int)y);
                        _distances.Add(_canvas.BottomRightMarker, (int)x, (int)y);

                        _canvas.Answers[curransverindex].Clear();
                        _canvas.Answers[curransverindex].Cells.ReMeasure(_distances, _canvas.Answers[curransverindex].InterCentresDistX, _canvas.Answers[curransverindex].CellsWidth, _canvas.Answers[curransverindex].CellsHeight);
                        _canvas.Answers[curransverindex].Select();
                        pb_img.Refresh();

                        //это комментить при подгонке
                        answersparam a = t.answersparams.First(ap => ap.num == curransverindex + 1);


                        a.toplx = (int)_distances[0].OnX;
                        a.toply = (int)_distances[0].OnY;

                        a.toprx = (int)_distances[1].OnX;
                        a.topry = (int)_distances[1].OnY;

                        a.blx = (int)_distances[2].OnX;
                        a.bly = (int)_distances[2].OnY;

                        a.brx = (int)_distances[3].OnX;
                        a.bry = (int)_distances[3].OnY;

                        pb.SaveChanges();



                        y += rowsinterval;

                        curransverindex++;
                    }
                }
                x += colsinterval;
            }
        }
Esempio n. 22
0
        private void CalculateTrip()
        {
            for (var i = 0; i < Coordinates.Count; i++)
            {
                Legs.Add(new List <DirectionSteps>());

                Distances.Add(new List <double>());

                Durations.Add(new List <double>());

                for (var j = 0; j < Coordinates.Count; j++)
                {
                    Legs[i].Add(new DirectionSteps());

                    Distances[i].Add(0);

                    Durations[i].Add(0);
                }
            }

            GetDistTable(0, 0);

            BestPath = new List <int>();

            NextSet = new List <int>();

            BestTrip = MaxTripSentry;

            var numActive = Coordinates.Count;

            var numCombos = 1 << Coordinates.Count;

            var c = new List <List <double> >();

            var parent = new List <List <int> >();

            for (var i = 0; i < numCombos; i++)
            {
                c.Add(new List <double>());

                parent.Add(new List <int>());

                for (var j = 0; j < numActive; ++j)
                {
                    c[i].Add(0.0);

                    parent[i].Add(0);
                }
            }

            int index;

            for (var k = 1; k < numActive; ++k)
            {
                index = 1 + (1 << k);

                c[index][k] = Durations[0][k];
            }

            for (var s = 3; s <= numActive; ++s)
            {
                for (var i = 0; i < numActive; ++i)
                {
                    NextSet.Add(0);
                }

                index = NextSetOf(s);

                while (index >= 0)
                {
                    for (var k = 1; k < numActive; ++k)
                    {
                        if (NextSet[k] != 0)
                        {
                            var previousIndex = index - (1 << k);

                            c[index][k] = MaxTripSentry;

                            for (var m = 1; m < numActive; ++m)
                            {
                                if (NextSet[m] != 0 && m != k)
                                {
                                    if (c[previousIndex][m] + Durations[m][k] < c[index][k])
                                    {
                                        c[index][k]      = c[previousIndex][m] + Durations[m][k];
                                        parent[index][k] = m;
                                    }
                                }
                            }
                        }
                    }
                    index = NextSetOf(s);
                }
            }

            for (var i = 0; i < numActive; ++i)
            {
                BestPath.Add(0);
            }

            index = (1 << numActive) - 1;

            var currentNode = -1;

            BestPath.Add(0);

            for (var i = 1; i < numActive; ++i)
            {
                if (c[index][i] + Durations[i][0] < BestTrip)
                {
                    BestTrip = c[index][i] + Durations[i][0];

                    currentNode = i;
                }
            }

            BestPath[numActive - 1] = currentNode;

            for (var i = numActive - 1; i > 0; --i)
            {
                currentNode = parent[index][currentNode];

                index -= 1 << BestPath[i];

                BestPath[i - 1] = currentNode;
            }
        }
Esempio n. 23
0
        private void cmd_addtest_Click(object sender, EventArgs e)
        {
            this.lst_answ.Items.Clear();
            _canvas = new Canvas((Bitmap)this.pb_img.Image, 8d);
            _canvas.RecognizeImage();
            this.pb_img.Image = _canvas.CorrectedImage;

            //KetelData td = new KetelData();
            pBaseEntities pb = new pBaseEntities();

            // modulData md = new modulData();
            // testsparam tst =  testsparam.Createtestsparam(0, "ОПРОСНИК МОДУЛЬ", 200, true);
            // for (int a = 0; a < tst.answerscount; a++)
            // {
            //     answersparam ap = answersparam.Createanswersparam(0, tst.idt, "Вопрос № " + (a + 1), 2);
            //     ap.num = a + 1;
            //     ap.buttondescription = md.answers[a].text;
            //     ap.intercellswidth = 27;
            //     ap.cellshight = 25;
            //     ap.cellswidth = 25;
            //     ap.toplx = 0;
            //     ap.toply = 0;
            //     ap.toprx = 0;
            //     ap.topry = 0;
            //     ap.blx = 0;
            //     ap.bly = 0;
            //     ap.brx = 0;
            //     ap.bry = 0;

            //     cellsparam cp = cellsparam.Createcellsparam(0, ap.ida);
            //     cp.description = "Да";
            //     cp.buttonsescription = "Да";
            //     cp.mark = md.answers[a].isYes?md.answers[a].mark:0;
            //     cellsparam cp1 = cellsparam.Createcellsparam(0, ap.ida);
            //     cp1.description = "Нет";
            //     cp1.buttonsescription = "Нет";
            //     cp1.mark = md.answers[a].isYes ? 0 : md.answers[a].mark;



            //     ap.cellsparams.Add(cp);
            //     ap.cellsparams.Add(cp1);

            //     tst.answersparams.Add(ap);


            // }

            //pb.testsparams.AddObject(tst);
            // pb.SaveChanges();



            testsparam t = pb.testsparams.First(tp => tp.idt == (int)EnumPTests.NPNA);

            t.answersparams.Load();
            IEnumerable <answersparam> answers = t.answersparams;

            foreach (answersparam ap in answers)
            {
                ListViewItem it = new ListViewItem(ap.num.ToString());
                it.SubItems.Add(ap.ida.ToString());
                it.SubItems.Add(ap.description.ToString());
                it.SubItems.Add(ap.intercellswidth.ToString());
                it.SubItems.Add(ap.cellswidth.ToString());
                it.SubItems.Add(ap.cellshight.ToString());
                it.SubItems.Add(ap.toplx.ToString());
                it.SubItems.Add(ap.toply.ToString());
                this.lst_answ.Items.Add(it);
                //добавляем вопросы на грид
                //создаем коллекцию дистанций для каждого ответа

                Distances _distances = new Distances();
                _distances.Add(_canvas.TopLeftMarker, (double)ap.toplx, (double)ap.toply);
                _distances.Add(_canvas.TopRightMarker, (double)ap.toprx, (double)ap.topry);
                _distances.Add(_canvas.BottomLeftMarker, (double)ap.blx, (double)ap.bly);
                _distances.Add(_canvas.BottomRightMarker, (double)ap.brx, (double)ap.bry);

                //_distances.Add(_canvas.TopLeftMarker, 100, 100);
                //_distances.Add(_canvas.TopRightMarker, 100, 100);
                //_distances.Add(_canvas.BottomLeftMarker, 100, 100);
                //_distances.Add(_canvas.BottomRightMarker, 100, 100);


                //создаем ответы
                Answer _answer = new Answer(_canvas.CorrectedImage, (int)ap.ida, (int)ap.cellscount, _distances, (int)ap.intercellswidth, (int)ap.cellswidth, (int)ap.cellshight);
                _answer.Select();
                _canvas.Answers.Add(_answer);
            }
        }
Esempio n. 24
0
        public void Dijkstra(string start, string end)
        {
            //Initial State
            foreach (var node in Vertexes.Values)
            {
                if (node.Name == start)
                {
                    Distances.Add(new NodeDistance(node.Name, 0));
                    PriorityQueue.Add(new NodePriority(node.Name, 0));
                }
                else
                {
                    Distances.Add(new NodeDistance(node.Name, int.MaxValue));
                    PriorityQueue.Add(new NodePriority(node.Name, int.MaxValue));
                }
                PathSteps.Add(new PathStep(node.Name, null));
            }
            PriorityQueue.Sort((x, y) => x.Priority.CompareTo(y.Priority));
            //As long as there's smth to visit
            while (PriorityQueue.Count > 0)
            {
                var lowest = PriorityQueue[0].Node;
                PriorityQueue.RemoveAt(0);
                if (lowest == end)
                {
                    //We're DONE;
                    Console.WriteLine("Distances");
                    foreach (var item in Distances)
                    {
                        Console.WriteLine(item.Node + ":" + item.Distance);
                    }
                    Console.WriteLine("PathSteps:");
                    foreach (var pathstep in PathSteps)
                    {
                        Console.WriteLine(pathstep.Location + ":" + pathstep.PreviousStep);
                    }
                    var path = PrintShortestPath(end, start, "");
                    //path.Reverse();
                    Console.WriteLine($"Shortest path from {start} to {end} is: {end}<--{path}");
                    break;
                }
                ;
                if (lowest != null || Distances
                    .Where(x => x.Node == lowest)
                    .Select(x => x.Distance)
                    .FirstOrDefault() != int.MaxValue)
                {
                    foreach (var neighbor in Vertexes[lowest].Edges)
                    {
                        //Find neighboring nodes
                        var index    = Vertexes[lowest].Edges.IndexOf(neighbor);
                        var nextNode = Vertexes[lowest].Edges[index];
                        //calculate new distance to neighboring node
                        var candidate    = Distances.Where(x => x.Node == lowest).FirstOrDefault();
                        var addDistance  = candidate.Distance + nextNode.Distance;
                        var nextNeighbor = nextNode.Node;
                        if (addDistance < Distances.Where(x => x.Node == nextNeighbor).Select(x => x.Distance).FirstOrDefault())
                        {
                            var oldDistance = Distances.Where(x => x.Node == nextNeighbor).FirstOrDefault();
                            //updating new smallest distance to neighbor
                            var newDistance = new NodeDistance(oldDistance.Node, addDistance);
                            Distances.Remove(oldDistance);
                            Distances.Add(newDistance);
                            //update PathSteps - how we got to neighbor
                            var previous        = PathSteps.Where(x => x.Location == oldDistance.Node).FirstOrDefault();
                            var newPreviousPair = new PathStep(previous.Location, lowest);
                            PathSteps.Remove(previous);
                            PathSteps.Add(newPreviousPair);
                            //update the priority queue
                            var oldPriority = PriorityQueue.Where(x => x.Node == nextNeighbor).FirstOrDefault();
                            var newPriority = new NodePriority(nextNeighbor, addDistance);
                            PriorityQueue.Remove(oldPriority);
                            PriorityQueue.Add(newPriority);

                            PriorityQueue.Sort((x, y) => x.Priority.CompareTo(y.Priority));
                        }
                    }
                }
            }
        }
Esempio n. 25
0
        public override DiscourseEntity Retain(Mention.MentionContext mention, DiscourseModel discourseModel)
        {
            //System.err.println(this+".retain("+ec+") "+mode);
            if (mResolverMode == ResolverMode.Train)
            {
                DiscourseEntity discourseEntity         = null;
                bool            referentFound           = false;
                bool            hasReferentialCandidate = false;
                bool            nonReferentFound        = false;
                for (int entityIndex = 0; entityIndex < GetNumberEntitiesBack(discourseModel); entityIndex++)
                {
                    DiscourseEntity        currentDiscourseEntity = discourseModel.GetEntity(entityIndex);
                    Mention.MentionContext entityMention          = currentDiscourseEntity.LastExtent;
                    if (IsOutOfRange(mention, currentDiscourseEntity))
                    {
                        if (mention.Id != -1 && !referentFound)
                        {
                            //System.err.println("retain: Referent out of range: "+ec.toText()+" "+ec.parse.getSpan());
                        }
                        break;
                    }
                    if (IsExcluded(mention, currentDiscourseEntity))
                    {
                        if (ShowExclusions)
                        {
                            if (mention.Id != -1 && entityMention.Id == mention.Id)
                            {
                                System.Console.Error.WriteLine(this + ".retain: Referent excluded: (" + mention.Id + ") " + mention.ToText() + " " + mention.IndexSpan + " -> (" + entityMention.Id + ") " + entityMention.ToText() + " " + entityMention.Span + " " + this);
                            }
                        }
                    }
                    else
                    {
                        hasReferentialCandidate = true;
                        bool useAsDifferentExample = defaultReferent(currentDiscourseEntity);
                        //if (!sampleSelection || (mention.getId() != -1 && entityMention.getId() == mention.getId()) || (!nonReferentFound && useAsDifferentExample)) {
                        List <string> features = GetFeatures(mention, currentDiscourseEntity);

                        //add Event to Model
                        if (mDebugOn)
                        {
                            System.Console.Error.WriteLine(this + ".retain: " + mention.Id + " " + mention.ToText() + " -> " + entityMention.Id + " " + currentDiscourseEntity);
                        }
                        if (mention.Id != -1 && entityMention.Id == mention.Id)
                        {
                            referentFound = true;
                            mEvents.Add(new SharpEntropy.TrainingEvent(Same, features.ToArray()));
                            discourseEntity = currentDiscourseEntity;
                            //System.err.println("MaxentResolver.retain: resolved at "+ei);
                            Distances.Add(entityIndex);
                        }
                        else if (!mPairedSampleSelection || (!nonReferentFound && useAsDifferentExample))
                        {
                            nonReferentFound = true;
                            mEvents.Add(new SharpEntropy.TrainingEvent(Diff, features.ToArray()));
                        }
                        //}
                    }
                    if (mPairedSampleSelection && referentFound && nonReferentFound)
                    {
                        break;
                    }
                    if (mPreferFirstReferent && referentFound)
                    {
                        break;
                    }
                }
                // doesn't refer to anything
                if (hasReferentialCandidate)
                {
                    mNonReferentialResolver.AddEvent(mention);
                }
                return(discourseEntity);
            }
            else
            {
                return(base.Retain(mention, discourseModel));
            }
        }
Esempio n. 26
0
        private void CalculateTrip()
        {
            for (int i = 0; i < Coordinates.Count; i++)
            {
                Legs.Add(new List <DirectionSteps>());

                Distances.Add(new List <double>());

                Durations.Add(new List <double>());

                for (int j = 0; j < Coordinates.Count; j++)
                {
                    Legs[i].Add(new DirectionSteps());

                    Distances[i].Add(0);

                    Durations[i].Add(0);
                }
            }

            GetDistTable(0, 0);

            BestPath = new List <int>();

            double minDistance = -1;

            for (int i = 1; i < Coordinates.Count; i++)
            {
                List <int> coordinatesIndex = new List <int>();

                for (int j = 1; (j < Coordinates.Count); j++)
                {
                    if (j == i)
                    {
                        continue;
                    }
                    coordinatesIndex.Add(j);
                }
                var coordinatesIndexPermutation = GetPermutations(coordinatesIndex, coordinatesIndex.Count);

                List <List <int> > listCoordinatesIndexPermutationComplete = new List <List <int> >();

                foreach (var coordinateIndexPermutation in coordinatesIndexPermutation)
                {
                    var coordinateIndexPermutationTemp = new List <int> {
                        0
                    };

                    coordinateIndexPermutationTemp.AddRange(coordinateIndexPermutation);

                    coordinateIndexPermutationTemp.Add(i);

                    listCoordinatesIndexPermutationComplete.Add(coordinateIndexPermutationTemp);
                }

                // get min
                foreach (var coordinatesIndexPermutationComplete in listCoordinatesIndexPermutationComplete)
                {
                    double pathDistance = 0;

                    for (int j = 0; j < coordinatesIndexPermutationComplete.Count - 1; j++)
                    {
                        pathDistance += Distances[coordinatesIndexPermutationComplete[j]][coordinatesIndexPermutationComplete[j + 1]];
                    }

                    if (minDistance < 0 || pathDistance < minDistance)
                    {
                        BestPath    = coordinatesIndexPermutationComplete;
                        minDistance = pathDistance;
                    }
                }
            }
            // get min of results is best path
        }