public static void Main(string[] args) { client = new TwitterClient(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret); client.OnRequestAuthenticationResponse += new TwitterClient.AuthenticationHandler(client_OnRequestAuthenticationResponse); if (!client.Authenticated) client.Authenticate(); Properties.Settings.Default.AccessToken = client.AccessToken; Properties.Settings.Default.AccessTokenSecret = client.AccessTokenSecret; Properties.Settings.Default.Save(); queryString = client.Trends.ToArray()[0]; Console.WriteLine("Starting monitoring of trend: "+queryString); network = new Network(); //NetworkVisualizer visualizer = new NetworkVisualizer(network, new NETGen.Layout.FruchtermanReingold.FruchtermanReingoldLayout(10), new PresentationSettings(2000d, 1000d, 0d)); //NetworkDisplay display = new NetworkDisplay(visualizer); counter = 0; stream = client.CreateStatusFilter(client.Trends.ToArray()[0]); stream.OnNewJsonObject += new TwitterStream.NewJSONHandler(stream_OnNewJsonObject); stream.Start(); Console.ReadKey(); stream.Stop(); }
internal NetworkVisualizer(Network network, LayoutProvider layout, NetworkColorizer colorizer, int width, int height) : base(width, height, OpenTK.Graphics.GraphicsMode.Default, "NETGen Display") { Keyboard.KeyDown += new EventHandler<KeyboardKeyEventArgs>(Keyboard_KeyDown); Mouse.ButtonDown += new EventHandler<MouseButtonEventArgs>(Mouse_ButtonDown); Mouse.ButtonUp += new EventHandler<MouseButtonEventArgs>(Mouse_ButtonUp); Mouse.Move += new EventHandler<MouseMoveEventArgs>(Mouse_Move); Mouse.WheelChanged += new EventHandler<MouseWheelEventArgs>(Mouse_WheelChanged); ComputeNodeSize = new Func<Vertex, float>(v => { return 2f; }); ComputeEdgeWidth = new Func<Edge, float>( e => { return 0.05f; }); _network = network; _layout = layout; _layout.Init(Width, Height, network); if (colorizer == null) _colorizer = new NetworkColorizer(); else _colorizer = colorizer; }
/// <summary> /// Creates a new undirected edge between source and target. The edge is not registered with the source and /// target vertices unless it is added to the graph! /// </summary> /// <param name="a">The A vertex</param> /// <param name="b">The B vertex</param> /// <param name="graph">The graph to which this edge belongs</param> public Edge(Vertex a, Vertex b, Network graph) { ID = Guid.NewGuid(); A = a; B = b; Network = graph; EdgeType = EdgeType.Undirected; }
/// <summary> /// Creates a new edge between source and target. The edge is not registered with the source and /// target vertices unless it is added to the graph! /// </summary> /// <param name="a">The A vertex</param> /// <param name="b">The B vertex</param> /// <param name="graph">The graph to which this edge belongs</param> /// <param name="type">Whether to create an undirected or a directed edge</param> public Edge(Vertex a, Vertex b, Network graph, EdgeType type) { ID = Guid.NewGuid(); A = a; B = b; Network = graph; EdgeType = type; }
/// <summary> /// Creates a new edge between source and target. The edge is not registered with the source and /// target vertices unless it is added to the graph! /// </summary> /// <param name="a">The A vertex</param> /// <param name="b">The B vertex</param> /// <param name="graph">The graph to which this edge belongs</param> /// <param name="type">Whether to create an undirected or a directed edge</param> /// <param name="id">The ID that this vertex will be assigned</param> public Edge(Vertex a, Vertex b, Network graph, EdgeType type, Guid id) { ID = id; A = a; B = b; Network = graph; EdgeType = type; }
public override void Init(double width, double height, NETGen.Core.Network network) { base.Init(width, height, network); Network.OnVertexAdded += new Network.VertexUpdateHandler(delegate(Vertex v) { DoLayout(); }); }
public CEFPlayer(string cefFile, Network n, NetworkColorizer c = null) { filename = cefFile; network = n; colorizer = c; if(cefFile == null || !System.IO.File.Exists(cefFile)) Logger.AddMessage(LogEntryType.Error, "Given cef-File does not exist."); }
public SIRSpreading(Network n, NetworkColorizer colorizer = null) { _network = n; _colorizer = colorizer; _active = new List<Vertex>(); _infected = new List<Vertex>(); _infections = new Dictionary<Vertex, bool>(); }
/// <summary> /// Assigns the random positions if they have not been assigned before ... /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="n"></param> public void DoLayout(double width, double height, Network n) { foreach (Vertex v in n.Vertices) { if (!_vertexPositions.ContainsKey(v)) _vertexPositions[v] = new Vector3(v.Network.NextRandomDouble() * width, v.Network.NextRandomDouble() * height, 0); } _laidout = true; }
private static void ClassifyNeighbors(Network net, Vertex v, List<Vertex> intraNeighbors, List<Vertex> interNeighbors) { foreach (Vertex x in v.Neigbors) { if ((net as ClusterNetwork).GetClusterForNode(x) == (net as ClusterNetwork).GetClusterForNode(v)) intraNeighbors.Add(x); else interNeighbors.Add(x); } }
public void EpidemicSyncTest() { Network n = new Network(); Vertex a = n.CreateVertex(); Vertex b = n.CreateVertex(); n.CreateEdge(a, b); Kuramoto sync = new Kuramoto(n, 2d); sync.WriteTimeSeries(null); sync.Stop(); }
private static void Draw(XGraphics g, Network n, PresentationSettings presentationSettings, ILayoutProvider layout) { lock (n) { if (g == null) return; g.SmoothingMode = PdfSharp.Drawing.XSmoothingMode.HighQuality; g.Clear(Color.White); foreach (Edge e in n.Edges) DrawEdge(g, e, presentationSettings, layout); foreach (Vertex v in n.Vertices) DrawVertex(g, v, presentationSettings, layout); } }
private static void Draw(XGraphics g, Network n, LayoutProvider layout, NetworkColorizer colorizer) { lock (n) { if (g == null) return; g.SmoothingMode = PdfSharp.Drawing.XSmoothingMode.HighQuality; g.Clear(Color.White); foreach (Edge e in n.Edges) DrawEdge(g, e, layout, colorizer); foreach (Vertex v in n.Vertices) DrawVertex(g, v, layout, colorizer); } }
/// <summary> /// Creates a new instance of a Networkvisualizer which renders the specified network in real-time /// </summary> /// <param name='n'> /// N. /// </param> /// <param name='layout'> /// Layout. /// </param> public static void Start(Network network, ILayoutProvider layout, NetworkColorizer colorizer = null, int width=800, int height=600) { // The actual rendering needs to be done in a separate thread placed in the single thread appartment state _mainThread = new Thread(new ThreadStart(new Action(delegate() { NetworkVisualizer p = new NetworkVisualizer(network, layout, colorizer, width, height); p.Run(80f); }))); _mainThread.SetApartmentState(ApartmentState.STA); _mainThread.Name = "STA Thread for NETGen Visualizer"; // Fire up the thread _mainThread.Start(); }
public static void CreatePDF(string path, Network n, LayoutProvider layout, NetworkColorizer colorizer) { PdfSharp.Pdf.PdfDocument doc = new PdfDocument(); doc.Info.Title = "Network"; doc.Info.Subject = "Created by NETGen"; PdfPage page = doc.AddPage(); page.Size = PageSize.A4; page.Orientation = PageOrientation.Landscape; // Draw the network to the xgraphics object Draw(XGraphics.FromPdfPage(page), n, layout, colorizer); // Save the s_document... doc.Save(path); }
internal NetworkVisualizer(Network network, ILayoutProvider layout, NetworkColorizer colorizer, int width, int height) : base(width, height, GraphicsMode.Default, "NETGen Display") { Keyboard.KeyDown += new EventHandler<KeyboardKeyEventArgs>(Keyboard_KeyDown); Mouse.ButtonDown += new EventHandler<MouseButtonEventArgs>(Mouse_ButtonDown); Mouse.ButtonUp += new EventHandler<MouseButtonEventArgs>(Mouse_ButtonUp); Mouse.Move += new EventHandler<MouseMoveEventArgs>(Mouse_Move); Mouse.WheelChanged += new EventHandler<MouseWheelEventArgs>(Mouse_WheelChanged); if (colorizer == null) _colorizer = new NetworkColorizer(); else _colorizer = colorizer; _network = network; _layout = layout; }
public static void CreatePDF(string path, Network n, PresentationSettings presentationSettings, ILayoutProvider layout) { if (presentationSettings ==null) presentationSettings = new Visualization.PresentationSettings(2000d, 1000d, 0d); PdfSharp.Pdf.PdfDocument doc = new PdfDocument(); doc.Info.Title = "Network"; doc.Info.Subject = "Created by NETGen, the cross-platform network simulation framework"; PdfPage page = doc.AddPage(); page.Size = PageSize.A4; page.Orientation = PageOrientation.Landscape; PresentationSettings newSettings = presentationSettings.Clone(); newSettings.WorldWidth = (int) page.Width.Point; newSettings.WorldHeight = (int) page.Height.Point; newSettings.VertexSize *= (int) (newSettings.WorldWidth/presentationSettings.WorldWidth); // Draw the network to the xgraphics object Draw(XGraphics.FromPdfPage(page), n, presentationSettings, layout); // Save the s_document... doc.Save(path); }
public static void SaveToEdgeFile(Network n, string path) { System.IO.StreamWriter sw = System.IO.File.CreateText(path); foreach(Edge e in n.Edges) sw.WriteLine(e.Source.Label.Replace(" ", "_") + " " + e.Target.Label.Replace(" ", "_")); sw.Close(); }
public static void TryAddTypeRelation(Network n, Type v, Type w) { if(v == null || w == null || v.FullName == null || w.FullName == null) return; Vertex v_Vert = n.SearchVertex(v.FullName); Vertex w_Vert = n.SearchVertex(w.FullName); if(v_Vert != null && w_Vert != null) n.CreateEdge(v_Vert, w_Vert, EdgeType.DirectedAB); }
/// <summary> /// The entry point of the program, where the program control starts and ends. /// </summary> /// <param name='args'> /// The command-line arguments. /// </param> public static void Main(string[] args) { int limit = 0; // Print usage information if (args.Length<3) { Console.WriteLine("Usage: MonoParser [class_number] [scan_path] [output_file]"); Console.WriteLine("\t path: \tPath of the directory to scan for assemblies"); Console.WriteLine("\t output_file: \tPath of the graphML file to produce for the resulting network"); return; } // Some error handling if (!System.IO.Directory.Exists(args[1])) { Console.WriteLine("Error: The given scan_path '{0}' is not a valid directory", args[1]); return; } limit = Int32.Parse(args[0]); try { System.IO.File.CreateText(args[2]); } catch(System.IO.IOException) { Console.WriteLine("Error: Cannot write to the specified output_file"); return; } // The network Network n = new Network(); // Scan the assemblies List<Assembly> assemblies = new List<Assembly>(); foreach(string s in System.IO.Directory.GetFiles(args[1], "*.dll", System.IO.SearchOption.AllDirectories)) { Assembly a = Assembly.LoadFile(s); assemblies.Add(a); } Console.WriteLine("Found {0} assemblies", assemblies.Count); // Scan for classes foreach(Assembly a in assemblies) foreach(Type t in a.GetTypes()) if(t.FullName!="System.Object") if((t.IsClass || t.IsInterface || t.IsAbstract) && n.VertexCount < limit) n.CreateVertex(t.FullName); Console.WriteLine("Found {0} classes", n.VertexCount); // Scan for class relations foreach(Assembly a in assemblies) foreach(Type t in a.GetTypes()) if(t.IsClass || t.IsInterface || t.IsAbstract) { Type baseType = t.BaseType; TryAddTypeRelation(n, baseType, t); foreach(Type i in t.GetInterfaces()) TryAddTypeRelation(n, i, t); } /* foreach(PropertyInfo p in t.GetProperties()) TryAddTypeRelation(n, t, p.PropertyType); foreach(FieldInfo f in t.GetFields()) TryAddTypeRelation(n, t, f.FieldType); foreach(MethodInfo m in t.GetMethods()) { ParameterInfo[] info = m.GetParameters(); MethodBody mb = m.GetMethodBody(); mb. if(mb != null) foreach(LocalVariableInfo i in m.GetMethodBody().LocalVariables) TryAddTypeRelation(n, t, i.LocalType); } */ //} Console.WriteLine("Found {0} types and {1} connections", n.VertexCount, n.EdgeCount); // n.ReduceToLargestConnectedComponent(); int maxDegree = int.MinValue; Vertex maxVertex = null; foreach(Vertex v in n.Vertices) { if(v.Degree > maxDegree) { maxDegree = v.Degree; maxVertex = v; } } Console.WriteLine(maxVertex.Label); Console.WriteLine("{0} vertices and {1} connections", n.VertexCount, n.EdgeCount); Network.SaveToGraphML(args[2], n); //NetworkVisualizer.Start(n, new FruchtermanReingoldLayout(10)); }
/// <summary> /// Loads a network from a textfile in which each edge is given by a line of whitespace- or comma-seperated strings representing two nodes /// </summary> /// <param name="path"> /// The path of the textfile /// </param> /// <returns> /// The network /// </returns> public static Network LoadFromEdgeFile(string path) { // First read all lines string[] lines = System.IO.File.ReadAllLines(path); Network net = new Network(); // Then process them in parallel System.Threading.Tasks.Parallel.ForEach(lines, s => { string[] vertices = s.Split(' ', '\t', ','); if(vertices.Length==2) { Vertex v1 = net.SearchVertex(vertices[0]); Vertex v2 = net.SearchVertex(vertices[1]); // this needs to be atomic lock(net) { if(v1 == null) v1 = net.CreateVertex(vertices[0]); if (v2 == null) v2 = net.CreateVertex(vertices[1]); } net.CreateEdge(v1, v2, EdgeType.Undirected); } }); return net; }
void HandleFileChooserNetworkFilehandleFileSet(object sender, EventArgs e) { if (this.fileChooserNetworkFile.Filename.EndsWith("cxf")) n = Network.LoadFromCXF(this.fileChooserNetworkFile.Filename); else if (this.fileChooserNetworkFile.Filename.EndsWith("graphml")) n = Network.LoadFromGraphML(this.fileChooserNetworkFile.Filename); else n = Network.LoadFromEdgeFile(this.fileChooserNetworkFile.Filename); NetworkVisualizer.Start(n, new NETGen.Layouts.RandomLayout.RandomLayout(), colorizer, 800, 600); }
public override void Init(double width, double height, Network network) { base.Init(width, height, network); foreach(Vertex v in network.Vertices) { _vertexPositions[v] = new Vector3(network.NextRandomDouble() * width, network.NextRandomDouble() * height, 1d); _newVertices.Add(v); } // Add vertex to _newVertices whenever one is added to the network network.OnVertexAdded+=new Network.VertexUpdateHandler( delegate(Vertex v) { _vertexPositions[v] = new Vector3(network.NextRandomDouble() * width, network.NextRandomDouble() * height, 1d); _newVertices.Add(v); }); }
public void DoLayout(double width, double height, Network n) { double _area = width * height; double _k = Math.Sqrt(_area / (double)n.Vertices.Count()); _k *= 0.75d; // The displacement calculated for each vertex in each step ConcurrentDictionary<Vertex, Vector3> disp = new ConcurrentDictionary<Vertex, Vector3>(System.Environment.ProcessorCount, (int) n.VertexCount); _vertexPositions = new ConcurrentDictionary<Vertex, Vector3>(System.Environment.ProcessorCount, (int) n.VertexCount); double t = width/10; double tempstep = t / (double) _iterations; Parallel.ForEach(n.Vertices.ToArray(), v=> { _vertexPositions[v] = new Vector3(n.NextRandomDouble() * width, n.NextRandomDouble() * height, 1d); disp[v] = new Vector3(0d, 0d, 1d); }); _laidout = true; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(delegate(object o) { for (int i=0; i<_iterations; i++) { // parallely Calculate repulsive forces for every pair of vertices Parallel.ForEach(n.Vertices.ToArray(), v => { disp[v] = new Vector3(0d, 0d, 1d); // computation of repulsive forces foreach(Vertex u in n.Vertices.ToArray()) { if (v != u) { Vector3 delta = _vertexPositions[v] - _vertexPositions[u]; disp[v] = disp[v] + (delta / Vector3.Length(delta)) * repulsion(Vector3.Length(delta), _k); } } }); // Parallely calculate attractive forces for all pairs of connected nodes Parallel.ForEach(n.Edges.ToArray(), e => { Vertex v = e.Source; Vertex w = e.Target; Vector3 delta = _vertexPositions[v] - _vertexPositions[w]; disp[v] = disp[v] - (delta / Vector3.Length(delta)) * attraction(Vector3.Length(delta), _k); disp[w] = disp[w] + (delta / Vector3.Length(delta)) * attraction(Vector3.Length(delta), _k); }); // Limit to frame and include temperature cooling that reduces displacement step by step Parallel.ForEach(n.Vertices.ToArray(), v => { Vector3 vPos = _vertexPositions[v] + (disp[v] / Vector3.Length(disp[v])) * Math.Min(Vector3.Length(disp[v]), t); vPos.X = Math.Min(width-10, Math.Max(10, vPos.X)); vPos.Y = Math.Min(height-10, Math.Max(10, vPos.Y)); _vertexPositions[v] = vPos; }); t-= tempstep; } })); }
public Kuramoto(Network n, double K, double UserDefinedcouplingProb, NetworkColorizer colorizer = null, Func<Vertex, Vertex[]> couplingSelector = null) : base(0d, new DenseVector((int) n.VertexCount)) { _network = n; _colorizer = colorizer; // Coupling Probability is taken from User CouplingProbability = UserDefinedcouplingProb; CouplingStrengths = new Dictionary<Tuple<Vertex, Vertex>, double>(); NaturalFrequencies = new ConcurrentDictionary<Vertex, double>(); foreach (Edge e in _network.Edges) { Tuple<Vertex,Vertex> t1 = new Tuple<Vertex, Vertex>(e.Source, e.Target); Tuple<Vertex,Vertex> t2 = new Tuple<Vertex, Vertex>(e.Target, e.Source); if(e.EdgeType == EdgeType.Undirected || e.EdgeType == EdgeType.DirectedAB) CouplingStrengths[t1] = K; if(e.EdgeType == EdgeType.Undirected || e.EdgeType == EdgeType.DirectedBA) CouplingStrengths[t2] = K; // My code modifications // Console.WriteLine(e.Source.Label+"......... "+e.Target.Label); } _mapping = new Dictionary<Vertex, int>(); int i= 0; foreach(Vertex v in _network.Vertices) { NaturalFrequencies[v] = 0.1d; _mapping[v] = i++; } // if no neighbor selector is given, just couple to all nearest neighbors if(couplingSelector==null) CouplingSelector = new Func<Vertex, Vertex[]>( v => { return v.Neigbors.ToArray(); }); else CouplingSelector = couplingSelector; // Initialize phases, colors and average degree foreach (Vertex v in _network.Vertices) { CurrentValues[_mapping[v]] = _network.NextRandomDouble() * Math.PI * 2d; if(_colorizer != null) _colorizer[v] = ColorFromPhase(CurrentValues[_mapping[v]]); _avgDeg += v.Degree; } _avgDeg /= (double) _network.VertexCount; Logger.AddMessage(LogEntryType.Info, string.Format("Sychchronization module initialized. Initial global order = {0:0.000}", GetOrder(_network.Vertices.ToArray()))); TimeDelta = Math.PI / 100d; OnStep+= new StepHandler(recolor); }
static void Main(string[] args) { string configFile, dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), netFile, NetworkFile, resFile,destResultFile; string[] path = dir.Split(new string[] { "Launch" }, StringSplitOptions.None); string srcResultFile = path[0] +"Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "result.dat"; configFile = path[0] + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "config.param.txt"; Console.WriteLine("Starting the program to generate the network based on Barbasi Albert Model.."); GlobValues glob = new GlobValues(); try { // Read parameters from param.config file read_parameters(configFile, glob); } catch (Exception e) { Console.WriteLine(e.Message); return; } for (int i = 1; i<= glob.numberOfGraphs; i++) { for (double j = glob.minPower; j <= (glob.maxPower + 0.1); j=j+0.1) { // Creating network file netFile = i+ "_BarbasiNetwork_N"+glob.nodes+ "_powerLaw"+j+"_K"+glob.couplingStrength+".edges"; NetworkFile = path[0] + "Launch" + Path.DirectorySeparatorChar + "output" + Path.DirectorySeparatorChar+netFile ; resFile = i + "_res_N" + glob.nodes + "_powerLaw" + j + "_K" + glob.couplingStrength+".dat"; destResultFile = path[0] + "Launch" + Path.DirectorySeparatorChar + "output" + Path.DirectorySeparatorChar + resFile; try { // upload the network to run the Kuramoto Model pop = Network.LoadFromEdgeFile(NetworkFile); // Run the Kuramoto model here and store the results in the output directory NetworkColorizer colorizer = new NetworkColorizer(); // Distribution of natural frequencies double mean_frequency = 1d; Normal normal = new Normal(mean_frequency, mean_frequency / 5d); sync = new Kuramoto(pop, glob.couplingStrength, glob.couplingProb, colorizer, new Func<Vertex, Vertex[]>(v => { return new Vertex[] { v.RandomNeighbor }; }) ); foreach (Vertex v in pop.Vertices) sync.NaturalFrequencies[v] = normal.Sample(); // foreach (int g in network.ClusterIDs) // pacemaker_mode[g] = false; sync.OnStep += new Kuramoto.StepHandler(recordOrder); Logger.AddMessage(LogEntryType.AppMsg, "Press enter to start synchronization experiment..."); Console.ReadLine(); // Run the simulation sync.Run(); // Write the time series to the resultfile if (srcResultFile != null) sync.WriteTimeSeries(srcResultFile); // Moving results of kuramoto model into output directory System.IO.File.Move(srcResultFile, destResultFile); } catch (Exception e) { Console.WriteLine("Error: " + e); } } } }
/// <summary> /// Saves a network to a graphML file /// </summary> /// <param name='path'> /// The path of the file /// </param> /// <param name='n'> /// The network to save /// </param> public static void SaveToGraphML(string path, Network n) { if (path == null || n == null) return; Dictionary<Guid, long> _GuidMapping = new Dictionary<Guid, long>(); XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8); writer.WriteStartDocument(); writer.WriteStartElement("graphml", "http://graphml.graphdrawing.org/xmlns"); writer.WriteStartElement("key"); writer.WriteStartAttribute("id"); writer.WriteValue("value0"); writer.WriteEndAttribute(); writer.WriteStartAttribute("for"); writer.WriteValue("node"); writer.WriteEndAttribute(); writer.WriteStartAttribute("attr.name"); writer.WriteValue("strength"); writer.WriteEndAttribute(); writer.WriteStartAttribute("attr.type"); writer.WriteValue("double"); writer.WriteEndAttribute(); writer.WriteEndElement(); writer.WriteStartElement("graph"); writer.WriteStartAttribute("id"); writer.WriteValue("g"); writer.WriteEndAttribute(); writer.WriteStartAttribute("edgedefault"); writer.WriteValue("undirected"); writer.WriteEndAttribute(); long counter = 0; foreach (Vertex v in n.Vertices) { writer.WriteStartElement("node"); writer.WriteStartAttribute("id"); _GuidMapping[v.ID] = counter++; writer.WriteValue("n" + _GuidMapping[v.ID].ToString()); writer.WriteEndAttribute(); writer.WriteStartElement("data"); writer.WriteStartAttribute("key"); writer.WriteValue("value0"); writer.WriteEndAttribute(); if (v.Tag != null) writer.WriteValue(v.Tag); else writer.WriteValue(0d); writer.WriteEndElement(); writer.WriteEndElement(); } foreach (Edge e in n.Edges) { writer.WriteStartElement("edge"); if (e.EdgeType == EdgeType.DirectedAB) { writer.WriteStartAttribute("source"); writer.WriteValue("n" + _GuidMapping[e.Source.ID].ToString()); writer.WriteEndAttribute(); writer.WriteStartAttribute("target"); writer.WriteValue("n" + _GuidMapping[e.Target.ID].ToString()); writer.WriteEndAttribute(); writer.WriteStartAttribute("directed"); writer.WriteValue("true"); writer.WriteEndAttribute(); } else if (e.EdgeType == EdgeType.DirectedBA) { writer.WriteStartAttribute("source"); writer.WriteValue("n" + _GuidMapping[e.Target.ID].ToString()); writer.WriteEndAttribute(); writer.WriteStartAttribute("target"); writer.WriteValue("n" + _GuidMapping[e.Source.ID].ToString()); writer.WriteEndAttribute(); writer.WriteStartAttribute("directed"); writer.WriteValue("true"); writer.WriteEndAttribute(); } else { writer.WriteStartAttribute("source"); writer.WriteValue("n" + _GuidMapping[e.Source.ID].ToString()); writer.WriteEndAttribute(); writer.WriteStartAttribute("target"); writer.WriteValue("n" + _GuidMapping[e.Target.ID].ToString()); writer.WriteEndAttribute(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }
public static void SaveToEdgeFile(Network n, string path) { System.IO.File.CreateText(path); foreach(Edge e in n.Edges) System.IO.File.AppendAllText(path, e.Source.Label + " " + e.Target.Label + "\n"); }
/// <summary> /// Loads a network from a GraphML file. /// </summary> /// <returns> /// A network /// </returns> /// <param name='path'> /// The path of the graphml file /// </param> public static Network LoadFromGraphML(string path) { if (path == null) return null; Network n = new Network(); XmlTextReader reader = new XmlTextReader(path); Dictionary<string, Vertex> _idMapping = new Dictionary<string,Vertex>(); while (reader.Read()) { XmlNodeType nt = reader.NodeType; if (nt == XmlNodeType.Element) { if (reader.LocalName == "node") { string id = reader.GetAttribute("id"); if (!_idMapping.ContainsKey(id)) { _idMapping[id] = new Vertex(n); n.AddVertex(_idMapping[id]); } } else if (reader.LocalName == "edge") { string sourceID = reader.GetAttribute("source"); string targetID = reader.GetAttribute("target"); Edge newEdge = new Edge(_idMapping[sourceID], _idMapping[targetID], n, EdgeType.Undirected); n.AddEdge(newEdge); } } } reader.Close(); return n; }
/// <summary> /// Loads a network from a textfile in which each edge is given by a line of whitespace- or comma-seperated strings representing two nodes /// </summary> /// <param name="path"> /// The path of the textfile /// </param> /// <returns> /// The network /// </returns> public static Network LoadFromEdgeFile(string path) { // First read all lines string[] lines = System.IO.File.ReadAllLines(path); Network net = new Network(); // Then process them in parallel System.Threading.Tasks.Parallel.ForEach(lines, s => { string[] vertices = s.Split(' ', '\t'); if(vertices.Length>=2) { Vertex v1 = net.SearchVertex(vertices[0]); Vertex v2 = net.SearchVertex(vertices[1]); // this needs to be atomic lock(net) { if(v1 == null) v1 = net.CreateVertex(vertices[0]); if (v2 == null) v2 = net.CreateVertex(vertices[1]); } Edge e = net.CreateEdge(v1, v2, EdgeType.Undirected); if (vertices.Length==3) { try { e.Weight = float.Parse(vertices[2]); } catch { Logger.AddMessage(LogEntryType.Warning, "Could not parse edge weight."); } } } }); return net; }
public static Network LoadFromCXF(string filename) { string[] cxf = System.IO.File.ReadAllLines(filename); Network n = new Network(); foreach(string s in cxf) { string type = s.Substring(0, s.IndexOf(":")); if(type=="node") { string label = ExtractNodeLabel(s); n.CreateVertex(label); // if(colorizer!= null && extractColor(s)!=Color.Empty) // colorizer[v] = extractColor(s); } else if (type=="edge") { string sourceLabel = ExtractSourceLabel (s); string targetLabel = ExtractTargetLabel (s); n.CreateEdge(n.SearchVertex(sourceLabel), n.SearchVertex(targetLabel)); } } return n; }