public static Supergraph CreateSatsumaGraph(this Choosability.Graph g) { var satsumaGraph = new CustomGraph(); var nodes = new Dictionary <int, Node>(); foreach (var v in g.Vertices) { var node = satsumaGraph.AddNode(); nodes[v] = node; } for (int i = 0; i < g.N; i++) { for (int j = i + 1; j < g.N; j++) { if (g.Directed[i, j]) { satsumaGraph.AddArc(nodes[i], nodes[j], Directedness.Directed); } else if (g.Directed[j, i]) { satsumaGraph.AddArc(nodes[j], nodes[i], Directedness.Directed); } else if (g.Adjacent[i, j]) { satsumaGraph.AddArc(nodes[i], nodes[j], Directedness.Undirected); } } } return(satsumaGraph); }
public Graph(int seed) { SetSeed(seed); nodeList = new List <Node>(); arcList = new List <Arc>(); baseGraph = new CustomGraph(); }
/// <summary> /// Retourne un object CustomGraph qui pourra être utilisé pour générer la visualisation /// Crée l'object à partir d'une chaine de caractères JSON /// </summary> /// <param name="json_string">Chaine de caractères JSON</param> /// <returns>CustomGraph</returns> public static CustomGraph loadGraphFromJson(string json_string) { CustomGraph graph = new CustomGraph(); // On converti la string JSON en object JsonGraph JsonGraph jsonGraph = JsonConvert.DeserializeObject <JsonGraph>(json_string); // On ajoute tous les arcs foreach (JsonEdge edge in jsonGraph.ExecutionNodes) { graph.addEdge(edge.Source, edge.Dest, edge.Time, edge.Name); } // On ajoute les informations comprises dans "node_selection" foreach (JsonNode node in jsonGraph.NodeSelection) { CustomNode graph_node = graph.nodes[node.Id]; graph_node.visited = true; graph_node.heuristic_value = node.HeuristicValue; graph_node.real_final_value = node.RealFinalValue; graph_node.order_visited = node.Order; } // On ajoute les informations comprises dans "selected_path" foreach (JsonNode node in jsonGraph.SelectedPath) { CustomNode graph_node = graph.nodes[node.Id]; graph_node.in_selected_path = true; } return(graph); }
private void CreateGraph(NavigationNode[] navigationNodes) { Graph = new CustomGraph(); foreach (NavigationNode navigationNode in navigationNodes) { navigationNode.Node = Graph.AddNode(navigationNode.transform.position); } }
/// <summary> /// Saves the graph. /// </summary> /// <param name="graph">The graph.</param> /// <param name="filename">The filename.</param> public static void SaveGraph(CustomGraph graph, string filename) { ////create the xml writer if (!string.IsNullOrEmpty(filename)) { using (var writer = XmlWriter.Create(filename)) { var serializer = new GraphMLSerializer<CustomVertex, CustomEdge, CustomGraph>(); ////serialize the graph serializer.Serialize(writer, graph, v => v.Text + ";" + v.BackgroundColor.ToString() + ";" + v.X.ToString() + ";" + v.Y.ToString() + ";" + v.Highlight.ToString() + ";", e => e.EdgeColor.ToString() + ";" + e.Trigger); } } }
/// <summary> /// Loads the graph. /// </summary> /// <param name="filename">The filename.</param> /// <returns></returns> public static CustomGraph LoadGraph(string filename) { ////open the file of the graph var reader = XmlReader.Create(filename); ////create the serializer var serializer = new GraphMLDeserializer<CustomVertex, CustomEdge, CustomGraph>(); ////graph where the vertices and edges should be put in var customGraph = new CustomGraph(); ////deserialize the graph serializer.Deserialize(reader, customGraph, id => new CustomVertex(id.Split(';').First(), (Color)ColorConverter.ConvertFromString(id.Split(';').ElementAt(1)), id.Split(';').ElementAt(4), double.Parse(id.Split(';').ElementAt(2)), double.Parse(id.Split(';').ElementAt(3))), (source, target, name) => new CustomEdge(name.Split(';').ElementAt(1), source, target, (Color)ColorConverter.ConvertFromString(name.Split(';').FirstOrDefault()))); return customGraph; }
/// Loads from a reader. /// \param reader A reader on the input file, e.g. a StreamReader. /// \param directedness Specifies the directedness of the graph to be loaded. Possible values: /// - \c Directedness.Directed: each created arc will be directed. /// - \c Directedness.Undirected: each created arc will be an edge (i.e. undirected). /// \return the loaded nodes, by index ascending public Node[] Load(TextReader reader, Directedness directedness) { if (Graph == null) { Graph = new CustomGraph(); } IBuildableGraph buildableGraph = (IBuildableGraph)Graph; buildableGraph.Clear(); string[] tokens; var whitespaces = new Regex(@"\s+"); // first line: number of nodes and arcs tokens = whitespaces.Split(reader.ReadLine()); int nodeCount = int.Parse(tokens[0], CultureInfo.InvariantCulture); int arcCount = int.Parse(tokens[1], CultureInfo.InvariantCulture); Node[] nodes = new Node[nodeCount]; for (int i = 0; i < nodeCount; i++) { nodes[i] = buildableGraph.AddNode(); } Extensions.Clear(); for (int i = 0; i < arcCount; i++) { tokens = whitespaces.Split(reader.ReadLine()); int a = (int)(long.Parse(tokens[0], CultureInfo.InvariantCulture) - StartIndex); int b = (int)(long.Parse(tokens[1], CultureInfo.InvariantCulture) - StartIndex); Arc arc = buildableGraph.AddArc(nodes[a], nodes[b], directedness); int extensionCount = tokens.Length - 2; for (int j = 0; j < extensionCount - Extensions.Count; j++) { Extensions.Add(new Dictionary <Arc, string>()); } for (int j = 0; j < extensionCount; j++) { Extensions[j][arc] = tokens[2 + j]; } } return(nodes); }
public bool Layout(Polygon bounds = null) { bool flag = false; int num = 0; Vector2 vector = default(Vector2); while (!flag && num < 100) { flag = true; Func <Satsuma.Node, PointD> initialPositions = (Satsuma.Node n) => GetPositionForNode(n); CustomGraph baseGraph = this.baseGraph; int seed = num; ForceDirectedLayout forceDirectedLayout = new ForceDirectedLayout(baseGraph, initialPositions, seed); forceDirectedLayout.ExternalForce = ((PointD point) => GetForceForBoundry(point, bounds)); forceDirectedLayout.Run(0.01); IEnumerator <Satsuma.Node> enumerator = this.baseGraph.Nodes().GetEnumerator(); int num2 = 0; while (enumerator.MoveNext()) { Satsuma.Node node = enumerator.Current; Node node2 = nodeList.Find((Node n) => n.node == node); if (node2 != null) { vector.x = (float)forceDirectedLayout.NodePositions[node].X; vector.y = (float)forceDirectedLayout.NodePositions[node].Y; if (!bounds.Contains(vector)) { flag = false; Debug.LogWarning("Re-doing layout - cell was off map"); break; } node2.SetPosition(vector); } if (!flag) { break; } num2++; } num++; } if (num >= 10) { Debug.LogWarning("Re-ran layout " + num + " times"); } return(flag); }
public override void Solve() { var pparser = new Pparser(FpatIn); int ccity, cwizard; pparser.Fetch(out ccity, out cwizard); var rgcity = pparser.FetchN <Nod>(ccity); var rgwizard = pparser.FetchN <Nod>(cwizard); var graph = new CustomGraph(); var mpnodByinod = new Dictionary <long, Nod>(); foreach (var wizard in rgwizard) { wizard.kind = Kind.Wizard; wizard.node = graph.AddNode(); mpnodByinod[wizard.node.Id] = wizard; } foreach (var city in rgcity) { city.kind = Kind.City; city.node = graph.AddNode(); mpnodByinod[city.node.Id] = city; } foreach (var wizard in rgwizard) { foreach (var city in rgcity) { if (Dist(wizard, city) <= 50) { graph.AddArc(wizard.node, city.node, Directedness.Directed); } } } var mm = new MaximumMatching(graph, node => mpnodByinod[node.Id].kind == Kind.Wizard); mm.Run(); using (Output) { Solwrt.WriteLine(mm.Matching.ArcCount()); } }
/// <summary> /// Fonction appelée quand on clique sur le bouton "Calculer" /// Recalcul le layout du ou des graphes avec les nouveaux paramètres /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void calculer_Clicked(object sender, RoutedEventArgs e) { SecondaryVisible = false; // Dans tous les cas on charge le graphe principal CustomGraph graphe1 = JsonGraphProvider.loadGraphFromFile(folderName + "\\" + selectedMainFile.SelectedItem.ToString()); // Si on ne veut afficher que un seul graphe if ((bool)oneGraph.IsChecked) { viewer1.Graph = graphe1.getVisualGraph((bool)mainGraphVisitedNodes.IsChecked, (bool)mainGraphGroupNodes.IsChecked, (bool)mainGraphEdgeName.IsChecked, mainGraphGroupLevel.Value); } else if ((bool)twoInOne.IsChecked) // Si on veut afficher deux graphe dans la même vue { CustomGraph graphe2 = JsonGraphProvider.loadGraphFromFile(folderName + "\\" + selectedSecondaryFile.SelectedItem.ToString()); CustomGraphMerged merged_graph = new CustomGraphMerged(graphe1, graphe2); viewer1.Graph = merged_graph.getVisualGraph((bool)mainGraphVisitedNodes.IsChecked, (bool)mainGraphGroupNodes.IsChecked, (bool)mainGraphEdgeName.IsChecked, mainGraphGroupLevel.Value); } else if ((bool)twoGraphs.IsChecked) // Si on veut afficher 2 graphes cote à cote { SecondaryVisible = true; CustomGraph graphe2 = JsonGraphProvider.loadGraphFromFile(folderName + "\\" + selectedSecondaryFile.SelectedItem.ToString()); viewer1.Graph = graphe1.getVisualGraph((bool)mainGraphVisitedNodes.IsChecked, (bool)mainGraphGroupNodes.IsChecked, (bool)mainGraphEdgeName.IsChecked, mainGraphGroupLevel.Value); viewer2.Graph = graphe2.getVisualGraph((bool)secondGraphVisitedNodes.IsChecked, (bool)secondGraphGroupNodes.IsChecked, (bool)secondGraphEdgeName.IsChecked, secondGraphhGroupLevel.Value); } }
public Node[] Load(TextReader reader, Directedness directedness) { if (Graph == null) { Graph = new CustomGraph(); } IBuildableGraph buildableGraph = (IBuildableGraph)Graph; buildableGraph.Clear(); Regex regex = new Regex("\\s+"); string[] array = regex.Split(reader.ReadLine()); int num = int.Parse(array[0], CultureInfo.InvariantCulture); int num2 = int.Parse(array[1], CultureInfo.InvariantCulture); Node[] array2 = new Node[num]; for (int i = 0; i < num; i++) { array2[i] = buildableGraph.AddNode(); } Extensions.Clear(); for (int j = 0; j < num2; j++) { array = regex.Split(reader.ReadLine()); int num3 = (int)(long.Parse(array[0], CultureInfo.InvariantCulture) - StartIndex); int num4 = (int)(long.Parse(array[1], CultureInfo.InvariantCulture) - StartIndex); Arc key = buildableGraph.AddArc(array2[num3], array2[num4], directedness); int num5 = array.Length - 2; for (int k = 0; k < num5 - Extensions.Count; k++) { Extensions.Add(new Dictionary <Arc, string>()); } for (int l = 0; l < num5; l++) { Extensions[l][key] = array[2 + l]; } } return(array2); }
/// Loads from an XML document. public void Load(XDocument doc) { // Namespaces are ignored so we can load broken documents. if (Graph == null) { Graph = new CustomGraph(); } IBuildableGraph buildableGraph = (IBuildableGraph)Graph; buildableGraph.Clear(); XElement xGraphML = doc.Root; // load properties Properties.Clear(); Dictionary <string, GraphMLProperty> propertyById = new Dictionary <string, GraphMLProperty>(); foreach (var xKey in Utils.ElementsLocal(xGraphML, "key")) { foreach (var handler in PropertyLoaders) { try { GraphMLProperty p = handler(xKey); Properties.Add(p); propertyById[p.Id] = p; break; } catch (ArgumentException) { } } } // load graph XElement xGraph = Utils.ElementLocal(xGraphML, "graph"); Directedness defaultDirectedness = (xGraph.Attribute("edgedefault").Value == "directed" ? Directedness.Directed : Directedness.Undirected); ReadProperties(propertyById, xGraph, Graph); // load nodes Dictionary <string, Node> nodeById = new Dictionary <string, Node>(); foreach (var xNode in Utils.ElementsLocal(xGraph, "node")) { Node node = buildableGraph.AddNode(); nodeById[xNode.Attribute("id").Value] = node; ReadProperties(propertyById, xNode, node); } // load arcs foreach (var xArc in Utils.ElementsLocal(xGraph, "edge")) { Node u = nodeById[xArc.Attribute("source").Value]; Node v = nodeById[xArc.Attribute("target").Value]; Directedness dir = defaultDirectedness; XAttribute dirAttr = xArc.Attribute("directed"); if (dirAttr != null) { dir = (dirAttr.Value == "true" ? Directedness.Directed : Directedness.Undirected); } Arc arc = buildableGraph.AddArc(u, v, dir); ReadProperties(propertyById, xArc, arc); } }
public void Load(XDocument doc) { if (Graph == null) { Graph = new CustomGraph(); } IBuildableGraph buildableGraph = (IBuildableGraph)Graph; buildableGraph.Clear(); XElement root = doc.Root; Properties.Clear(); Dictionary <string, GraphMLProperty> dictionary = new Dictionary <string, GraphMLProperty>(); foreach (XElement item in Utils.ElementsLocal(root, "key")) { using (List <Func <XElement, GraphMLProperty> > .Enumerator enumerator2 = PropertyLoaders.GetEnumerator()) { while (true) { if (enumerator2.MoveNext()) { Func <XElement, GraphMLProperty> current2 = enumerator2.Current; try { GraphMLProperty graphMLProperty = current2(item); Properties.Add(graphMLProperty); dictionary[graphMLProperty.Id] = graphMLProperty; } catch (ArgumentException) { continue; } } break; } } } XElement xElement = Utils.ElementLocal(root, "graph"); Directedness directedness = (!(xElement.Attribute("edgedefault").Value == "directed")) ? Directedness.Undirected : Directedness.Directed; ReadProperties(dictionary, xElement, Graph); Dictionary <string, Node> dictionary2 = new Dictionary <string, Node>(); foreach (XElement item2 in Utils.ElementsLocal(xElement, "node")) { Node node = buildableGraph.AddNode(); dictionary2[item2.Attribute("id").Value] = node; ReadProperties(dictionary, item2, node); } foreach (XElement item3 in Utils.ElementsLocal(xElement, "edge")) { Node u = dictionary2[item3.Attribute("source").Value]; Node v = dictionary2[item3.Attribute("target").Value]; Directedness directedness2 = directedness; XAttribute xAttribute = item3.Attribute("directed"); if (xAttribute != null) { directedness2 = ((!(xAttribute.Value == "true")) ? Directedness.Undirected : Directedness.Directed); } Arc arc = buildableGraph.AddArc(u, v, directedness2); ReadProperties(dictionary, item3, arc); } }
/// Loads from a reader. /// \param reader A reader on the input file, e.g. a StreamReader. /// \param directedness Specifies the directedness of the graph to be loaded. Possible values: /// - \c Directedness.Directed: each created arc will be directed. /// - \c Directedness.Undirected: each created arc will be undirected. /// - \c null (default): arcs defined in \c \@arcs sections will be directed, /// while those defined in \c \@edges sections will be undirected. public void Load(TextReader reader, Directedness?directedness) { if (Graph == null) { Graph = new CustomGraph(); } IBuildableGraph buildableGraph = (IBuildableGraph)Graph; buildableGraph.Clear(); NodeMaps.Clear(); var nodeFromLabel = new Dictionary <string, Node>(); ArcMaps.Clear(); Attributes.Clear(); Regex splitRegex = new Regex(@"\s*((""(\""|.)*"")|(\S+))\s*", RegexOptions.Compiled); string section = ""; Directedness currDir = Directedness.Directed; // are currently read arcs directed? bool prevHeader = false; List <string> columnNames = null; int labelColumnIndex = -1; while (true) { string line = reader.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line == "" || line[0] == '#') { continue; } List <string> tokens = splitRegex.Matches(line).Cast <Match>() .Select(m => { string s = m.Groups[1].Value; if (s == "") { return(s); } if (s[0] == '"' && s[s.Length - 1] == '"') { s = Unescape(s.Substring(1, s.Length - 2)); } return(s); }).ToList(); string first = tokens.First(); // header? if (line[0] == '@') { section = first.Substring(1); currDir = directedness ?? (section == "arcs" ? Directedness.Directed : Directedness.Undirected); prevHeader = true; continue; } switch (section) { case "nodes": case "red_nodes": case "blue_nodes": { if (prevHeader) { columnNames = tokens; for (int i = 0; i < columnNames.Count; i++) { string column = columnNames[i]; if (column == "label") { labelColumnIndex = i; } if (!NodeMaps.ContainsKey(column)) { NodeMaps[column] = new Dictionary <Node, string>(); } } } else { Node node = buildableGraph.AddNode(); for (int i = 0; i < tokens.Count; i++) { NodeMaps[columnNames[i]][node] = tokens[i]; if (i == labelColumnIndex) { nodeFromLabel[tokens[i]] = node; } } } } break; case "arcs": case "edges": { if (prevHeader) { columnNames = tokens; foreach (var column in columnNames) { if (!ArcMaps.ContainsKey(column)) { ArcMaps[column] = new Dictionary <Arc, string>(); } } } else { Node u = nodeFromLabel[tokens[0]]; Node v = nodeFromLabel[tokens[1]]; Arc arc = buildableGraph.AddArc(u, v, currDir); for (int i = 2; i < tokens.Count; i++) { ArcMaps[columnNames[i - 2]][arc] = tokens[i]; } } } break; case "attributes": { Attributes[tokens[0]] = tokens[1]; } break; } prevHeader = false; } // while can read from file }
/// <summary> /// Sets the nodes position to save. /// </summary> private void SetNodesPositionToSave(CustomGraph graphToSave) { foreach (CustomVertex vertex in graphLayout.Graph.Vertices) { double vertexX = GraphLayout.GetX(graphLayout.GetVertexControl(vertex)); double vertexY = GraphLayout.GetY(graphLayout.GetVertexControl(vertex)); graphToSave.Vertices.Where(var => var.CompareTo(vertex)).FirstOrDefault().X = vertexX; graphToSave.Vertices.Where(var => var.CompareTo(vertex)).FirstOrDefault().Y = vertexY; } }
/// <summary> /// Sets the nodes position from custom graph. /// </summary> /// <param name="graph">The graph.</param> private void SetNodesPositionFromCustomGraph(CustomGraph graph) { StringBuilder s = new StringBuilder(); for (int i = 0; i < graph.Vertices.Count(); i++) { GraphLayout.SetX(graphLayout.GetVertexControl(graphLayout.Graph.Vertices.ElementAt(i)), graph.Vertices.ElementAt(i).X); GraphLayout.SetY(graphLayout.GetVertexControl(graphLayout.Graph.Vertices.ElementAt(i)), graph.Vertices.ElementAt(i).Y); } }
/// <summary> /// Opens the specified custom graph. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void Open(object sender, RoutedEventArgs e) { string path = Utilities.GetPath("Select the custom graph to open"); if (path != null) { try { CustomGraph graph = new CustomGraph(); graph = SerializeHelper.LoadGraph(path); this.DataContext = graph; MessageBox.Show("Graph opened succesfully!"); this.SetNodesPositionFromCustomGraph(SerializeHelper.LoadGraph(path)); } catch (Exception ex) { console.Text += ex.Message + "\r\nIncorrect file type!\r\n"; scrConsole.ScrollToEnd(); } } }
static void Main(string[] args) { try { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Implementing the Graph with basic operations"); Console.ForegroundColor = ConsoleColor.White; CustomGraph customGraph = new CustomGraph(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Pushing the lables A, B, C, D, E to graph"); Console.WriteLine("Adding edges A-->B, B-->D, D-->C, A-->C, A-->D, B-->E"); Console.ForegroundColor = ConsoleColor.White; customGraph.AddNode("A"); customGraph.AddNode("B"); customGraph.AddNode("C"); customGraph.AddNode("D"); customGraph.AddNode("E"); customGraph.AddEdge("A", "B"); customGraph.AddEdge("B", "D"); customGraph.AddEdge("D", "C"); customGraph.AddEdge("A", "C"); customGraph.AddEdge("A", "D"); customGraph.AddEdge("B", "E"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Printing nodes connected with edges"); Console.ForegroundColor = ConsoleColor.White; customGraph.Print(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Removing edge A-->B and D-->C"); Console.ForegroundColor = ConsoleColor.White; customGraph.RemoveEdge("A", "B"); customGraph.RemoveEdge("D", "C"); customGraph.Print(); customGraph.AddEdge("A", "B"); customGraph.AddEdge("D", "C"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Perform the DFS Traversal for node A using recurssion"); Console.ForegroundColor = ConsoleColor.White; customGraph.DFSTraversalUsingRecurssion("A"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Perform the DFS Traversal for node A using iteration"); Console.ForegroundColor = ConsoleColor.White; customGraph.DFSTraversaUsingIteration("A"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Perform the DFS Traversal for node A using iteration"); Console.ForegroundColor = ConsoleColor.White; customGraph.BFSTraversaUsingIteration("B"); #region Topological Sort Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Performing topological sort"); Console.ForegroundColor = ConsoleColor.White; CustomGraph topologicalSort = new CustomGraph(); topologicalSort.AddNode("P"); topologicalSort.AddNode("A"); topologicalSort.AddNode("B"); topologicalSort.AddNode("X"); topologicalSort.AddEdge("A", "P"); topologicalSort.AddEdge("X", "A"); topologicalSort.AddEdge("X", "B"); topologicalSort.AddEdge("B", "A"); List <string> nodes = topologicalSort.TopologicalSort(); foreach (var item in nodes) { Console.WriteLine(item); } #endregion #region Cycle Detection Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Checking whether the graph"); Console.ForegroundColor = ConsoleColor.White; CustomGraph cycleDetection = new CustomGraph(); cycleDetection.AddNode("A"); cycleDetection.AddNode("B"); cycleDetection.AddNode("C"); cycleDetection.AddNode("D"); cycleDetection.AddEdge("A", "D"); cycleDetection.AddEdge("B", "C"); cycleDetection.AddEdge("C", "B"); Console.WriteLine(cycleDetection.HasCycle()); #endregion } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(ex.Message); Console.ForegroundColor = ConsoleColor.White; } }
public void GenerateNewTileMap(int row1, int col1, int row2, int col2) { // CustomGraph.GetDFSMap(ref tiles, row1, col1, row2, col2); CustomGraph.GetRankBasedMap(ref tiles, row1, col1, row2, col2); SetRoadTypes(); }