Example #1
0
        private void AddPortalsForLevel(BidirectionalGraph <Point, Edge <Point> > graph, HashSet <Portal> portals, int level)
        {
            foreach (var portalPair in portals.GroupBy(p => p.Name).Where(g => g.Count() == 2))
            {
                var pair = portalPair.ToArray();

                var outerPortal = portalPair.First(p => p.IsOuter);
                var innerPortal = portalPair.First(p => !p.IsOuter);

                // Connect the inner portal to the next level and the outer portal to to previous level.

                // Connect the inner portal at the level above this level to the outer portal at this level.
                var innerPortalSource = GetPointForLevel(innerPortal.MapLocation, level - 1);
                var innerPortalTarget = GetPointForLevel(outerPortal.MapLocation, level);

                if (graph.ContainsVertex(innerPortalSource) && graph.ContainsVertex(innerPortalTarget))
                {
                    var edge = new Edge <Point>(innerPortalSource, innerPortalTarget);
                    graph.AddEdge(edge);
                    graph.AddEdge(edge.Reverse);
                }

                // Connect the outer portal at this level to the inner portal at the level below this.
                var outerPortalSource = GetPointForLevel(outerPortal.MapLocation, level);
                var outerPortalTarget = GetPointForLevel(innerPortal.MapLocation, level + 1);

                if (graph.ContainsVertex(outerPortalSource) && graph.ContainsVertex(outerPortalTarget))
                {
                    var edge = new Edge <Point>(outerPortalSource, outerPortalTarget);
                    graph.AddEdge(edge);
                    graph.AddEdge(edge.Reverse);
                }
            }
        }
Example #2
0
        public BidirectionalGraph <Point, Edge <Point> > BuildDoorGraph(Point location)
        {
            var graph        = new BidirectionalGraph <Point, Edge <Point> >();
            var keysUnlocked = new Dictionary <char, List <char> >();

            var reachablePoints = ReachablePoints(location).ToArray();
            var doorsReachable  = reachablePoints.Where(p => _doors.ContainsKey(p)).ToArray();

            foreach (var source in doorsReachable)
            {
                // Connect them together.
                foreach (var target in doorsReachable)
                {
                    if (source != target)
                    {
                        if (!graph.ContainsVertex(source))
                        {
                            graph.AddVertex(source);
                        }

                        if (!graph.ContainsVertex(target))
                        {
                            graph.AddVertex(target);
                        }

                        graph.AddEdge(new Edge <Point>(source, target));
                    }
                }
            }

            return(graph);
        }
        /// <summary>
        /// Retourne True si une sortie d'un component1 à une sortie d'un component2 ont été reliées, et si c'est le cas mettre à jour les input/output
        /// </summary>
        /// <param name="component1">Le composant qui comporte le input/output sortie</param>
        /// <param name="component2">Le composant qui comporte le input/output entree</param>
        /// <param name="sortie">La sortie à relier</param>
        /// <param name="entree">L'entrée à relier</param>
        /// <returns></returns>
        public bool Relate(Outils component1, Outils component2, Sortie sortie, ClasseEntree entree)
        {
            component1.circuit = this;
            component2.circuit = this;
            //On vérifie si l'entrée entree n'est pas déjà reliée,
            //et si sortie et entree ont le meme état booléen,
            //et si sortie est contenue dans la liste_sorties de component1,
            //et si entree est contenue dans la liste_sentrees de component2,
            //et si component1 et component2 sont contenus dans le circuit
            if (!entree.getRelated() && entree.getEtat() == sortie.getEtat() && component1.getListesorties().Contains(sortie) && component2.getListeentrees().Contains(entree) && Circuit.ContainsVertex(component2) && Circuit.ContainsVertex(component1)) //Si l'entrée de component2 n'est pas reliée
            {
                OutStruct outstruct = new OutStruct(entree, component2);                                                                                                                                                                                    //Mise à jour des liaison
                if (!sortie.getSortie().Contains(outstruct))
                {
                    sortie.getSortie().Add(outstruct);
                    entree.setRelated(true);//Mise à jour de related
                }

                if (!Circuit.ContainsEdge(component1, component2)) //Si il n'y a pas un edge déja présent liant component1 et component2
                {
                    Edge <Outils> edge = new Edge <Outils>(component1, component2);
                    Circuit.AddEdge(edge); //Ajouter edge entre component1 et component2
                }

                entree.setEtat(sortie.getEtat()); //Mise à jour de l'état d'entree de component2
                return(true);                     // component1 et component2 liées avec succès
            }
            else
            {
                return(false);
            }
        }
Example #4
0
    public void AddEdge(string Source, string Target)
    {
        if (!graph.ContainsVertex(Source))
        {
            AddNode(Source);
        }
        if (!graph.ContainsVertex(Target))
        {
            AddNode(Target);
        }

        graph.AddEdge(new Edge <string>(Source, Target));
    }
Example #5
0
        public void removeIsolatedVertices()
        {
            var graph = new BidirectionalGraph <int, IEdge <int> >();

            graph.AddVertex(1);
            var edge = new EquatableEdge <int>(2, 3);

            graph.AddVerticesAndEdge(edge);
            var predicate = new IsolatedVertexPredicate <int, IEdge <int> >(graph);

            graph.RemoveVertexIf(predicate.Test);
            Assert.IsTrue(graph.ContainsVertex(2));
            Assert.IsTrue(graph.ContainsEdge(edge));
            Assert.IsFalse(graph.ContainsVertex(1));
        }
Example #6
0
        private BidirectionalGraph <Point, Edge <Point> > BuildGraph(HashSet <Point> map, char[] keys, Dictionary <Point, char> doors, Point startingLocation)
        {
            var graph = new BidirectionalGraph <Point, Edge <Point> >();

            graph.AddVertex(startingLocation);
            var pointsToCheck = new Queue <Point>();

            pointsToCheck.Enqueue(startingLocation);
            while (pointsToCheck.Count > 0)
            {
                var source = pointsToCheck.Dequeue();
                foreach (var dir in _allDirections)
                {
                    // Is there a location on the map in this direction?
                    var target = source.GetPoint(dir);
                    if (map.Contains(target) && !graph.ContainsVertex(target))
                    {
                        // Valid point that we can move to.
                        graph.AddVertex(target);
                        graph.AddEdge(new Edge <Point>(source, target));
                        graph.AddEdge(new Edge <Point>(target, source));

                        // Can we continue past this location?
                        if (!doors.ContainsKey(target) || keys.Contains(doors[target]))
                        {
                            pointsToCheck.Enqueue(target);
                        }
                    }
                }
            }

            return(graph);
        }
Example #7
0
        private void AddVertex_Click(object sender, RoutedEventArgs e)
        {
            if (graph == null || graph.VertexCount >= 100)
            {
                return;
            }

            var rnd           = new Random(DateTime.Now.Millisecond);
            int verticesToAdd = Math.Max(graph.VertexCount / 4, 1);
            var parents       = new string[verticesToAdd];

            for (int j = 0; j < verticesToAdd; j++)
            {
                parents[j] = graph.Vertices.ElementAt(rnd.Next(graph.VertexCount));
            }
            for (int i = 0; i < verticesToAdd; i++)
            {
                string newVertex = string.Empty;
                do
                {
                    newVertex = rnd.Next(0, graph.VertexCount + 20) + "_new";
                } while (graph.ContainsVertex(newVertex));
                graph.AddVertex(newVertex);

                if (graph.VertexCount < 2)
                {
                    return;
                }

                //string vo1 = graph.Vertices.ElementAt(rnd.Next(Math.Max(9 * graph.VertexCount / 10, graph.VertexCount - 1)));
                graph.AddEdge(new Edge <string>(parents[i], newVertex));
            }
        }
Example #8
0
 public void Add(Node node, bool isOutput = false, bool isInput = false)
 {
     if (isOutput && !Outputs.Contains(node))
     {
         Outputs.Add(node);
     }
     if (isInput && !Inputs.Contains(node))
     {
         Inputs.Add(node);
     }
     if (graph.ContainsVertex(node))
     {
         return;
     }
     if (!NodeIndex.ContainsKey(node.Value))
     {
         NodeIndex[node.Value] = node;
     }
     else if (NodeIndex[node.Value] != node)
     {
         NodeIndex[node.Value] = node; //TODO: this could be really bad!!!
         //throw new InvalidOperationException($"a node with the value '{node.Value}' already exists!");
     }
     graph.AddVertex(node);
     node.OnAdd(this);
 }
Example #9
0
        public static IEnumerable <string> Get_Branch_Points_Backwards(string vertex, BidirectionalGraph <string, TaggedEdge <string, ITag> > graph)
        {
            var visited = new HashSet <string>();

            return(Get_Branch_Points_Backwards_LOCAL(vertex));

            #region Local Method
            IEnumerable <string> Get_Branch_Points_Backwards_LOCAL(string v1)
            {
                if (visited.Contains(v1))
                {
                    yield break;
                }
                if (!graph.ContainsVertex(v1))
                {
                    yield break;
                }

                if (graph.OutDegree(v1) > 1)
                {
                    visited.Add(v1);
                    yield return(v1);
                }

                foreach (var edge in graph.InEdges(v1))
                {
                    foreach (var v in Get_Branch_Points_Backwards_LOCAL(edge.Source))
                    {
                        yield return(v);
                    }
                }
            }

            #endregion
        }
        /// <summary>
        /// Removes the group that is related to the specified ID.
        /// </summary>
        /// <param name="group">The ID of the group that should be removed.</param>
        /// <returns>A task that indicates when the removal has taken place.</returns>
        public Task Remove(GroupCompositionId group)
        {
            {
                Debug.Assert(group != null, "The ID that should be removed should not be a null reference.");
                Debug.Assert(m_Groups.ContainsKey(group), "The ID should be known.");
            }

            m_Diagnostics.Log(
                LevelToLog.Trace,
                HostConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.ProxyCompositionLayer_LogMessage_RemovingGroup_WithId,
                    group));

            var remoteTask = m_Commands.Remove(group);

            return(remoteTask.ContinueWith(
                       t =>
            {
                lock (m_Lock)
                {
                    if (m_GroupConnections.ContainsVertex(group))
                    {
                        m_GroupConnections.RemoveVertex(group);
                    }

                    if (m_Groups.ContainsKey(group))
                    {
                        m_Groups.Remove(group);
                    }
                }
            }));
        }
Example #11
0
        private void OnAddVertexClick(object sender, RoutedEventArgs args)
        {
            if (_graph is null || _graph.VertexCount >= 100)
            {
                return;
            }

            var random        = new Random(DateTime.Now.Millisecond);
            int verticesToAdd = Math.Max(_graph.VertexCount / 4, 1);
            var parents       = new string[verticesToAdd];

            for (int j = 0; j < verticesToAdd; ++j)
            {
                int index = random.Next(_graph.VertexCount);
                parents[j] = _graph.Vertices.ElementAt(index);
            }

            for (int i = 0; i < verticesToAdd; ++i)
            {
                string newVertex;
                do
                {
                    newVertex = $"{random.Next(0, _graph.VertexCount + 20)}_new";
                } while (_graph.ContainsVertex(newVertex));
                _graph.AddVertex(newVertex);

                if (_graph.VertexCount < 2)
                {
                    return;
                }

                _graph.AddEdge(new Edge <string>(parents[i], newVertex));
            }
        }
Example #12
0
        /// <summary>
        /// Traverses the schedule and applies an action to each vertex visited.
        /// </summary>
        /// <param name="start">The vertex where the traverse should be started.</param>
        /// <param name="vertexAction">
        /// The action taken for each vertex that is encountered. The action is provided with the current vertex and
        /// a collection of all outbound, if <paramref name="traverseViaOutBoundVertices"/> is <see langword="true" />,
        /// or inbound vertices and the ID of the traversing condition. The function should return <see langword="false" />
        /// to terminate the traverse.
        /// </param>
        /// <param name="traverseViaOutBoundVertices">
        /// A flag indicating if the schedule should be traversed via the outbound edges of the vertices, or the inbound ones.
        /// </param>
        public void TraverseAllScheduleVertices(
            IScheduleVertex start,
            Func <IScheduleVertex, IEnumerable <Tuple <ScheduleElementId, IScheduleVertex> >, bool> vertexAction,
            bool traverseViaOutBoundVertices = true)
        {
            {
                Lokad.Enforce.Argument(() => start);
                Lokad.Enforce.With <UnknownScheduleVertexException>(
                    m_Graph.ContainsVertex(start),
                    Resources.Exceptions_Messages_UnknownScheduleVertex);

                Lokad.Enforce.Argument(() => vertexAction);
            }

            var nodeCounter = new List <IScheduleVertex>();

            var uncheckedVertices = new Queue <IScheduleVertex>();

            uncheckedVertices.Enqueue(start);
            while (uncheckedVertices.Count > 0)
            {
                var source = uncheckedVertices.Dequeue();
                if (nodeCounter.Contains(source))
                {
                    continue;
                }

                nodeCounter.Add(source);

                var outEdges    = traverseViaOutBoundVertices ? m_Graph.OutEdges(source) : m_Graph.InEdges(source);
                var traverseMap = from edge in outEdges
                                  select new Tuple <ScheduleElementId, IScheduleVertex>(
                    edge.TraversingCondition,
                    traverseViaOutBoundVertices ? edge.Target : edge.Source);

                var result = vertexAction(source, traverseMap);
                if (!result)
                {
                    return;
                }

                foreach (var outEdge in outEdges)
                {
                    uncheckedVertices.Enqueue(traverseViaOutBoundVertices ? outEdge.Target : outEdge.Source);
                }
            }
        }
Example #13
0
 /// <summary>
 /// Returns a possible implicit cast chain.
 /// </summary>
 /// <param name="original"></param>
 /// <param name="destinationType"></param>
 /// <returns></returns>
 public IEnumerable <CoercionRule> GetImplicitlyCastChain(System.Type original, System.Type destinationType)
 {
     if (implicitCoercionRules.ContainsVertex(original) && implicitCoercionRules.ShortestPathsDijkstra(t => 1, original)(destinationType, out IEnumerable <TaggedEdge <Type, CoercionRule> > result))
     {
         return(result.Select(e => e.Tag).ToArray());
     }
     return(Enumerable.Empty <CoercionRule>());
 }
Example #14
0
        public BidirectionalGraph <object, IEdge <object> > toGraphSharp()
        {
            BidirectionalGraph <object, IEdge <object> > gr = new BidirectionalGraph <object, IEdge <object> >();

            foreach (var v in a)
            {
                if (!gr.ContainsVertex(v.Origem))
                {
                    gr.AddVertex(v.Origem);
                }
                if (!gr.ContainsVertex(v.vertice))
                {
                    gr.AddVertex(v.vertice);
                }
                gr.AddEdge(new TaggedEdge <object, object>(v.Origem, v.vertice, v.peso));
            }

            return(gr);
        }
        public IReadOnlyList <TVertex> GetConnectedVertices(TVertex vertex, Func <TVertex, TEdge, bool> edgePredicate, bool recursive = false)
        {
            lock (SyncRoot)
            {
                if (!Graph.ContainsVertex(vertex))
                {
                    return(new TVertex[0]);
                }

                return(GetConnectedVerticesRecursive(vertex, edgePredicate, recursive).ToArray());
            }
        }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        protected void AddNode(NodeVertex node)
        {
            // Skip if it it already been added
            if (graph.ContainsVertex(node))
            {
                return;
            }

            // Add the vertex to the logic graph
            graph.AddVertex(node);

            // Create the vertex control
            var control = AssociatedObject.ControlFactory.CreateVertexControl(node);

            control.DataContext = node;
            //control.Visibility = Visibility.Hidden; // make them invisible (there is no layout positions yet calculated)

            // Create data binding for input slots and output slots
            var binding = new Binding();

            binding.Path   = new PropertyPath("InputSlots");
            binding.Mode   = BindingMode.TwoWay;
            binding.Source = node;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(control, NodeVertexControl.InputSlotsProperty, binding);

            binding        = new Binding();
            binding.Path   = new PropertyPath("OutputSlots");
            binding.Mode   = BindingMode.TwoWay;
            binding.Source = node;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(control, NodeVertexControl.OutputSlotsProperty, binding);

            // Add vertex and control to the graph area
            AssociatedObject.AddVertex(node, control);
            AssociatedObject.RelayoutGraph();

            // Connect control
            node.ConnectControl(control);
        }
Example #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Schedule"/> class.
        /// </summary>
        /// <param name="graph">The graph that describes the current schedule.</param>
        /// <param name="start">The start node for the schedule.</param>
        /// <param name="end">The end node for the schedule.</param>
        public Schedule(
            BidirectionalGraph <IScheduleVertex, ScheduleEdge> graph,
            IScheduleVertex start,
            IScheduleVertex end)
        {
            {
                Debug.Assert(graph != null, "The graph should not be a null reference.");

                Debug.Assert(start != null, "The start vertex should not be a null reference.");
                Debug.Assert(start is StartVertex, "The start vertex should be an editable start vertex.");
                Debug.Assert(graph.ContainsVertex(start), "The start vertex should be part of the graph.");

                Debug.Assert(end != null, "The end vertex should not be a null reference.");
                Debug.Assert(end is EndVertex, "The end vertex should be an editable end vertex.");
                Debug.Assert(graph.ContainsVertex(end), "The end vertex should be part of the graph.");
            }

            m_Start = start;
            m_End   = end;

            m_Graph = graph;
        }
        public void ReadFromString(string metroNetworkGraphStr)
        {
            if(String.IsNullOrWhiteSpace(metroNetworkGraphStr))
                throw new ArgumentException("Metro network string either null, empty or consists only of whitespaces", "metroNetworkGraphStr");

            try
            {
                var edges = metroNetworkGraphStr.Split(',').Select(s => s.Trim());
                foreach (var edgeStr in edges)
                {
                    var stationPairAndDistance = edgeStr.Split(':');
                    var stationPair = stationPairAndDistance[0].Split('-');
                    var station1 = stationPair[0];
                    var station2 = stationPair[1];
                    var distance = Int32.Parse(stationPairAndDistance[1]);

                    if (!_graph.ContainsVertex(station1))
                    {
                        _graph.AddVertex(station1);
                    }
                    if (!_graph.ContainsVertex(station2))
                    {
                        _graph.AddVertex(station2);
                    }

                    var edge = new Edge<string>(station1, station2);
                    if (!_graph.ContainsEdge(edge))
                    {
                        _graph.AddEdge(edge);
                        _costs.Add(edge, distance);
                    }
                }
            }
            catch (Exception exc)
            {
                throw new FormatException("Can't read a metro networkgraph - string is in incorrect format", exc);
            }
            
        }
Example #19
0
        private void AddTypeToGraph(TypeDefinition type)
        {
            var derivedTypes = m_Types
                               .Where(
                p =>
            {
                return(p.Value.BaseInterfaces.Contains(type.Identity) ||
                       ((p.Value.BaseType != null) && p.Value.BaseType.Equals(type.Identity)) ||
                       ((p.Value.GenericTypeDefinition != null) && p.Value.GenericTypeDefinition.Equals(type.Identity)));
            })
                               .Select(p => p.Key)
                               .ToList();

            m_TypeGraph.AddVertex(type.Identity);
            if ((type.BaseType != null) && m_TypeGraph.ContainsVertex(type.BaseType))
            {
                m_TypeGraph.AddEdge(new Edge <TypeIdentity>(type.Identity, type.BaseType));
            }

            if ((type.GenericTypeDefinition != null) && m_TypeGraph.ContainsVertex(type.GenericTypeDefinition))
            {
                m_TypeGraph.AddEdge(new Edge <TypeIdentity>(type.Identity, type.GenericTypeDefinition));
            }

            foreach (var baseInterface in type.BaseInterfaces)
            {
                if ((baseInterface != null) && m_TypeGraph.ContainsVertex(baseInterface))
                {
                    m_TypeGraph.AddEdge(new Edge <TypeIdentity>(type.Identity, baseInterface));
                }
            }

            foreach (var derivedType in derivedTypes)
            {
                m_TypeGraph.AddEdge(new Edge <TypeIdentity>(derivedType, type.Identity));
            }
        }
Example #20
0
        public static IEnumerable <string> Get_First_Mutual_Branch_Point_Backwards(string vertex, BidirectionalGraph <string, TaggedEdge <string, Tag> > graph)
        {
            Contract.Requires(graph != null);

            if (!graph.ContainsVertex(vertex))
            {
                yield break;
            }

            int inDegree = graph.InDegree(vertex);

            if (inDegree < 2)
            {
                yield break; // the provided vertex is not a mergePoint
            }

            if (inDegree == 2)
            {
                string s1 = graph.InEdge(vertex, 0).Source;
                string s2 = graph.InEdge(vertex, 1).Source;

                if (s1 != s2)
                {
                    HashSet <string> branchPoints1 = new HashSet <string>();
                    HashSet <string> branchPoints2 = new HashSet <string>();

                    foreach (string v in Get_First_Branch_Point_Backwards(s1, graph))
                    {
                        branchPoints1.Add(v);
                    }

                    foreach (string v in Get_First_Branch_Point_Backwards(s2, graph))
                    {
                        branchPoints2.Add(v);
                    }

                    foreach (string mutual in branchPoints1.Intersect(branchPoints2))
                    {
                        yield return(mutual);
                    }
                }
            }
            else
            {
                Console.WriteLine("WARNING: Get_First_Mutual_Branch_Point_Backwards: multiple merge points at this the provided vertex " + vertex);
            }
        }
Example #21
0
        /// <summary>
        /// Adds a vertex that indicates the end of a synchronization block.
        /// </summary>
        /// <param name="startPoint">The vertex that forms the start point of the block.</param>
        /// <returns>The vertex that indicates the end of a synchronization block.</returns>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="startPoint"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="UnknownScheduleVertexException">
        ///     Thrown if <paramref name="startPoint"/> is not part of the current schedule.
        /// </exception>
        public SynchronizationEndVertex AddSynchronizationEnd(SynchronizationStartVertex startPoint)
        {
            {
                Lokad.Enforce.Argument(() => startPoint);
                Lokad.Enforce.With <UnknownScheduleVertexException>(
                    m_Schedule.ContainsVertex(startPoint),
                    Resources.Exceptions_Messages_UnknownScheduleVertex);
            }

            var result = new SynchronizationEndVertex(m_Schedule.VertexCount);

            m_Schedule.AddVertex(result);

            return(result);
        }
        public static BidirectionalGraph<object, IEdge<object>> ToBidirectionalGraph(this AssemblyDependencyGraph graph)
        {
            // convert schedule graph into generic bidirectional graph that is bindable to the WPF control
            var g = new BidirectionalGraph<object, IEdge<object>>();
            foreach (Assembly assembly in graph.GetAssemblies())
            {
                string fromAssemblyName = assembly.GetName().Name;
                g.AddVertex(fromAssemblyName);

                foreach (Assembly dependantAssembly in graph.GetDependantAssemblies(assembly))
                {
                    string toAssemblyName = dependantAssembly.GetName().Name;
                    if (!g.ContainsVertex(toAssemblyName))
                    {
                        g.AddVertex(toAssemblyName);
                    }
                    g.AddEdge(new Edge<object>(fromAssemblyName, toAssemblyName));
                }
            }
            return g;
        }
        public static BidirectionalGraph <object, IEdge <object> > ToBidirectionalGraph(this AssemblyDependencyGraph graph)
        {
            // convert schedule graph into generic bidirectional graph that is bindable to the WPF control
            var g = new BidirectionalGraph <object, IEdge <object> >();

            foreach (Assembly assembly in graph.GetAssemblies())
            {
                string fromAssemblyName = assembly.GetName().Name;
                g.AddVertex(fromAssemblyName);

                foreach (Assembly dependantAssembly in graph.GetDependantAssemblies(assembly))
                {
                    string toAssemblyName = dependantAssembly.GetName().Name;
                    if (!g.ContainsVertex(toAssemblyName))
                    {
                        g.AddVertex(toAssemblyName);
                    }
                    g.AddEdge(new Edge <object>(fromAssemblyName, toAssemblyName));
                }
            }
            return(g);
        }
Example #24
0
        private void FloodFill(IntCode vm, ref Point currentPos, Dictionary <Point, Status> map, BidirectionalGraph <Point, Edge <Point> > g)
        {
            // Check all directions from this point.
            var pointsToCheck = new Stack <Point>();

            pointsToCheck.Push(currentPos);

            var pointStatus = new Dictionary <Direction, Status>();

            while (pointsToCheck.Count > 0)
            {
                var pointToCheck = pointsToCheck.Pop();
                Log(string.Empty);
                Log($"Checking new point {pointToCheck}");
                MoveTo(pointToCheck, ref currentPos, g, vm, $"new point to check {pointToCheck}");

                var dirsToCheck = Enum.GetValues(typeof(Direction)).Cast <Direction>();
                pointStatus.Clear();
                foreach (var dir in dirsToCheck)
                {
                    var targetPos = currentPos.GetLocation(dir);
                    if (map.ContainsKey(targetPos))
                    {
                        continue;
                    }

                    var currentStatus = Move(ref currentPos, dir, vm, $"checking out unknown position.");
                    pointStatus.Add(dir, currentStatus);
                    map[targetPos] = currentStatus;
                    switch (currentStatus)
                    {
                    case Status.Wall:
                        // The robot did not move, but it hit a wall.
                        break;

                    case Status.Empty:
                        // We moved, and are now at the target position
                        if (!g.ContainsVertex(targetPos))
                        {
                            g.AddVertex(targetPos);
                        }

                        g.AddEdge(new Edge <Point>(pointToCheck, targetPos));
                        g.AddEdge(new Edge <Point>(targetPos, pointToCheck));

                        // Add it as a point to check.
                        pointsToCheck.Push(targetPos);

                        // Then go back to the pointToCheck.
                        MoveTo(pointToCheck, ref currentPos, g, vm, $"point checked. Moving back to {pointToCheck}");

                        break;

                    case Status.System:
                        // We moved, and are now at the target position
                        if (!g.ContainsVertex(targetPos))
                        {
                            g.AddVertex(targetPos);
                        }

                        // We found the oxygen system. No need to check any further in this path. (No other way will be shorter than this).
                        // We just go back to the current position.

                        g.AddEdge(new Edge <Point>(pointToCheck, targetPos));
                        g.AddEdge(new Edge <Point>(targetPos, pointToCheck));

                        MoveTo(pointToCheck, ref currentPos, g, vm, $"point checked (System found). Moving back to {pointToCheck}");

                        break;
                    }
                }

                Log($"Finished with {pointToCheck}:");
                foreach (var kvp in pointStatus)
                {
                    Log($"  {kvp.Key}: {kvp.Value}");
                }
            }
        }
Example #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Schedule"/> class.
        /// </summary>
        /// <param name="graph">The graph that describes the current schedule.</param>
        /// <param name="start">The start node for the schedule.</param>
        /// <param name="end">The end node for the schedule.</param>
        public Schedule(
            BidirectionalGraph<IScheduleVertex, ScheduleEdge> graph,
            IScheduleVertex start,
            IScheduleVertex end)
        {
            {
                Debug.Assert(graph != null, "The graph should not be a null reference.");

                Debug.Assert(start != null, "The start vertex should not be a null reference.");
                Debug.Assert(start is StartVertex, "The start vertex should be an editable start vertex.");
                Debug.Assert(graph.ContainsVertex(start), "The start vertex should be part of the graph.");

                Debug.Assert(end != null, "The end vertex should not be a null reference.");
                Debug.Assert(end is EndVertex, "The end vertex should be an editable end vertex.");
                Debug.Assert(graph.ContainsVertex(end), "The end vertex should be part of the graph.");
            }

            m_Start = start;
            m_End = end;

            m_Graph = graph;
        }
Example #26
0
 public bool ContainsVertex(TVertexId vertexId) => _graph.ContainsVertex(vertexId);
Example #27
0
 void setElement(InfoWrapper W, int parent, int children)
 {
     BidirectionalGraph<object, IEdge<object>> L = new BidirectionalGraph<object, IEdge<object>>();
     L.AddVertex(W);
     if (parent != 0)
     {
         InfoWrapper c = W;
         while (c.Parent.pString != "")
         {
             InfoWrapper p = m_pData[W.Parent.pString];
             if (!L.ContainsVertex(p))
                 L.AddVertex(p);
             L.AddEdge(new Edge<object>(p, c));
             if (parent == 1 || p.Name.pString == c.Name.pString)
                 break;
             c = p;
         }
     }
     if (children != 0)
     {
         Action<InfoWrapper> T = null;
         T = (p) =>
         {
             foreach (InfoWrapper a in m_pData.Values)
                 if (a.Parent.pString == p.Name.pString)
                 {
                     if (!L.AddVertex(a))
                         L.AddVertex(a);
                     L.AddEdge(new Edge<object>(p, a));
                     if (children != 1)
                         T(a);
                 }
         };
         T(W);
     }
     graphLayout1.Graph = L;
     foreach (var v in graphLayout1.Children)
     {
         if (v is VertexControl)
             (v as VertexControl).PreviewMouseDoubleClick += graphLayout1_MouseDown;
     }
     (windowsFormsHost2.Child as System.Windows.Forms.PropertyGrid).SelectedObject = W;
     addWrapper(W);
 }
Example #28
0
 public bool ContainsVertex(TVertex vertex) => _graph.ContainsVertex(vertex);
 public bool ContainsAssembly(Assembly assembly)
 {
     return(_dependencyGraph.ContainsVertex(new AssemblyNode(assembly)));
 }
        private void FindDependencies(IDomainObject currentObject, IDomainObject child, bool halt = false)
        {
            if (abort || currentObject == null)
            {
                return;
            }

            if (graph.ContainsVertex(currentObject))
            {
                if (child != null)
                {
                    graph.AddEdge(new Edge <IDomainObject>(currentObject, child));
                }

                return;
            }

            statusLabel.Invoke(new System.Action(() =>
            {
                statusLabel.Text = string.Format("Analyzing {0}...", currentObject.ToString());
            }));

            NHibernateUtil.Initialize(currentObject);

            graph.AddVertex(currentObject);

            if (child != null)
            {
                graph.AddEdge(new Edge <IDomainObject>(currentObject, child));
            }

            if (currentObject is Cdc.MetaManager.DataAccess.Domain.Application || halt)
            {
                return;
            }

            List <IDomainObject> list = modelService.GetReferencingObjects(currentObject) as List <IDomainObject>;

            if (currentObject is ServiceMethod || (currentObject is Dialog && ((Dialog)currentObject).Type == DialogType.Find))
            {
                statusLabel.Invoke(new System.Action(() =>
                {
                    statusLabel.Text = string.Format("Finding XML references for {0}...", currentObject.ToString());
                }));

                string query = "select v from View v where v.VisualTreeXml like '%" + currentObject.Id + "%'";
                IList <IDomainObject> xmlReferences = modelService.GetDomainObjectsByQuery <IDomainObject>(query);

                list.AddRange(xmlReferences);
            }

            IList <IVersionControlled> vcParents = new List <IVersionControlled>();

            foreach (IDomainObject domainObject in list)
            {
                halt = false;

                ViewAction vc = domainObject as ViewAction;

                if (vc != null && vc.Type == ViewActionType.JumpTo)
                {
                    halt = true;
                }

                IVersionControlled vcObject = domainObject as IVersionControlled;

                if (vcObject == null)
                {
                    List <IDomainObject> allParents;
                    vcObject = modelService.GetVersionControlledParent(domainObject, out allParents).LastOrDefault();
                }

                if (!vcParents.Contains(vcObject))
                {
                    vcParents.Add(vcObject);
                    FindDependencies(vcObject, currentObject, halt);
                }
            }
        }