Exemplo n.º 1
0
 private Graph.Graph CreateGraph()
 {
     Graph.Graph graph = new Graph.Graph();
     graph.Places.AddRange(_places);
     graph.ChosenPlaces.AddRange(_places);
     return(graph);
 }
        public override bool Execute(AccessibleQueryStatement query, Graph.Graph graph, HistoryStatement history)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            query.StateFromCondition = query.StateFromCondition ?? graph.GetStartCondition(history);
            var startVertices = graph.Vertexes.FindVerticesSatisfyingCondition(query.StateFromCondition).ToList();

            startVertices = BuildGraph(startVertices, graph, history).ToList();

            switch (query.Sufficiency)
            {
            case Sufficiency.Necessary:
                return(ExecuteNecessarySufficiency(startVertices, query.StateToCondition));

            case Sufficiency.Possibly:
                return(ExecutePossiblySufficiency(startVertices, query.StateToCondition));

            case Sufficiency.Typically:
                return(ExecuteTypicallySufficiency(startVertices, query.StateToCondition));

            default:
                throw new InvalidOperationException();
            }
            return(false);
        }
Exemplo n.º 3
0
 public DijkstraAlgorithm(Graph.Graph g)
 {
     this.g            = g;
     priority          = new PriorityQueue <double, string>();
     ShortestPathNodes = new List <INode>();
     marked            = new Dictionary <string, string>();
 }
Exemplo n.º 4
0
        /// <summary>
        /// Возвращает список всех путей от одной вершины до другой
        /// </summary>
        /// <param name="graph">Граф</param>
        /// <param name="start">Имя начальной вершина</param>
        /// <param name="end">Имя конечной вершина</param>
        /// <returns>Список путей; путь - список вершин</returns>
        public IReadOnlyList <IReadOnlyList <Vertex> > FindAllPathes(Graph.Graph graph, string start, string end)
        {
            Vertex startVertex = graph.GetVertex(start);
            Vertex endVertex   = graph.GetVertex(end);

            return(FindAllPathes(graph, startVertex, endVertex));
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            /*int[,] matrix = {
             *  { 0, 1, 0, 0, 0, 1, 1},
             *  { 1, 0, 0, 1, 1, 1, 0},
             *  { 0, 0, 0, 1, 0, 0, 1},
             *  { 0, 1, 1, 0, 1, 0, 0},
             *  { 0, 1, 0, 1, 0, 0, 0},
             *  { 1, 1, 0, 0, 0, 0, 0},
             *  { 1, 0, 1, 0, 0, 0, 0}
             * }; */

            int[,] matrix =
            {
                { 0, 1, 0, 0, 0, 1, 1 },
                { 1, 0, 0, 0, 1, 1, 0 },
                { 0, 0, 0, 0, 0, 0, 0 },
                { 0, 0, 0, 0, 0, 0, 0 },
                { 0, 1, 0, 0, 0, 0, 0 },
                { 1, 1, 0, 0, 0, 0, 0 },
                { 1, 0, 0, 0, 0, 0, 0 }
            };

            Graph.Graph graph = new Graph.Graph(matrix);

            graph.BreadthTraversal(Console.WriteLine);
        }
Exemplo n.º 6
0
        public void AStarSameOriginAndDestination()
        {
            bool error = false;

            try
            {
                var list = CreatePointList();
                Graph.Graph <GameObject> graph = new Graph.Graph <GameObject>();
                graph.AddNodes(list);
                int[] indices = new int[graph.Nodes.Count * 2];
                for (int i = 0; i < graph.Nodes.Count * 2; i += 2)
                {
                    indices[i]     = Random.Range(0, graph.Nodes.Count);
                    indices[i + 1] = Random.Range(0, graph.Nodes.Count);
                }
                graph.CreateEdges(indices, (c, d) => Vector3.Distance(c.transform.position, d.transform.position));
                graph.CalculateHeuristics(graph.Nodes[0].Item, (c, d) => Vector3.Distance(c.transform.position, d.transform.position));
                var path = graph.AStar(0, 0);
            }
            catch
            {
                error = true;
            }

            Assert.IsFalse(error);
        }
Exemplo n.º 7
0
        private static void AddChosenPlaces(Graph.Graph graph, bool isGiven = false)
        {
            if (isGiven)
            {
                foreach (var ln in _data3)
                {
                    List <String> id = ln.Split("|").ToList();

                    Place place = graph.Places.Find(item => item.Id.Equals(id[1].Replace(" ", "")));
                    if (graph.ChosenPlaces.Exists(item => item.Equals(place)))
                    {
                        throw new IOException($"Cannot choose place twice {ln}");
                    }
                    if (place == null)
                    {
                        throw new IOException($"Cannot choose place that not exist {ln}");
                    }

                    graph.AddChosenPlace(place);
                }
            }
            else
            {
                graph.ChosenPlaces.AddRange(graph.Places);
            }
        }
Exemplo n.º 8
0
        public Tensor[] Step(Graph.Graph f, Tensor[] x, bool reverse = false)
        {
            var res   = new Tensor[x.Length];
            var cells = new Tensor[x.Length];
            var c     = new Tensor(1, _bc.Col, true);
            var h     = new Tensor(1, _bo.Col, true);

            if (reverse)
            {
                for (var i = x.Length - 1; i >= 0; i--)
                {
                    res[i] = Step(f, x[i], c, h, out cells[i]);
                    h      = res[i];
                    c      = cells[i];
                }
            }
            else
            {
                for (var i = 0; i < x.Length; i++)
                {
                    res[i] = Step(f, x[i], c, h, out cells[i]);
                    h      = res[i];
                    c      = cells[i];
                }
            }
            return(res);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Implementation of a BFS algorithm for a given starting node.
        /// This doesn't work with a destination node, but rather returns
        /// the whole "reachability graph".
        /// </summary>
        /// <param name="startingNode">The node from which to get the reachability graph</param>
        /// <returns>The reachability graph from the node given</returns>
        private Graph.Graph Bfs(INode startingNode)
        {
            var visited = new Dictionary <INode, bool>();
            var queue   = new Queue <INode>();

            visited[startingNode] = true;

            var graph = new Graph.Graph();

            queue.Enqueue(startingNode);

            while (queue.Count > 0)
            {
                var node = queue.Dequeue();
                graph.AddNode(node);
                graph.AddEdges(node.GetOutwardsEdges());

                foreach (var child in node.GetChilds())
                {
                    if (child == null)
                    {
                        continue;
                    }

                    if (visited.ContainsKey(child))
                    {
                        continue;
                    }
                    queue.Enqueue(child);
                    visited[child] = true;
                }
            }

            return(graph);
        }
Exemplo n.º 10
0
        void Start()
        {
            // Load the graph..
            string filePath = Application.streamingAssetsPath + "/Examples/NewWorld.json";

            Graph.Graph graph = Launcher.Instance.LoadGraph(filePath);

            if (graph == null)
            {
                Log.Error("Can not find graph file " + filePath);
                return;
            }

            // Get the chunk generator node..
            graph.ForceUpdateNodes();
            _chunkGenerator = (ChunkGeneratorNode)graph.GetFirstNodeWithType(typeof(ChunkGeneratorNode));

            if (_chunkGenerator == null)
            {
                Log.Error("Can not find a chunk generator node in the graph.");
            }

            // Get the main camera.
            _camera = GameObject.Find("Main Camera");
            if (_camera == null)
            {
                Log.Error("Can not camera with the name 'Main Camera'.");
                return;
            }

            _camera.AddComponent <KeyboardControls>();
        }
        private static IEnumerable <Vertex> ApplyNotInitiallyValueStatements(Graph.Graph graph, HistoryStatement history, IEnumerable <Vertex> vertices)
        {
            foreach (var val in history.Values.Where(x => x.Actions.Count != 0))
            {
                var valuePaths = vertices.SelectMany(x => x.EdgesOutgoing);
                for (int i = 0; i < val.Actions.Count - 1; i++)
                {
                    // wybranie wszystkich krawędzi odpowiadajacych danej parze (actor, action) z value staatement
                    valuePaths = valuePaths.Where(y => y.Action == val.Actions[i].Action && y.Actor == val.Actions[i].Agent).Select(x => x.To)
                                 .SelectMany(x => x.EdgesOutgoing);
                    if (valuePaths.Count() == 0)
                    {
                        break;
                    }
                }
                // krawędzie spełniajace warunek ostatniej pary (actor, action) z value staatement
                valuePaths = valuePaths.Where(y => y.Action == val.Actions[val.Actions.Count - 1].Action && y.Actor == val.Actions[val.Actions.Count - 1].Agent);

                var edgeList = valuePaths.ToList();
                for (int i = 0; i < edgeList.Count; i++)
                {
                    // znalezienie wierzchołka, do którego przeniesiemy się po zaaplikowaniu value statements
                    var vertexState = edgeList[i].To.State.Values.ToDictionary(x => x.Key, x => x.Value);
                    foreach (var fluent in val.Condition.ExtractFluentsValues())
                    {
                        vertexState[fluent.Key] = fluent.Value;
                    }
                    var vertexEvaluatingValueStatement = graph.Vertexes.Where(v => v.State.Values.All(x => vertexState[x.Key] == x.Value)).ToList();
                    if (vertexEvaluatingValueStatement.Count > 1)
                    {
                        throw new InvalidOperationException("vertexEvaluatingValueStatement length is grater than 1.");
                    }

                    // sprawdzić czy wszystkie drogi prowadzące do wierzchołka spełniają value statement
                    // TODO
                    if (edgeList[i].To.EdgesIncoming.All(x => valuePaths.Contains(x)) && val.IsObservable == false)
                    {
                        edgeList[i].To = vertexEvaluatingValueStatement.First();
                    }
                    else
                    {
                        vertexEvaluatingValueStatement.ForEach(
                            x =>
                        {
                            var actionEdge = edgeList[i].From.EdgesOutgoing.FirstOrDefault(
                                y => y.IsTypical == edgeList[i].IsTypical && edgeList[i].Action == y.Action && edgeList[i].Actor == y.Actor);
                            if (actionEdge == null)
                            {
                                edgeList[i].From.EdgesOutgoing.Add(new Edge(edgeList[i].From, x, edgeList[i].IsTypical, edgeList[i].Action, edgeList[i].Actor));
                            }
                            else
                            {
                                actionEdge.To = x;
                            }
                        });
                    }
                }
            }
            return(vertices);
        }
Exemplo n.º 12
0
        public void FindNoPathTest()
        {
            Graph.Graph graph    = CreateGraph();
            Dijkstra    dijkstra = new Dijkstra(graph);
            Path        path     = dijkstra.FindPath(_places[0], _places[0]);

            Assert.Null(path);
        }
Exemplo n.º 13
0
 public Genetic(int generationNumber, int populationSize, Graph.Graph graph)
 {
     _graph            = graph;
     _random           = new Random();
     _allPaths         = new AllPaths(graph);
     _generationNumber = generationNumber;
     _populationSize   = populationSize;
 }
Exemplo n.º 14
0
 private static void AddPlace(Graph.Graph graph)
 {
     foreach (var ln in _data1)
     {
         List <String> data = ln.Split("|").ToList();
         graph.AddPlace(new Place((data[1].Replace(" ", "")), data[2]));
     }
 }
Exemplo n.º 15
0
        public static String RelayGraphProperties(Graph.Graph g)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("The Graph shown " + g.LABEL);
            sb.Append(" has " + g.AllEdges.Count.ToString() + " total edges and " + g.AllNodes.Count.ToString() + " total nodes. ");
            return(sb.ToString());
        }
Exemplo n.º 16
0
 public DashboardItem(int id, int column, int row, int x_Size, int y_Size, Graph.Graph graph)
 {
     Id     = id;
     Column = column;
     Row    = row;
     X_Size = x_Size;
     Y_Size = y_Size;
     Graph  = graph;
 }
Exemplo n.º 17
0
        private void UpdateGenUnitsGraphIndex(Graph.Graph graph, int newId)
        {
            var list = GetGenUnitsOnGraph(graph);

            foreach (var genUnit in list)
            {
                genUnit.Graphid = newId;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Adds the specified road to this map. This also modifies the underlying graph structures
        /// </summary>
        /// <param name="road"></param>
        public void AddRoad(Road road)
        {
            mRoads.AddLast(road);

            // first check if two graphs got connected.
            // because we need to differ between road connected two graphs, or road was added to one graph only

            if (((PlatformBlank)road.GetChild()).Friendly && ((PlatformBlank)road.GetParent()).Friendly)
            {
                if (mPlatformToGraphId[(PlatformBlank)road.GetChild()] !=
                    mPlatformToGraphId[(PlatformBlank)road.GetParent()])
                {
                    var childIndex  = mPlatformToGraphId[(PlatformBlank)road.GetChild()];
                    var parentIndex = mPlatformToGraphId[(PlatformBlank)road.GetParent()];

                    // since the graphes will get connected by this road, we first
                    // get all the nodes and edges from both graphes
                    var connectGraphNodes = mGraphIdToGraph[childIndex].GetNodes()
                                            .Concat(mGraphIdToGraph[parentIndex].GetNodes()).ToList();

                    var connectGraphEdges = mGraphIdToGraph[childIndex].GetEdges()
                                            .Concat(mGraphIdToGraph[parentIndex].GetEdges()).ToList();

                    // don't forget to add the current road to the graph aswell
                    connectGraphEdges.Add(road);

                    foreach (var node in connectGraphNodes)
                    {
                        // now we update our dictionary, such that all nodes formerly in the graph
                        // of the node road.GetChild() are now in the parent nodes graph.
                        // this is "arbitrary", we could also do it the other way around
                        mPlatformToGraphId[(PlatformBlank)node] = parentIndex;
                        ((PlatformBlank)node).SetGraphIndex(parentIndex);
                    }

                    // now we create the actual connected graph
                    var graph = new Graph.Graph(connectGraphNodes, connectGraphEdges);

                    // the only thing left is to update the two former graph references
                    // and add the new graph
                    mGraphIdToGraph[childIndex]  = null;
                    mGraphIdToGraph[parentIndex] = graph;

                    UpdateGenUnitsGraphIndex(mGraphIdToGraph[parentIndex], parentIndex);
                    mGraphIdToEnergyLevel[childIndex] = 0;

                    mDirector.GetDistributionDirector.MergeManagers(childIndex, parentIndex, parentIndex);
                    mDirector.GetPathManager.RemoveGraph(childIndex);
                    mDirector.GetPathManager.AddGraph(parentIndex, graph);
                    return;
                }


                // the road was in the same graph, thus just add it to the graph
                mGraphIdToGraph[mPlatformToGraphId[(PlatformBlank)road.GetChild()]].AddEdge(road);
            }
        }
Exemplo n.º 19
0
 public IAlgorithm<IList<IVertex>> GetAlgorithm(Parameters parameters)
 {
     var antFactory = new AntFactory();
     var prober = new Prober(parameters.Alpha, parameters.Betta);
     IGraph graph = new Graph.Graph(parameters.Matrix);
     var algorithm = new GreedyAlgorithm(antFactory, prober, parameters.IterationsWithoutChanges,
         parameters.Iterations, parameters.EvaporationRate, parameters.DefaultPheromone, parameters.GreedyRate, graph, parameters.Q);
     return algorithm;
 }
        public static GraphEdgeBinaryChromosome CreateRandom(Graph.Graph graph, IRandomization randomization)
        {
            IEnumerable <EdgeBinaryGene> genes = graph.Edges.Select(e => new EdgeBinaryGene(randomization.NextBoolean(), e))
                                                 .ToList();

            Graph.Graph chromosomeGraph = new Graph.Graph(graph.Vertices, genes.Where(g => g.Value).Select(g => g.Edge));

            return(new GraphEdgeBinaryChromosome(genes, chromosomeGraph.GetConnectedComponents()));
        }
Exemplo n.º 21
0
 public Map(int mapSize)
 {
     //TODO: randomize choice of rooms
     String[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "Levels\\", "*.cmap");
     generateMap(files, this, mapSize);
     state = MapState.Enter;
     UIManager.Instance.Fade = true;
     graph = new Graph.Graph(mapSize * mapSize, 64, 64);
 }
Exemplo n.º 22
0
        public void DoesNotAllowDuplicates()
        {
            var list = CreatePointList();

            list.Add(list[0]);
            Graph.Graph <GameObject> graph = new Graph.Graph <GameObject>();
            graph.AddNodes(list);

            Assert.IsTrue(graph.FindAllNodes(n => n.Item == list[0]).Count == 1);
        }
Exemplo n.º 23
0
        // i(t) = sigmoid(W(i)*x(t) + U(i)*h(t-1))             input gate
        // f(t) = sigmoid(W(f)*x(t) + U(f)*h(t-1))             forget gate
        // o(t) = sigmoid(W(o)*x(t) + U(o)*h(t-1))             output exposure gate
        // c tilde(t) = tanh(W(c)*x(t) + U(c)*h(t-1))          new memory cell
        // c(t) = f(t).*c tilde(t-1) + i(t).*c tilde(t)        final memory cell
        // h(t) = o(t).*tanh(c(t))
        public Tensor Step(Graph.Graph f, Tensor x, Tensor h)
        {
            // input gate
            var inputGate = f.Sigmoid(f.AddBias(f.Add(f.Multiply(x, _wix), f.Multiply(h, _wih)), _bi));
            // forget gate
            var forgetGate = f.Sigmoid(f.AddBias(f.Add(f.Multiply(x, _wfx), f.Multiply(h, _wfh)), _bf));
            var newInput   = f.Tanh(f.Multiply(x, _wcx));

            return(f.Add(f.ElementwiseMultiply(inputGate, newInput), f.ElementwiseMultiply(forgetGate, f.Tanh(h))));
        }
        void Start()
        {
            // create the graph
            Graph.Graph graph = new Graph.Graph();

            // create an operator node
            var operator01 = (NumberOperatorNode)graph.CreateNode <NumberOperatorNode>();

            operator01.X = 200;
            operator01.Y = 40;
            operator01.SetMode(Operator.Add);
            graph.AddNode(operator01);

            // create a display node
            var diplay01 = (NumberDisplayNode)graph.CreateNode <NumberDisplayNode>();

            diplay01.X = 330;
            diplay01.Y = 80;
            graph.AddNode(diplay01);

            // link the nodes
            graph.Link(
                (InputSocket)diplay01.GetSocket(typeof(INumberConnection), typeof(InputSocket), 0),
                (OutputSocket)operator01.GetSocket(typeof(INumberConnection), typeof(OutputSocket), 0));

            // cerate a perlin noise node
            var perlinNoise = graph.CreateNode <UnityPerlinNoiseNode>();

            perlinNoise.X = 80;
            perlinNoise.Y = 250;
            graph.AddNode(perlinNoise);

            // create a display map node
            var displayMap = graph.CreateNode <DisplayMapNode>();

            displayMap.X = 300;
            displayMap.Y = 280;
            graph.AddNode(displayMap);

            // link the nodes
            graph.Link(
                (InputSocket)displayMap.GetSocket(typeof(INumberConnection), typeof(InputSocket), 0),
                (OutputSocket)perlinNoise.GetSocket(typeof(INumberConnection), typeof(OutputSocket), 0));


            // to test the serialization...

            // create a json out of the graph
            var serializedJSON = graph.ToJson();
            // dezeiralize the json back to a graph
            var deserializedGraph = Graph.Graph.FromJson(serializedJSON);

            // add the graph to the launcher to see it in the editor.
            Launcher.Instance.AddGraph(deserializedGraph);
        }
Exemplo n.º 25
0
 private Graph.Graph CreateGraph()
 {
     Graph.Graph graph = new Graph.Graph();
     graph.Places.AddRange(_places);
     graph.ChosenPlaces.AddRange(_places);
     graph.AddEdge("A", "B", new[] { "1", "00" }, "0");
     graph.AddEdge("A", "C", new[] { "4", "00" }, "0");
     graph.AddEdge("B", "C", new[] { "1", "00" }, "0");
     graph.AddEdge("C", "D", new[] { "1", "00" }, "0");
     return(graph);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Path creating and setting first location
        /// Lobby tells cleaner that there is a place to clean so based on that cleaner will get a destination to walk to and to clean
        /// </summary>
        /// <param name="destination"></param>
        /// <returns></returns>
        public List <Node> CreateGraph(LocationType destination)
        {
            Destination = destination;
            // Cleaner creates his path andreturns it
            Graph.Graph graph = new Graph.Graph();
            Path = graph.CreateNodeGraph(Location.LocationType, Destination, PathFinding, CurrentEvent.EventType);

            // if visitor changes his mind, he's steps will be reset. Step 0 is his location where he stands on, we don't want him to walk to that place
            NextStep = 1;
            return(Path);
        }
Exemplo n.º 27
0
        public void FindPathTest()
        {
            Graph.Graph graph    = CreateGraph();
            Dijkstra    dijkstra = new Dijkstra(graph);
            Path        path     = dijkstra.FindPath(_places[0], _places[3]);

            Assert.AreEqual(3, path.TotalLength.Hours);
            Assert.AreEqual("A", path.Steps[0].StartPlace.Id);
            Assert.AreEqual("B", path.Steps[1].StartPlace.Id);
            Assert.AreEqual("C", path.Steps[2].StartPlace.Id);
            Assert.AreEqual("D", path.Steps[2].EndPlace.Id);
        }
Exemplo n.º 28
0
        public Tensor[] Step(Graph.Graph f, Tensor[] x)
        {
            var res = new Tensor[x.Length];
            var h   = new Tensor(1, _bh.Col, true);

            for (var i = 0; i < x.Length; i++)
            {
                res[i] = Step(f, x[i], h);
                h      = res[i];
            }
            return(res);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Finds the shortest path with the A* Algorithm
        /// </summary>
        /// <param name="g">the graph</param>
        /// <param name="start">the start node</param>
        /// <param name="end">the end node</param>
        /// <returns>A route with the shortest path</returns>
        public static Route FindShortestPath(Graph.Graph g, Node start, Node end)
        {
            List <Node> closedList = new List <Node>();
            List <Node> openList   = new List <Node>();

            openList.Add(start);

            foreach (Node n in g.Nodes)
            {
                n.DistanceToStartNode = double.MaxValue;
                n.DistanceToEnd       = double.MaxValue;
            }

            start.DistanceToStartNode = 0;
            start.DistanceToEnd       = CalcHeuristicCost(start, end);

            while (openList.Count > 0)
            {
                Node current = GetNodeWithLowestDistanceToEnd(openList);
                if (current != null && current == end)
                {
                    return(new Route(start, end));
                }

                openList.Remove(current);
                closedList.Add(current);
                foreach (Node neighbor in current.GetNeighbours())
                {
                    if (closedList.Contains(neighbor))
                    {
                        continue;
                    }

                    double suggestedDistanceFromStartToCurrent = current.DistanceToStartNode +
                                                                 current.GetWeightToNeighbour(neighbor);

                    if (!openList.Contains(neighbor))
                    {
                        openList.Add(neighbor);
                    }
                    else if (suggestedDistanceFromStartToCurrent >= neighbor.DistanceToStartNode)
                    {
                        continue;
                    }

                    neighbor.PreviousNode        = current;
                    neighbor.DistanceToStartNode = suggestedDistanceFromStartToCurrent;
                    neighbor.DistanceToEnd       = neighbor.DistanceToStartNode + CalcHeuristicCost(neighbor, end);
                }
            }
            return(null);
        }
Exemplo n.º 30
0
        public ComputationGraph(Graph.Graph graph, IPathFinder pathFinder, Vertex startVertex, Vertex endVertex)
        {
            _pathes = new List <List <DestroyableElement> >();
            _units  = new Dictionary <IGraphUnit, DestroyableElement>();


            // Заполняем словарь элементами
            foreach (var vertex in graph.Vertex)
            {
                _units.Add(vertex, new DestroyableElement(vertex));

                foreach (var edge in vertex.Edges)
                {
                    if (!_units.ContainsKey(edge))
                    {
                        _units.Add(edge, new DestroyableElement(edge));
                    }
                }
            }

            Pathes = pathFinder.FindAllPathes(graph, startVertex, endVertex);

            // На основе путей, составляем пути из DestroyableElements, так же добавляя
            // ребра между вершинами, потому что они тоже могут отказывать
            foreach (var path in Pathes)
            {
                var dPath = new List <DestroyableElement>();

                for (int i = 0; i < path.Count - 1; i++)
                {
                    var v1   = path[i];
                    var v2   = path[i + 1];
                    var edge = graph.GetEdge(v1, v2);   // Ребро гарантированно существует

                    var vUnit = _units[v1];
                    var vEdge = _units[edge];

                    vUnit.EncountsCount++;
                    vEdge.EncountsCount++;

                    dPath.Add(vUnit);
                    dPath.Add(vEdge);
                }

                // Добавляем последнюю вершину
                var unit = _units[path[path.Count - 1]];
                unit.EncountsCount++;
                dPath.Add(unit);

                _pathes.Add(dPath);
            }
        }
Exemplo n.º 31
0
        private static void AddEdge(Graph.Graph graph)
        {
            foreach (var ln in _data2)
            {
                List <String> data = ln.Split("|").ToList();
                graph.AddEdge(data[1].Replace(" ", ""), data[2].Replace(" ", ""), data[3].Split(":"), data[5]);

                if (!data[4].Equals("0:00"))
                {
                    graph.AddEdge(data[2].Replace(" ", ""), data[1].Replace(" ", ""), data[4].Split(":"), data[5]);
                }
            }
        }
Exemplo n.º 32
0
 /// <summary>
 /// Create a path.
 /// </summary>
 /// <param name="graph">The graph this path is through.</param>
 /// <param name="steps">The edges.</param>
 public Path(Graph.Graph graph, Edge[] steps)
 {
     this.graph = graph;
     this.steps = steps;
 }