示例#1
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 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();
        }
示例#3
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);
        }
示例#4
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;
        }
示例#5
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;
        }