Esempio n. 1
0
    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");
        }
    }
Esempio n. 2
0
        public static SpreadingResult RunSpreading(ClusterNetwork net, double bias, int delay=0)
        {
            SpreadingResult res = new SpreadingResult();

            Dictionary<Vertex, int> infectionTime = new Dictionary<Vertex, int>();
            foreach (Vertex v in net.Vertices)
                infectionTime[v] = int.MinValue;

            List<Vertex> infected = new List<Vertex>();

            Vertex seed = net.RandomVertex;
            infected.Add(seed);

            int i = 0;

            while (infected.Count < net.VertexCount)
            {
                foreach (Vertex v in infected.ToArray())
                {
                    // Biasing strategy
                    Vertex neighbor = v.RandomNeighbor;

                    double r = net.NextRandomDouble();

                    List<Vertex> intraNeighbors = new List<Vertex>();
                    List<Vertex> interNeighbors = new List<Vertex>();
                    ClassifyNeighbors(net, v, intraNeighbors, interNeighbors);

                    if (r <= bias && interNeighbors.Count > 0)
                        neighbor = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count));

                    if (neighbor != null && infectionTime[neighbor] == int.MinValue)
                    {
                        infectionTime[neighbor] = i;
                        infected.Add(neighbor);
                    }
                }
                if (delay > 0)
                    System.Threading.Thread.Sleep(delay);
                i++;
            }

            res.Iterations = i;
            res.Modularity = (net as ClusterNetwork).NewmanModularity;
            return res;
        }
 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);
     }
 }
        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. 5
0
        public static void Main()
        {
            List<double> results;
            List<double> modularity;
            string line = "";
            System.IO.File.Delete(Properties.Settings.Default.ResultFile);

            int Nc = Properties.Settings.Default.clusterSize;
            int c = Properties.Settings.Default.clusters;
            double m = Properties.Settings.Default.m * Nc * c;
            // what is the maximum p_i possible for the given parameters?

            // in order to yield a connected network, at least ...
            double inter_thresh = 1.2d * ((c * Math.Log(c)) / 2d);       // ... inter edges are required

            double intra_edges = m - inter_thresh;      // the maximum number of expected intra edges

            // this yields a maximum value for p_i of ...
            double max_pi = intra_edges / (c * Combinatorics.Combinations(Nc, 2));

            // Explore parameter space for parameters p_in and bias
            for (double p_in = Properties.Settings.Default.p_in_from; p_in <= max_pi; p_in += Properties.Settings.Default.p_in_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>();

                    // Parallely start runs for this parameter set ...
                    System.Threading.Tasks.Parallel.For(0, Properties.Settings.Default.runs, j =>
                    {
                        // compute the parameter p_e that will give the desired edge number
                        double p_e = (m - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2) * p_in) / (Combinatorics.Combinations(c * Nc, 2) - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2));
                        if (p_e < 0)
                            throw new Exception("probability out of range");

                        // Create the network
                        ClusterNetwork net = null;
                        do
                        {
                            if (net != null)
                                Console.WriteLine("Network (inter = {0}, intra = {1} not connected ... ", net.InterClusterEdges, net.IntraClusterEdges);
                            net = new ClusterNetwork(Properties.Settings.Default.clusters, Properties.Settings.Default.clusterSize, p_in, p_e);
                        }
                        while (!net.Connected);

                        Console.WriteLine("Run {0}, created cluster network for p_in={1:0.00} with modularity={2:0.00}", j, p_in, (net as ClusterNetwork).NewmanModularity);

                        NETGen.Dynamics.EpidemicSynchronization.EpidemicSynchronization sync = new NETGen.Dynamics.EpidemicSynchronization.EpidemicSynchronization(
                            net,
                            null,
                            v => {
                                Vertex neighbor = v.RandomNeighbor;
                                double r = net.NextRandomDouble();

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

                                // biasing strategy ...
                                if (r <= bias && interNeighbors.Count > 0)
                                    neighbor = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count));
                                return neighbor;
                            }
                        );

                        sync.Run();

                        NETGen.Dynamics.EpidemicSynchronization.SyncResults res = sync.Collect();
                        results.Add(res.time);
                        modularity.Add(net.NewmanModularity);
                    });
                    line = string.Format(new CultureInfo("en-US").NumberFormat, "{0} {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 runs for p_in = {0:0.00}, bias = {1:0.00}, Average time = {2:0.000000}", p_in, bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()));
                }
                System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, "\n");
            }
            Console.ReadKey();
        }
Esempio n. 6
0
        /// <summary>
        /// Loads a network with known module structure
        /// </summary>
        /// <param name='file'>
        /// The name of the edgelist file with line format "source,target,source_module,target_module"
        /// </param>
        public static ClusterNetwork LoadNetwork(string file, bool directed = false)
        {
            ClusterNetwork n = new ClusterNetwork();

            string[] lines = System.IO.File.ReadAllLines(file);
            Dictionary <string, int> moduleMapping = new Dictionary <string, int>();

            foreach (string e in lines)
            {
                string[] components = e.Split(',');
                Vertex   v          = null;
                Vertex   w          = null;
                // Create vertex v and assign module
                if (!n.ContainsVertex(components[0]))
                {
                    v = n.CreateVertex(components[0]);
                    if (!moduleMapping.ContainsKey(components[2]))
                    {
                        moduleMapping[components[2]] = moduleMapping.Count;
                    }
                    n._clusterAssignment[v] = moduleMapping[components[2]];
                    if (!n._clusters.ContainsKey(n._clusterAssignment[v]))
                    {
                        n._clusters[n._clusterAssignment[v]] = new List <Vertex>();
                    }
                    n._clusters[n._clusterAssignment[v]].Add(v);
                }
                else
                {
                    v = n.SearchVertex(components[0]);
                }

                if (!n.ContainsVertex(components[1]))
                {
                    w = n.CreateVertex(components[1]);
                    if (!moduleMapping.ContainsKey(components[3]))
                    {
                        moduleMapping[components[3]] = moduleMapping.Count;
                    }
                    n._clusterAssignment[w] = moduleMapping[components[3]];
                    if (!n._clusters.ContainsKey(n._clusterAssignment[w]))
                    {
                        n._clusters[n._clusterAssignment[w]] = new List <Vertex>();
                    }
                    n._clusters[n._clusterAssignment[w]].Add(w);
                }
                else
                {
                    w = n.SearchVertex(components[1]);
                }
                Edge edge = n.CreateEdge(v, w, directed?EdgeType.DirectedAB:EdgeType.Undirected);
                if (n._clusterAssignment[v] != n._clusterAssignment[w])
                {
                    n.InterClusterEdges.Add(edge);
                }
                else
                {
                    n.IntraClusterEdges.Add(edge);
                }
            }
            return(n);
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            List<double> results;
            List<double> modularity;
            string line = "";
            System.IO.File.Delete(Properties.Settings.Default.ResultFile);

            int Nc = Properties.Settings.Default.clusterSize;
            int c = Properties.Settings.Default.clusters;
            double m = Properties.Settings.Default.m * Nc * c;
            // what is the maximum p_i possible for the given parameters?

            // in order to yield a connected network, at least ...
            double inter_thresh = 1.2d * ((c * Math.Log(c)) / 2d);       // ... inter edges are required

            double intra_edges = m - inter_thresh;      // the maximum number of expected intra edges

            // this yields a maximum value for p_i of ...
            double max_pi = intra_edges / (c * Combinatorics.Combinations(Nc, 2));

            for (double p_in = Properties.Settings.Default.p_in_from; p_in <= max_pi; p_in += Properties.Settings.Default.p_in_step)
            {
                    Console.WriteLine();
                    line = "";
                    for(double bias = Properties.Settings.Default.bias_from; bias <= Properties.Settings.Default.bias_to; bias += Properties.Settings.Default.bias_step)
                    {
                        SpreadingResult res;
                        results = new List<double>();
                        modularity = new List<double>();
                        System.Threading.Tasks.Parallel.For(0, Properties.Settings.Default.runs, j =>
                        {
                            double p_e = (m - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2) * p_in) / (Combinatorics.Combinations(c * Nc, 2) - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2));
                            if (p_e < 0)
                                throw new Exception("probability out of range");

                            ClusterNetwork net = null;
                            do
                            {
                                if (net != null)
                                    Console.WriteLine("Network (inter = {0}, intra = {1} not connected ... ", net.InterClusterEdges, net.IntraClusterEdges);
                                net = new ClusterNetwork(Properties.Settings.Default.clusters, Properties.Settings.Default.clusterSize, p_in, p_e);
                            }
                            while (!net.Connected);

                            Console.WriteLine("Run {0}, created cluster network for p_in={1:0.00} with modularity={2:0.00}", j, p_in, (net as ClusterNetwork).NewmanModularity);
                            res = RunSpreading(net, bias);
                            results.Add(res.Iterations);
                            modularity.Add(res.Modularity);
                        });
                        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 p_in = {0:0.00}, bias = {1:0.00}, Average = {2:0.00}", p_in, bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()));
                    }
                    System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, "\n");
            }
        }
Esempio n. 8
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. 9
0
        /// <summary>
        /// Loads a network with known module structure
        /// </summary>
        /// <param name='file'>
        /// The name of the edgelist file with line format "source,target,source_module,target_module"
        /// </param>
        public static ClusterNetwork LoadNetwork(string file, bool directed = false)
        {
            ClusterNetwork n = new ClusterNetwork();
            string[] lines = System.IO.File.ReadAllLines(file);
            Dictionary<string, int> moduleMapping = new Dictionary<string, int>();
            foreach(string e in lines)
            {
                string[] components = e.Split(',');
                Vertex v = null;
                Vertex w = null;
                // Create vertex v and assign module
                if (!n.ContainsVertex(components[0]))
                {
                    v = n.CreateVertex(components[0]);
                    if(!moduleMapping.ContainsKey(components[2]))
                        moduleMapping[components[2]] = moduleMapping.Count;
                    n._clusterAssignment[v] = moduleMapping[components[2]];
                    if(!n._clusters.ContainsKey(n._clusterAssignment[v]))
                        n._clusters[n._clusterAssignment[v]] = new List<Vertex>();
                    n._clusters[n._clusterAssignment[v]].Add(v);
                }
                else
                    v = n.SearchVertex(components[0]);

                if (!n.ContainsVertex(components[1]))
                {
                    w = n.CreateVertex(components[1]);
                    if(!moduleMapping.ContainsKey(components[3]))
                        moduleMapping[components[3]] = moduleMapping.Count;
                    n._clusterAssignment[w] = moduleMapping[components[3]];
                    if(!n._clusters.ContainsKey(n._clusterAssignment[w]))
                        n._clusters[n._clusterAssignment[w]] = new List<Vertex>();
                    n._clusters[n._clusterAssignment[w]].Add(w);
                }
                else
                    w = n.SearchVertex(components[1]);
                Edge edge = n.CreateEdge(v, w, directed?EdgeType.DirectedAB:EdgeType.Undirected);
                if(n._clusterAssignment[v]!=n._clusterAssignment[w])
                    n.InterClusterEdges.Add(edge);
                else
                    n.IntraClusterEdges.Add(edge);
            }
            return n;
        }
Esempio n. 10
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.NewmanModularity;

            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;
        }
Esempio n. 11
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);
        }
Esempio n. 12
0
        public static SIRResult RunSpreading(ClusterNetwork net, double bias, double k, int delay = 0)
        {
            SIRResult res = new SIRResult();

            Dictionary<Vertex, bool> infections = new Dictionary<Vertex, bool>();
            foreach (Vertex v in net.Vertices)
                infections[v] = false;

            List<Vertex> infected = new List<Vertex>();
            List<Vertex> active = new List<Vertex>();

            Vertex seed = net.RandomVertex;
            infected.Add(seed);
            active.Add(seed);

            int i = 0;

            while (active.Count > 0)
            {
                foreach (Vertex v in active.ToArray())
                {
                    // Biasing strategy
                    Vertex neighbor = v.RandomNeighbor;

                    double r = net.NextRandomDouble();

                    // First classify neighbors as intra- or inter-cluster neighbors
                    List<Vertex> intraNeighbors = new List<Vertex>();
                    List<Vertex> interNeighbors = new List<Vertex>();
                    ClassifyNeighbors(net, v, intraNeighbors, interNeighbors);

                    Console.Write("Local choice: {0} intra, {1} inter neighbors, ", intraNeighbors.Count, interNeighbors.Count);

                    // with a probability given by bias select a random inter-cluster neighbor
                    if (r <= bias && interNeighbors.Count > 0)
                        neighbor = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count));

                    if (net.GetClusterForNode(neighbor) == net.GetClusterForNode(v))
                        Console.WriteLine("intra-cluster neighbor chosen!");
                    else
                        Console.WriteLine("inter-cluster neighbor chosen!");

                    if (neighbor != null && !infections[neighbor])
                    {
                        infections[neighbor] = true;
                        infected.Add(neighbor);
                        active.Add(neighbor);
                    }
                    else if (neighbor != null)
                        if (net.NextRandomDouble() <= 1d / (double) k)
                            active.Remove(v);
                }
                if (delay > 0)
                    System.Threading.Thread.Sleep(delay);
                i++;
            }

            res.Duration = i;
            res.InfectedRatio = (double)infected.Count / (double)net.VertexCount;
            res.Modularity = (net as ClusterNetwork).NewmanModularity;
            return res;
        }