Esempio n. 1
0
        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;
        }
Esempio n. 2
0
        private static void DrawEdge(XGraphics g, Edge e, LayoutProvider layout, NetworkColorizer colorizer)
        {
            Vector3 p1 = layout.GetPositionOfNode(e.Source);
            Vector3 p2 = layout.GetPositionOfNode(e.Target);

            g.DrawLine(new Pen(colorizer[e], 0.05f), p1.X, p1.Y, p2.X, p2.Y);
        }
Esempio n. 3
0
        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;
            }
        }
Esempio n. 4
0
 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.");
 }
Esempio n. 5
0
        private static void DrawEdge(XGraphics g, Edge e, LayoutProvider layout, NetworkColorizer colorizer)
        {
            Vector3 p1 = layout.GetPositionOfNode(e.Source);
            Vector3 p2 = layout.GetPositionOfNode(e.Target);

            float width = ComputeEdgeWidth(e);

            g.DrawLine(new Pen(colorizer[e], width), p1.X, p1.Y, p2.X, p2.Y);
        }
Esempio n. 6
0
        public SIRSpreading(Network n, NetworkColorizer colorizer = null)
        {
            _network = n;
            _colorizer = colorizer;

            _active = new List<Vertex>();
            _infected = new List<Vertex>();
            _infections = new Dictionary<Vertex, bool>();
        }
Esempio n. 7
0
        private static void DrawVertex(XGraphics g, Vertex v, LayoutProvider layout, NetworkColorizer colorizer)
        {
            Vector3 p = layout.GetPositionOfNode(v);

            double size = Math.Min(2f, Math.Max(0.05d, Math.Log10(v.Degree)));

            if (!double.IsNaN(p.X) &&
               !double.IsNaN(p.Y) &&
               !double.IsNaN(p.Z))
                g.DrawEllipse(new SolidBrush(colorizer[v]), p.X - size/2d, p.Y - size/2d, size, size);
        }
Esempio n. 8
0
        private static void DrawVertex(XGraphics g, Vertex v, LayoutProvider layout, NetworkColorizer colorizer)
        {
            Vector3 p = layout.GetPositionOfNode(v);

            double size = ComputeNodeSize(v);

            if (!double.IsNaN(p.X) &&
                !double.IsNaN(p.Y) &&
                !double.IsNaN(p.Z))
            {
                g.DrawEllipse(new SolidBrush(colorizer[v]), p.X - size / 2d, p.Y - size / 2d, size, size);
            }
        }
Esempio n. 9
0
        /// <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();
        }
Esempio n. 10
0
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);
            }
}
Esempio n. 11
0
        /// <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, LayoutProvider 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() {
                Instance = new NetworkVisualizer(network, layout, colorizer, width, height);
                _initialized.Set();
                Instance.Run(80f);
            })));

            _mainThread.SetApartmentState(ApartmentState.STA);
            _mainThread.Name = "STA Thread for NETGen Visualizer";

            // Fire up the thread
            _mainThread.Start();
            _initialized.WaitOne();
        }
Esempio n. 12
0
        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);
        }
Esempio n. 13
0
        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;
        }
Esempio n. 14
0
        public VisualizerControl()
            : base(Gtk.WindowType.Toplevel)
        {
            this.Build ();

            colorizer = new	NetworkColorizer();
            this.fileChooserNetworkFile.FileSet += HandleFileChooserNetworkFilehandleFileSet;
            this.btnComputeLayout.Clicked+= HandleBtnComputeLayouthandleClicked;
            this.btnChoseDefaultNodeColor.ColorSet += HandleBtnChoseDefaultNodeColorhandleColorSet;
            this.btnChoseEdgeColor.ColorSet += HandleBtnChoseEdgeColorhandleColorSet;
            this.btnSearch.Clicked += HandleBtnSearchhandleClicked;
            this.fileChooserExportPDF.FileSet+= HandleFileChooserExportPDFhandleFileSet;
            this.fileChooserExportBitmap.FileSet += HandleFileChooserExportBitmaphandleFileSet;
            this.fileChooserHighlightNodes.FileSet += HandleFileChooserHighlightNodeshandleFileSet;
            this.btnApplyNodeSize.Clicked += HandleBtnApplyNodeSizehandleClicked;
            this.btnApplyEdgeWidth.Clicked += HandleBtnApplyEdgeWidthhandleClicked;
            this.fileChooserCEFFile.FileSet += HandleFileChooserCEFFilehandleFileSet;
            this.btnRunCEF.Clicked += HandlebtnRunCEFhandleClicked;
        }
Esempio n. 15
0
 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);
         }
     }
 }
Esempio n. 16
0
        public static void CreatePDF(string path, Network n, LayoutProvider layout, NetworkColorizer colorizer = null)
        {
            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;

            if (colorizer != null)
            {
                // Draw the network to the xgraphics object
                Draw(XGraphics.FromPdfPage(page), n, layout, colorizer);
            }
            else
            {
                Draw(XGraphics.FromPdfPage(page), n, layout, new NetworkColorizer());
            }

            // Save the s_document...
            doc.Save(path);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            GlobValues glob = new GlobValues();
            string configFile, dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), inputPath, outputPath;
            String[] path = dir.Split(new string[] { "Launch" }, StringSplitOptions.None);
            inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "input";
            configFile = inputPath + Path.DirectorySeparatorChar + "config.param.txt";
               // outputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "output";
            Console.WriteLine("File is : " + configFile);

            Console.WriteLine("Starting the program to generate the network based on modularity..");
            try
            {
                // Read parameters from param.config file

                read_parameters(configFile, glob);
            }
            catch
            {
                Console.WriteLine("Usage: mono Demo.exe [nodes] [edges] [clusters] [resultfile]");
                return;
            }

            // Displays the information

            Console.WriteLine("Given Parameter values");
            Console.WriteLine("\n Nodes: " + glob.nodes + "\n Edges: " + glob.edges + "\n Clusters: " + glob.clusters + "\n Modularity MinValue: " + glob.modularityMinValue + "\n Modularity MaxValue: " + glob.modularityMaxValue);
            Console.WriteLine(" Number of runs: " + glob.numberOfGraphs + "\n Coupling probability value: "+glob.couplingProb*100);

            string sourceNetworkFile = inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "network.edges";

            string sourceResultFile = inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "result.dat";

            // For loop to make n number of Networks with the given size and modularity ...
            double modularity = glob.modularityMinValue;

            while (modularity <= glob.modularityMaxValue)
            {
                String outputFile = "Result_M" + modularity;
                outputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + outputFile;
                System.IO.Directory.CreateDirectory(outputPath);

                try
                {

                    for (int n = 1; n <= glob.numberOfGraphs; n++)
                    {
                        network = new ClusterNetwork(glob.nodes, glob.edges, glob.clusters, modularity, true);

                        // Restricting the modularity value upto 1 decimal place
                       // modularity = Math.Round(network.NewmanModularityUndirected, 1);

                        String memberOutputFile = outputPath + Path.DirectorySeparatorChar + "membership.dat";
                        System.IO.StreamWriter sw = System.IO.File.CreateText(memberOutputFile);
                        int i = 0;
                        foreach (Vertex v in network.Vertices)
                        {
                            v.Label = (i++).ToString();
                            sw.WriteLine(network.GetClusterForNode(v).ToString());
                        }
                        sw.Close();
                        Network.SaveToEdgeFile(network, "network.edges");
                        Console.WriteLine("Created network with {0} vertices, {1} edges and modularity {2:0.00}", network.VertexCount, network.EdgeCount, modularity);
                        // To move a file or folder to a new location without renaming it. We rename the files after running the Kuramoto model.

                        string destinationResultFile = outputPath + Path.DirectorySeparatorChar + n + "_res_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".dat";
                        string destinationNetworkFile = outputPath + Path.DirectorySeparatorChar + n + "_network_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".edges";

                        System.IO.File.Move(outputPath + Path.DirectorySeparatorChar + "membership.dat", outputPath + Path.DirectorySeparatorChar + n + "_mem_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".dat");
                        try
                        {
                            Console.WriteLine("Moving the generated files to output directory..");
                            System.IO.File.Move(sourceNetworkFile, destinationNetworkFile);
                        }
                        catch (IOException e)
                        {
                            Console.WriteLine(e.Message);
                        }

                        // 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(network,
                                        glob.couplingStrength,
                                        glob.couplingProb,
                                        colorizer,
                                        new Func<Vertex, Vertex[]>(v => { return new Vertex[] { v.RandomNeighbor }; })
                                        );

                        foreach (Vertex v in network.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 (sourceResultFile != null)
                            sync.WriteTimeSeries(sourceResultFile);

                        // Moving results of kuramoto model into output directory
                        System.IO.File.Move(sourceResultFile, destinationResultFile);

                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: " + e);
                }
                modularity = modularity + 0.1;
            }
            // End line of the program
            Console.WriteLine("Program ended successfully..");
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            double bias;
            try{
                    // The neighbor selection bias is given as command line argument
                    bias1 = double.Parse(args[0]);
                    bias2 = double.Parse(args[1]);
            }
            catch(Exception)
            {
                Console.WriteLine("Usage: mono ./DemoSimulation.exe [initial_bias] [secondary_bias]");
                return;
            }

            // The number of clusters (c) and the nodes within a cluster (Nc)
            int c = 20;
            int Nc = 20;

            // The number of desired edges
            int m = 6 * c * Nc;

            // In order to yield a connected network, at least ...
            double inter_thresh = 3d * ((c * Math.Log(c)) / 2d);
                // ... edges between communities are required

            // So the maximum number of edges within communities we s create is ...
            double intra_edges = m - inter_thresh;

            Console.WriteLine("Number of intra_edge pairs = " + c * Combinatorics.Combinations(Nc, 2));
            Console.WriteLine("Number of inter_edge pairs = " + (Combinatorics.Combinations(c * Nc, 2) - (c * Combinatorics.Combinations(Nc, 2))));

            // Calculate the p_i necessary to yield the desired number of intra_edges
            double pi =  intra_edges / (c * Combinatorics.Combinations(Nc, 2));

            // From this we can compute p_e ...
            double p_e = (m - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2) * pi) / (Combinatorics.Combinations(c * Nc, 2) - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2));
            Console.WriteLine("Generating cluster network with p_i = {0:0.0000}, p_e = {1:0.0000}", pi, p_e);

            // Create the network ...
            network = new NETGen.NetworkModels.Cluster.ClusterNetwork(c, Nc, pi, p_e);

            // ... and reduce it to the GCC
            network.ReduceToLargestConnectedComponent();

            Console.WriteLine("Created network has {0} vertices and {1} edges. Modularity = {2:0.00}", network.VertexCount, network.EdgeCount, network.NewmanModularity);

            // Run the OopenGL visualization
            NetworkColorizer colorizer = new NetworkColorizer();
            NetworkVisualizer.Start(network, new FruchtermanReingoldLayout(15), colorizer);

            currentBias = bias1;

            // Setup the synchronization simulation, passing the bias strategy as a lambda expression
            sync = new EpidemicSynchronization(
                network,
                colorizer,
                v => {
                    Vertex neighbor = v.RandomNeighbor;
                    double r = network.NextRandomDouble();

                    // classify neighbors
                    List<Vertex> intraNeighbors = new List<Vertex>();
                    List<Vertex> interNeighbors = new List<Vertex>();
                    ClassifyNeighbors(network, v, intraNeighbors, interNeighbors);

                    neighbor = intraNeighbors.ElementAt(network.NextRandom(intraNeighbors.Count));

                    // biasing strategy ...
                    if (r <= currentBias && interNeighbors.Count > 0)
                        neighbor = interNeighbors.ElementAt(network.NextRandom(interNeighbors.Count));

                    return neighbor;
                },
                0.9d);

            Dictionary<int, double> _groupMus = new Dictionary<int, double>();
            Dictionary<int, double> _groupSigmas = new Dictionary<int, double>();

            MathNet.Numerics.Distributions.Normal avgs_normal = new MathNet.Numerics.Distributions.Normal(300d, 50d);
            MathNet.Numerics.Distributions.Normal devs_normal = new MathNet.Numerics.Distributions.Normal(20d, 5d);

            for(int i=0; i<c; i++)
            {
                double groupAvg = avgs_normal.Sample();
                double groupStdDev = devs_normal.Sample();

                foreach(Vertex v in network.GetNodesInCluster(i))
                {
                    sync._MuPeriods[v] = groupAvg;
                    sync._SigmaPeriods[v] = groupStdDev;
                }
            }

            sync.OnStep+=new EpidemicSynchronization.StepHandler(collectLocalOrder);

            // Run the simulation synchronously
            sync.Run();

            Console.ReadKey();

            // Collect and print the results
            SyncResults res = sync.Collect();
               	Console.WriteLine("Order {0:0.00} reached after {1} rounds", res.order, res.time);
        }
        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);
                            }

               }
             }
        }
Esempio n. 20
0
        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);
        }
Esempio n. 21
0
    static void Main(string[] args)
    {
        try
        {
            // The resultfile is given as command line argument
            //nodes = Int32.Parse(args[0]);
            //edges = Int32.Parse(args[1]);
            //clusters = Int32.Parse(args[2]);
            resultfile = args[3];
        } catch {
            Console.WriteLine("Usage: mono Demo.exe [nodes] [edges] [clusters] [resultfile]");
            return;
        }

        // Create a network of the given size and modularity ...
        network = new ClusterNetwork(nodes, edges, clusters, 0.63d, true);

        System.IO.StreamWriter sw = System.IO.File.CreateText("membership.dat");

        int i = 0;
        foreach (Vertex v in network.Vertices)
        {
            v.Label = (i++).ToString();
            sw.WriteLine(network.GetClusterForNode(v).ToString());
        }
        sw.Close();

        Network.SaveToEdgeFile(network, "network.edges");

        Console.WriteLine("Created network with {0} vertices, {1} edges and modularity {2:0.00}", network.VertexCount, network.EdgeCount, network.NewmanModularityUndirected);

        // Run the real-time visualization
        NetworkColorizer colorizer = new NetworkColorizer();
        //NetworkVisualizer.Start(network, new NETGen.Layouts.FruchtermanReingold.FruchtermanReingoldLayout(15), colorizer);
        //NetworkVisualizer.Layout.DoLayoutAsync();

        // Distribution of natural frequencies
        double mean_frequency = 1d;
        Normal normal = new Normal(mean_frequency, mean_frequency/5d);

        sync = new Kuramoto(	network,
                                K,
                                colorizer,
                                new Func<Vertex, Vertex[]>(v => { return new Vertex[] {v.RandomNeighbor}; })
                                );

        foreach(Vertex v in network.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(resultfile!=null)
            sync.WriteTimeSeries(resultfile);
    }
Esempio n. 22
0
private static void DrawVertex(XGraphics g, Vertex v, LayoutProvider layout, NetworkColorizer colorizer)
{
    Vector3 p = layout.GetPositionOfNode(v);

            double size = ComputeNodeSize(v);

            if (!double.IsNaN(p.X) &&
               !double.IsNaN(p.Y) &&
               !double.IsNaN(p.Z))
                g.DrawEllipse(new SolidBrush(colorizer[v]), p.X - size/2d, p.Y - size/2d, size, size);
}