// Use this for initialization
    void Start()
    {
#if NO_CLUSTER
#else
        isMaster = ClusterNetwork.IsMasterOfCluster();
#endif
    }
    // Update is called once per frame
    void Update()
    {
        if (initialized)
        {
#if NO_CLUSTER
#else
            Color c = flashColor;
            if (!ClusterNetwork.IsDisconnected())
            {
                c = Color.black;
            }
            foreach (Camera cam in this.cameras)
            {
                cam.backgroundColor = c;
            }
#endif
        }
        else if (this.GetComponent <InitialisationScript>().isInitialized)
        {
            this.initialized = true;
            this.cameras     = new List <Camera>();

            foreach (Camera cam in this.GetComponentsInChildren <Camera>())
            {
                if (cam.gameObject.name.Contains("Slave Camera"))
                {
                    cameras.Add(cam);
                }
            }
        }
    }
    static void Main(string[] args)
    {
        List <double> results;
        List <double> modularity;
        string        line = "";

        System.IO.File.Delete(Properties.Settings.Default.ResultFile);

        for (double mod = Properties.Settings.Default.Modularity_From; mod <= Properties.Settings.Default.Modularity_To; mod += Properties.Settings.Default.Modularity_Step)
        {
            Console.WriteLine();
            line = "";
            for (double bias = Properties.Settings.Default.bias_from; bias <= Properties.Settings.Default.bias_to; bias += Properties.Settings.Default.bias_step)
            {
                results    = new List <double>();
                modularity = new List <double>();
                System.Threading.Tasks.Parallel.For(0, Properties.Settings.Default.runs, j =>
                {
                    ClusterNetwork net = new ClusterNetwork(Properties.Settings.Default.Nodes, Properties.Settings.Default.Edges, Properties.Settings.Default.Clusters, mod);

                    Console.WriteLine("Run {0}, created cluster network with modularity={1:0.00}", j, (net as ClusterNetwork).NewmanModularityUndirected);
                    /// TODO: Run experiment
                });
                line = string.Format(new CultureInfo("en-US").NumberFormat, "{0:0.000} {1:0.000} {2:0.000} {3:0.000} \t", MathNet.Numerics.Statistics.Statistics.Mean(modularity.ToArray()), bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()), MathNet.Numerics.Statistics.Statistics.StandardDeviation(results.ToArray()));
                System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, line + "\n");
                Console.WriteLine("Finished spreading on cluster network for modularity = {0:0.00}, bias = {1:0.00}, Average = {2:0.00}", mod, bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()));
            }
            System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, "\n");
        }
    }
    public static bool isMaster()
    {
#if UNITY_EDITOR || NO_CLUSTER
        return(true);
#else
        return(ClusterNetwork.IsMasterOfCluster());
#endif
    }
Exemple #5
0
        private static void SaveKeepalived(ClusterNetwork networkConfig, ClusterNode[] nodesConfig)
        {
            if (networkConfig == null)
            {
                ConsoleLogger.Log("[cluster] keepalived not configured: missing network parameters");
                return;
            }
            if (!networkConfig.Active)
            {
                ConsoleLogger.Log("[cluster] shared network is disabled");
                return;
            }
            var ports = networkConfig.PortMapping;

            if (!ports.Any())
            {
                ConsoleLogger.Log("[cluster] exit: !ports.Any()");
                return;
            }

            ConsoleLogger.Log("[cluster] init keepalived");
            const string keepalivedService = "keepalived.service";

            if (Systemctl.IsActive(keepalivedService))
            {
                ConsoleLogger.Log("[cluster] stop service");
                Systemctl.Stop(keepalivedService);
            }
            ConsoleLogger.Log("[cluster] set configuration file");
            var lines = new string[] {
                "vrrp_script chk_haproxy {",
                "    script \"killall -0 haproxy\"",
                "    interval 30",
                "    weight 2",
                "}",
                "",
                "vrrp_instance RH_INT {",
                $"    interface {networkConfig.NetworkInterface}",
                "    state MASTER",
                "    virtual_router_id 51",
                $"    priority 100",
                "    virtual_ipaddress {",
                $"        {networkConfig.VirtualIpAddress}",
                "    }",
                "    track_script {",
                "        chk_haproxy",
                "    }",
                "}",
            };

            File.WriteAllLines(keepalivedFileOutput, lines);
            Keepalived.Stop();
            Keepalived.Start(keepalivedFileOutput);
        }
 // Use this for initialization
 void Start()
 {
     ClusterInput.AddInput("MouseTestX", "testDevice1", "10.0.1.28", 0, ClusterInputType.CustomProvidedInput);
     ClusterInput.AddInput("MouseTestY", "testDevice2", "10.0.1.28", 0, ClusterInputType.CustomProvidedInput);
     if (ClusterNetwork.IsMasterOfCluster())
     {
         Debug.Log("I am the cluster master");
     }
     else
     {
         Debug.Log("I am the cluster slave");
     }
 }
    // Update is called once per frame
    void Update()
    {
        if (ClusterNetwork.IsMasterOfCluster())
        {
            Vector3 mousepos = Input.mousePosition;
            mousepos.x /= Screen.width;
            mousepos.y /= Screen.height;
            ClusterInput.SetAxis("MouseTestX", mousepos.x);
            ClusterInput.SetAxis("MouseTestY", mousepos.y);
            Debug.Log("SetAxis to" + mousepos.ToString());
        }

        Vector2 pos = new Vector2();

        pos.x = ClusterInput.GetAxis("MouseTestX");
        pos.y = ClusterInput.GetAxis("MouseTestY");
        this.transform.position = new Vector3(pos.x, pos.y, 5.0f);
        Debug.Log("getAxis" + pos.ToString());
    }
        public void TestClusterNetwork()
        {
            ClusterNetwork network = new ClusterNetwork(2000, 5000, 100, 0.9d, false);

            Assert.LessOrEqual(Math.Abs(network.NewmanModularityUndirected - 0.9d), 0.02);
            Assert.LessOrEqual(Math.Abs(network.EdgeCount - 5000), 200);
            Assert.AreEqual(network.VertexCount, 2000);
            Assert.AreEqual(network.ClusterIDs.Length, 100);
            Assert.AreEqual(network.EdgeCount, network.InterClusterEdgeNumber + network.IntraClusterEdgeNumber);
            try{
                foreach (Edge e in network.IntraClusterEdges)
                {
                    int id1 = network.GetClusterForNode(e.Source);
                    int id2 = network.GetClusterForNode(e.Target);
                    Assert.AreEqual(id1, id2);
                }
                foreach (Edge e in network.InterClusterEdges)
                {
                    int id1 = network.GetClusterForNode(e.Source);
                    int id2 = network.GetClusterForNode(e.Target);
                    Assert.AreNotEqual(id1, id2);
                }
                foreach (Vertex v in network.Vertices)
                {
                    int id = network.GetClusterForNode(v);
                    Assert.LessOrEqual(id, network.ClusterIDs.Length);
                }
                List <Vertex> vertices = new List <Vertex>();
                foreach (int id in network.ClusterIDs)
                {
                    vertices.AddRange(network.GetNodesInCluster(id));
                }
                Assert.AreEqual(vertices.Count, network.VertexCount);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #9
0
 /// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the value to convert into an instance of <see cref="ClusterNetwork" />.</param>
 /// <returns>
 /// an instance of <see cref="ClusterNetwork" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public static object ConvertFrom(dynamic sourceValue)
 {
     if (null == sourceValue)
     {
         return(null);
     }
     try
     {
         ClusterNetwork.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());
     }
     catch
     {
         // Unable to use JSON pattern
     }
     try
     {
         return(new ClusterNetwork
         {
             DomainServer = ClusterDomainServerTypeConverter.ConvertFrom(sourceValue.DomainServer),
             ExternalDataServicesIp = sourceValue.ExternalDataServicesIp,
             ExternalIp = sourceValue.ExternalIp,
             ExternalSubnet = sourceValue.ExternalSubnet,
             HttpProxyList = sourceValue.HttpProxyList,
             HttpProxyWhitelist = sourceValue.HttpProxyWhitelist,
             InternalSubnet = sourceValue.InternalSubnet,
             MasqueradingIp = sourceValue.MasqueradingIp,
             MasqueradingPort = sourceValue.MasqueradingPort,
             NameServerIpList = sourceValue.NameServerIpList,
             NfsSubnetWhitelist = sourceValue.NfsSubnetWhitelist,
             NtpServerIpList = sourceValue.NtpServerIpList,
             SmtpServer = SmtpServerTypeConverter.ConvertFrom(sourceValue.SmtpServer),
         });
     }
     catch
     {
     }
     return(null);
 }
Exemple #10
0
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: ModularityComputation [network_file] [directed=false] [visualize=false] [reduce_to_LCC=false]");
                return;
            }

            bool directed = false;

            if (args.Length >= 2)
            {
                directed = Boolean.Parse(args[1]);
            }

            ClusterNetwork n = ClusterNetwork.LoadNetwork(args[0], directed);

            if (args.Length > 3 && Boolean.Parse(args[3]) == true)
            {
                n.ReduceToLargestConnectedComponent();
            }

            if (directed)
            {
                Console.WriteLine("Q = {0:0.0000000}", n.NewmanModularityDirected);
            }
            else
            {
                Console.WriteLine("Q = {0:0.0000000}", n.NewmanModularityUndirected);
            }

            if (args.Length > 2 && Boolean.Parse(args[2]) == true)
            {
                NETGen.Visualization.NetworkVisualizer.Start(n, new NETGen.Layouts.FruchtermanReingold.FruchtermanReingoldLayout(10), new NETGen.Visualization.NetworkColorizer(), 800, 600);
                NETGen.Visualization.NetworkVisualizer.Layout.DoLayout();
            }
        }
Exemple #11
0
        private static void SaveHaproxy(ClusterNetwork networkConfig, ClusterNode[] nodesConfig)
        {
            if (networkConfig == null)
            {
                ConsoleLogger.Warn("[cluster] haproxy not configured: missing network parameters");
                return;
            }
            if (!networkConfig.Active)
            {
                ConsoleLogger.Warn("[cluster] shared network is disabled");
                return;
            }
            var ports = networkConfig.PortMapping;

            if (!ports.Any())
            {
                ConsoleLogger.Warn("[cluster] exit: !ports.Any()");
                return;
            }

            ConsoleLogger.Log("[cluster] init haproxy");
            var lines = new List <string> {
                "global",
                "    daemon",
                "    log 127.0.0.1   local0",
                "    log 127.0.0.1   local1 notice",
                "    maxconn 4096",
                "    user haproxy",
                "    group haproxy",
                "",
                "defaults",
                "    log     global",
                "    mode    http",
                "    option  httplog",
                "    option  dontlognull",
                "    retries 3",
                "    option  redispatch",
                "    maxconn 2000",
                "    timeout connect 5000",
                "    timeout client  50000",
                "    timeout server  50000",
                ""
            };
            //var localServices = Application.CurrentConfiguration.Cluster.Nodes.FirstOrDefault(_ => _.MachineUid == Application.CurrentConfiguration.Host.MachineUid.ToString()).Services;
            //if(localServices != null) {
            int errorStateCounter = 0;

            for (var i = 0; i < ports.Length; i++)
            {
                var port = ports[i];
                //port.ServicePort = localServices.FirstOrDefault(_ => _.Name == port.ServiceName)?.Port.ToString();
                if (string.IsNullOrEmpty(port.ServicePort))
                {
                    errorStateCounter++;
                    ConsoleLogger.Warn($"[cluster] haproxy source port is not defined for '{port.ServiceName}'");
                    continue;
                }
                if (string.IsNullOrEmpty(port.VirtualPort))
                {
                    ConsoleLogger.Warn($"[cluster] haproxy virtual port is not defined for '{port.ServiceName}'");
                    errorStateCounter++;
                    continue;
                }
                var frontEndLabel = $"fe_in{port.ServicePort}_out{port.VirtualPort}";
                var backEndLabel  = $"be_in{port.ServicePort}_out{port.VirtualPort}";
                ConsoleLogger.Log($"[cluster] {port.ServiceName} virtual port: {port.VirtualPort} as {port.ServicePort}");
                lines.Add($"frontend {frontEndLabel}");
                lines.Add("    mode http");
                lines.Add($"    bind {networkConfig.VirtualIpAddress}:{port.VirtualPort} transparent");
                lines.Add("    stats enable");
                lines.Add("    stats auth admin:Anthilla");
                lines.Add("    option httpclose");
                lines.Add("    option forwardfor");
                lines.Add($"    default_backend {backEndLabel}");
                lines.Add("");
                lines.Add($"backend {backEndLabel}");
                lines.Add("    balance roundrobin");
                lines.Add("    cookie JSESSIONID prefix");
                //lines.Add("    option httpchk HEAD /check.txt HTTP/1.0");
                for (var n = 0; n < nodesConfig.Length; n++)
                {
                    var node = nodesConfig[n];
                    lines.Add($"    server {node.Hostname} {node.PublicIp}:{port.ServicePort} check");
                }
                lines.Add("");
            }
            //}
            //else {
            //    ConsoleLogger.Warn("[cluster] local service does not exist");
            //    return;
            //}

            if (errorStateCounter == ports.Length)
            {
                ConsoleLogger.Log("[cluster] failed to configure haproxy: port mapping list is empty");
                return;
            }
            File.WriteAllLines(haproxyFileOutput, lines);
            Haproxy.Stop();
            Haproxy.Start(haproxyFileOutput);
            ConsoleLogger.Log("[cluster] haproxy started");
        }
Exemple #12
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);
        }
    }
Exemple #13
0
        public override void RunSimulation()
        {
            empirical_network = ClusterNetwork.LoadNetwork(PrjName + "_network.edges", true);

            simulated_network = ClusterNetwork.LoadNetwork(PrjName + "_network.edges", true);

            //assign module membership deterministically for the simulated network
            int my_V      = 0;
            int NClusters = simulated_network.GetClustersCount;

            foreach (Vertex v in simulated_network.Vertices)
            {
                simulated_module_assignments[v] = my_V++ % NClusters;
            }

            //shuffle the dictionary to provide a randomized assignment making sure all modules are present
            Random rand = new Random();

            simulated_module_assignments = simulated_module_assignments.OrderBy(x => rand.Next()).ToDictionary(item => item.Key, item => item.Value);

            //run the simulation
            int time = 0;

            //System.IO.StreamWriter file = new System.IO.StreamWriter(PrjName + "out.txt");
            while (time < Steps)
            {
                Change();
                time++;
                //simulated_network.ResetClusters(simulated_module_assignments);
                //file.WriteLine("{0} {1} {2} {3} {4}",T, simulated_network.NewmanModularityDirected, simulated_network.EdgeCount, simulated_network.InterClusterEdgeNumber, simulated_network.IntraClusterEdgeNumber);
                //foreach(Vertex v in simulated_network.Vertices)
                //	simulated_module_assignments[v] = simulated_network.GetClusterForNode(v);
            }
            //file.Close();

            //shrink the clusterIDs to account for the possibility of the existance of empty modules
            simulated_network.ResetClusters(simulated_module_assignments);

            //results
            n_nodes = empirical_network.VertexCount;
            n_edges = empirical_network.EdgeCount;

            n_modules_e = empirical_network.GetClustersCount;
            n_modules_s = simulated_network.GetClustersCount;

            q_e = empirical_network.NewmanModularityDirected;
            q_s = simulated_network.NewmanModularityDirected;

            o_p = 0d;
            o_m = 0d;
            Vertex s_v;
            Vertex s_w;

            foreach (Vertex e_v in empirical_network.Vertices)
            {
                foreach (Vertex e_w in empirical_network.Vertices)
                {
                    if (e_v != e_w)
                    {
                        s_v = simulated_network.SearchVertex(e_v.Label);
                        s_w = simulated_network.SearchVertex(e_w.Label);

                        if ((simulated_network.GetClusterForNode(s_v) == simulated_network.GetClusterForNode(s_w)) && (empirical_network.GetClusterForNode(e_v) == empirical_network.GetClusterForNode(e_w)))
                        {
                            o_p++;
                        }
                        else
                        {
                            if ((simulated_network.GetClusterForNode(s_v) != simulated_network.GetClusterForNode(s_w)) && (empirical_network.GetClusterForNode(e_v) != empirical_network.GetClusterForNode(e_w)))
                            {
                                o_m++;
                            }
                        }
                    }
                }
            }
            o_p /= ((n_nodes * n_nodes) - n_nodes);
            o_m /= ((n_nodes * n_nodes) - n_nodes);

            av_module_s_e = empirical_network.GetAverageClusterSize;
            av_module_s_s = simulated_network.GetAverageClusterSize;

            sd_module_s_e = empirical_network.GetStandardDeviationClusterSize;
            sd_module_s_s = simulated_network.GetStandardDeviationClusterSize;

            av_n_module_s_e = empirical_network.GetAverageNodeClusterSize;
            av_n_module_s_s = simulated_network.GetAverageNodeClusterSize;

            sd_n_module_s_e = empirical_network.GetStandardDeviationNodeClusterSize;
            sd_n_module_s_s = simulated_network.GetStandardDeviationNodeClusterSize;

            n_inter_edges_e = empirical_network.InterClusterEdgeNumber;
            n_intra_edges_e = empirical_network.IntraClusterEdgeNumber;

            n_inter_edges_s = simulated_network.InterClusterEdgeNumber;
            n_intra_edges_s = simulated_network.IntraClusterEdgeNumber;
        }
Exemple #14
0
    private static AggregationResult RunAggregation(ClusterNetwork net, double bias)
    {
        Dictionary <Vertex, double> _attributes = new Dictionary <Vertex, double>();
        Dictionary <Vertex, double> _aggregates = new Dictionary <Vertex, double>();

        MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(0d, 5d);

        AggregationResult result = new AggregationResult();

        result.Modularity = net.NewmanModularityUndirected;

        double average = 0d;

        foreach (Vertex v in net.Vertices)
        {
            _attributes[v] = normal.Sample();
            _aggregates[v] = _attributes[v];
            average       += _attributes[v];
        }
        average /= (double)net.VertexCount;

        double avgEstimate = double.MaxValue;

        result.FinalVariance = double.MaxValue;
        result.FinalOffset   = 0d;

        for (int k = 0; k < Properties.Settings.Default.ConsensusRounds; k++)
        {
            foreach (Vertex v in net.Vertices.ToArray())
            {
                Vertex        w = v.RandomNeighbor;
                List <Vertex> intraNeighbors = new List <Vertex>();
                List <Vertex> interNeighbors = new List <Vertex>();
                ClassifyNeighbors(net, v, intraNeighbors, interNeighbors);

                double r = net.NextRandomDouble();
                if (r <= bias && interNeighbors.Count > 0)
                {
                    w = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count));
                }

                _aggregates[v] = aggregate(_aggregates[v], _aggregates[w]);
                _aggregates[w] = aggregate(_aggregates[v], _aggregates[w]);
            }

            avgEstimate = 0d;
            foreach (Vertex v in net.Vertices.ToArray())
            {
                avgEstimate += _aggregates[v];
            }
            avgEstimate /= (double)net.VertexCount;

            result.FinalVariance = 0d;
            foreach (Vertex v in net.Vertices.ToArray())
            {
                result.FinalVariance += Math.Pow(_aggregates[v] - avgEstimate, 2d);
            }
            result.FinalVariance /= (double)net.VertexCount;

            double intraVar = 0d;
            foreach (int c in net.ClusterIDs)
            {
                double localavg = 0d;
                double localvar = 0d;

                foreach (Vertex v in net.GetNodesInCluster(c))
                {
                    localavg += _aggregates[v];
                }
                localavg /= net.GetClusterSize(c);

                foreach (Vertex v in net.GetNodesInCluster(c))
                {
                    localvar += Math.Pow(_aggregates[v] - localavg, 2d);
                }
                localvar /= net.GetClusterSize(c);

                intraVar += localvar;
            }
            intraVar /= 50d;

            //Console.WriteLine("i = {0:0000}, Avg = {1:0.000}, Estimate = {2:0.000}, Intra-Var = {3:0.000}, Total Var = {4:0.000}", result.iterations, average, avgEstimate, intraVar, totalVar);
        }
        result.FinalOffset = average - avgEstimate;

        return(result);
    }
Exemple #15
0
    /// <summary>
    /// Runs the cluster synchronization experiments, reading simulation parameters from the .config file
    /// </summary>
    public override void RunSimulation()
    {
        // Setup the experiment by creating the network and the synchronization module
        ClusterNetwork net  = new ClusterNetwork(nodes, edges, clusters, modularity_tgt, true);
        Kuramoto       sync = new Kuramoto(net, K);

        // Couple to single random neighbor in each step
        sync.CouplingSelector = new Func <Vertex, Vertex[]>(v => {
            return(new Vertex[] { v.RandomNeighbor });
        });

        // Keeps track whether clusters have already switched to pacemaker mode
        Dictionary <int, bool> pacemaker_mode = new Dictionary <int, bool>();

        // Mixed distribution of natural frequencies
        Normal group_avgs = new Normal(global_mean, global_mean * global_mean_width_factor);

        foreach (int i in net.ClusterIDs)
        {
            double group_avg  = group_avgs.Sample();
            Normal group_dist = new Normal(group_avg, group_avg * cluster_width_factor);
            foreach (Vertex v in net.GetNodesInCluster(i))
            {
                sync.NaturalFrequencies[v] = group_dist.Sample();
            }
            pacemaker_mode[i] = false;
        }

        // Set up handler that will be called AFTER each simulation step
        sync.OnStep += new Kuramoto.StepHandler(
            delegate(double t)
        {
            // Compute global order parameter
            finalOrderParam = sync.GetOrder(net.Vertices.ToArray());

            normalizerIntegratedOrder += finalOrderParam;

            // Record order evolution
            sync.AddDataPoint("GlobalOrder", finalOrderParam);

            // Stop simulation if full ordered state is reached or time exceeded
            if (finalOrderParam >= orderThres || t > timeThres)
            {
                sync.Stop();
            }

            // Output will only been shown when pyspg module is started in debug mode
            //if(t % (sync.TimeDelta * 100d) == 0)
            Logger.AddMessage(LogEntryType.SimMsg, string.Format("Time {0}, Order = {1:0.00}", t, finalOrderParam));

            // Compute order parameter of individual clusters
            foreach (int g in net.ClusterIDs)
            {
                double localOrder = sync.GetOrder(net.GetNodesInCluster(g));
                sync.AddDataPoint(string.Format("ClusterOrder_{0}", g), localOrder);

                // Switch to pacemaker mode if cluster order exceeds threshold
                if (localOrder > orderThres && !pacemaker_mode[g])
                {
                    pacemaker_mode[g] = true;

                    // Probabilistically switch border nodes to pacemaker mode
                    // Note: CouplingStrengths[... v, w ... ] is the strength by which phase advance of v is influenced when coupling to node w
                    foreach (Vertex v in net.GetNodesInCluster(g))
                    {
                        if (net.HasInterClusterConnection(v))
                        {
                            foreach (Vertex w in v.Neigbors)
                            {
                                if (!net.HasInterClusterConnection(w) && net.NextRandomDouble() <= pacemakerProb)
                                {
                                    Logger.AddMessage(LogEntryType.AppMsg, string.Format("Vertex switched to pacemaker mode", g));
                                    sync.CouplingStrengths[new Tuple <Vertex, Vertex>(v, w)] = 0d;
                                }
                            }
                        }
                    }
                }
            }
        });

        // compute coupling density in the initial situation
        initialDensity = 0d;
        foreach (var t in sync.CouplingStrengths.Keys)
        {
            initialDensity += sync.CouplingStrengths[t];
        }

        // Synchronously run the experiment (blocks execution until experiment is finished)
        sync.Run();

        // compute final coupling density
        finalDensity = 0d;
        foreach (var t in sync.CouplingStrengths.Keys)
        {
            finalDensity += sync.CouplingStrengths[t];
        }

        // Write time-series of the order parameters (global and cluster-wise) to a file
        sync.WriteTimeSeries(dynamics);

        // Set results
        normalizerIntegratedOrder /= sync.Time;
        time            = sync.Time;
        finalOrderParam = sync.GetOrder(net.Vertices.ToArray());
        modularity_real = net.NewmanModularityUndirected;
    }