Exemple #1
0
        /// <summary>
        /// Checks whether the weighted aggregate representation of two temporal networks match
        /// </summary>
        /// <param name="args"></param>
        public static void Run(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: TempNet match [temporal_network_a] [temporal_network_b]");
                return;
            }
            string file_1 = args[1];
            string file_2 = args[2];

            Console.Write("Reading temporal network 1 ...");
            TemporalNetwork temp_net_1 = TemporalNetwork.ReadFromFile(file_1);

            Console.WriteLine("done.");

            Console.Write("Reading temporal network 1 ...");
            TemporalNetwork temp_net_2 = TemporalNetwork.ReadFromFile(file_2);

            Console.WriteLine("done.");

            Console.WriteLine("Comparing weighted aggregate networks ...");
            WeightedNetwork net_1 = temp_net_1.AggregateNetwork;
            WeightedNetwork net_2 = temp_net_2.AggregateNetwork;

            if (net_1.Equals(net_2))
            {
                Console.WriteLine("Both networks are identical.");
            }
            else
            {
                Console.WriteLine("The networks are NOT identical.");
            }
        }
        /// <summary>
        /// Computes the scalar betwenness preference of a node based on its normalized betweenness preference matrix
        /// </summary>
        /// <param name="aggregate_net">The temporal network for which to compute betweenness preference</param>
        /// <param name="x">The node for which to compute betweenness preference</param>
        /// <param name="P">The betweenness preference matrix based on which betw. pref. will be computed</param>
        /// <returns>The betweenness preference, defined as the mutual information of the source and target of two-paths</returns>
        public static double GetBetweennessPref(WeightedNetwork aggregate_net, string x, double[,] P, bool normalized=false)
        {
            // If the network is empty, just return zero
            if (aggregate_net.VertexCount == 0)
                return 0d;

            // Compute the mutual information (i.e. betweenness preference)
            double I = 0;

            int indeg = aggregate_net.GetIndeg(x);
            int outdeg = aggregate_net.GetOutdeg(x);

            double[] marginal_s = new double[indeg];
            double[] marginal_d = new double[outdeg];

            // Marginal probabilities P_d = \sum_s'{P_{s'd}}
            for (int d = 0; d < outdeg; d++)
            {
                double P_d = 0d;
                for (int s_prime = 0; s_prime < indeg; s_prime++)
                    P_d += P[s_prime, d];
                marginal_d[d] = P_d;
            }

            // Marginal probabilities P_s = \sum_d'{P_{sd'}}
            for (int s = 0; s < indeg; s++)
            {
                double P_s = 0d;
                for (int d_prime = 0; d_prime < outdeg; d_prime++)
                    P_s += P[s, d_prime];
                marginal_s[s] = P_s;
            }

            double H_s = Entropy(marginal_s);
            double H_d = Entropy(marginal_d);

            // Here we just compute equation (4) of the paper ...
            for (int s = 0; s < indeg; s++)
                for (int d = 0; d < outdeg; d++)
                    if (P[s, d] != 0) // 0 * Log(0)  = 0
                        // Mutual information
                        I += P[s, d] * Math.Log(P[s, d] / (marginal_s[s] * marginal_d[d]), 2d);

            return normalized?I/Math.Min(H_s,H_d):I;
        }
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("\nUsage: Visualize [network-file] [iterations=50]\n");
                return;
            }

            string network_file = args[0];
            int    iterations   = args.Length >= 2 ? int.Parse(args[1]) : 50;

            // Load the temporal and aggregate network
            Console.Write("Loading temporal network ...");
            TemporalNetwork net = TemporalNetwork.ReadFromFile(network_file);

            Console.WriteLine("done");
            Console.Write("Computing aggregate network ...");
            WeightedNetwork agg = net.AggregateNetwork;

            Console.WriteLine("done");

            // Change the colors
            NetworkColorizer colors = new NetworkColorizer();

            colors.DefaultBackgroundColor = Color.White;
            colors.DefaultVertexColor     = Color.DarkBlue;
            colors.DefaultEdgeColor       = Color.Black;

            Renderer.CurvedEdges = true;

            RenderableTempNet temp_net = new RenderableTempNet(net);

            // Start rendering ...
            Renderer.Start(temp_net, new FRLayout(iterations), colors);


            // Asynchronously compute the layout ...
            Renderer.Layout.DoLayout();

            Application.Run(new VisualizationController(temp_net));
        }
        /// <summary>
        /// Runs a random walk process on an aggregate networks and outputs the dynamics of the infection size
        /// </summary>
        /// <param name="args"></param>
        public static void Run(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: TempNet rw [network_file] [output_file] [RWMode=static_first] [aggregationWindow=1] [steps=1000]");
                Console.WriteLine("\t where RWMode can be ... ");
                Console.WriteLine("\t static_first\t Performs a random walk on the aggregate network that considers betweenness preferences computed from the temporal network");
                Console.WriteLine("\t static_second\t ...");
                return;
            }
            string         out_file = args[2];
            RandomWalkMode mode     = RandomWalkMode.StaticFirstOrder;
            int            runs     = 1;
            int            length   = 1000;

            int aggregationWindow = 1;

            if (args.Length >= 4)
            {
                if (args[3] == "static_second")
                {
                    mode = RandomWalkMode.StaticSecondOrder;
                }
                else
                {
                    Console.WriteLine("Unknown walk mode '{0}'", args[3]);
                }
            }
            if (args.Length >= 5)
            {
                aggregationWindow = int.Parse(args[4]);
            }
            if (args.Length >= 6)
            {
                runs = int.Parse(args[5]);
            }
            if (args.Length >= 7)
            {
                length = int.Parse(args[6]);
            }

            if (!CmdlTools.PromptExistingFile(out_file))
            {
                Console.WriteLine("User opted to exit.");
                return;
            }

            Console.Write("Reading temporal network as undirected network...");
            TemporalNetwork temp_net = TemporalNetwork.ReadFromFile(args[1], true);

            Console.WriteLine("done.");

            if (aggregationWindow != 1)
            {
                Console.WriteLine("Applying aggregation window, length = {0}, time steps before = {1}", aggregationWindow, temp_net.Length);
                temp_net.AggregateTime(aggregationWindow);
                Console.WriteLine("done, time steps after = {0}", temp_net.Length);
            }

            Console.Write("Building aggregate network...");
            WeightedNetwork aggregateNet = temp_net.AggregateNetwork;

            Console.WriteLine("done.");

            Console.WriteLine("Starting random walk ...");

            Dictionary <int, double> tvd = new Dictionary <int, double>();
            RandomWalk walk = new RandomWalk(temp_net, mode);

            for (int t = 0; t < length; t++)
            {
                walk.Step();
                tvd[t] = walk.TVD;
                Console.WriteLine("Node = {0}, step = {1}, tvd={2:0.000}", walk.CurrentNode, t, tvd[t]);
            }

            Console.Write("Writing time series of total variation distance ...");
            StringBuilder sb = new StringBuilder();

            foreach (var step in tvd)
            {
                sb.AppendLine(string.Format(System.Globalization.CultureInfo.GetCultureInfo("en-US").NumberFormat, "{0} {1}", step.Key, step.Value));
            }
            System.IO.File.WriteAllText(out_file + ".dat", sb.ToString());
            Console.WriteLine(" done.");
        }
        /// <summary>
        /// Runs a random walk process on an aggregate networks and outputs the dynamics of the infection size
        /// </summary>
        /// <param name="args"></param>
        public static void Run(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: TempNet rw [network_file] [output_file] [WalkType=random] [aggregationWindow=1] [runs=1] [length=100000]");
                Console.WriteLine("\t where WalkType can be ... ");
                Console.WriteLine("\t bwp_pres\t Performs a random walk on the aggregate network that considers betweenness preferences computed from the temporal network");
                Console.WriteLine("\t bwp_null\t ...");
                return;
            }
            string out_file = args[2];
            string type     = "bwp_pres";
            int    runs     = 1;
            int    length   = 100000;

            int aggregationWindow = 1;

            if (args.Length >= 4)
            {
                type = args[3];
            }
            if (args.Length >= 5)
            {
                aggregationWindow = int.Parse(args[4]);
            }
            if (args.Length >= 6)
            {
                runs = int.Parse(args[5]);
            }
            if (args.Length >= 7)
            {
                length = int.Parse(args[6]);
            }

            if (!CmdlTools.PromptExistingFile(out_file))
            {
                Console.WriteLine("User opted to exit.");
                return;
            }

            Console.Write("Reading temporal network as undirected network...");
            TemporalNetwork temp_net = TemporalNetwork.ReadFromFile(args[1], true);

            Console.WriteLine("done.");

            if (aggregationWindow != 1)
            {
                Console.WriteLine("Applying aggregation window, length = {0}, time steps before = {1}", aggregationWindow, temp_net.Length);
                temp_net.AggregateTime(aggregationWindow);
                Console.WriteLine("done, time steps after = {0}", temp_net.Length);
            }

            Console.Write("Building aggregate network...");
            WeightedNetwork aggregateNet = temp_net.AggregateNetwork;

            Console.WriteLine("done.");

            for (int r = 2000; r <= 2000 + runs; r++)
            {
                Console.WriteLine("Running Random walk [{0}] in mode [{1}] ...", r, type);
                IDictionary <int, double> tvd = null;
                if (type == "bwp_pres")
                {
                    tvd = RandomWalk.RunRW_BWP(temp_net, length, null_model: false);
                }
                else if (type == "bwp_null")
                {
                    tvd = RandomWalk.RunRW_BWP(temp_net, length, null_model: true);
                }
                else
                {
                    Console.WriteLine("\nError: RWType {0} unknown", type);
                    return;
                }

                Console.Write("Writing time series of total variation distance ...");
                StringBuilder sb = new StringBuilder();
                foreach (var step in tvd)
                {
                    sb.AppendLine(string.Format(System.Globalization.CultureInfo.GetCultureInfo("en-US").NumberFormat, "{0} {1}", step.Key, step.Value));
                }
                System.IO.File.WriteAllText(out_file + "_r_" + r + ".dat", sb.ToString());
                Console.WriteLine(" done.");
            }
        }
        /// <summary>
        /// Computes a normalized version P of a given betweenness preference matrix B.
        /// </summary>
        /// <param name="x">The node for which the normalized matrix is computed</param>
        /// <param name="aggregate_net">The weighted aggregate network</param>
        /// <param name="B">The betweenness preference matrix that shall be normalized</param>
        /// <returns>A normalized version of the betweenness preference matrix B</returns>
        public static double[,] NormalizeMatrix(string x, WeightedNetwork aggregate_net, double[,] B)
        {
            // Normalize the matrix ( i.e. this is equation (3) )
            double[,] P = new double[aggregate_net.GetIndeg(x), aggregate_net.GetOutdeg(x)];

            double sum = 0d;
            for (int s = 0; s < aggregate_net.GetIndeg(x); s++)
                for (int d = 0; d < aggregate_net.GetOutdeg(x); d++)
                    sum += B[s, d];

            if(sum>0d)
                for (int s = 0; s < aggregate_net.GetIndeg(x); s++)
                    for (int d = 0; d < aggregate_net.GetOutdeg(x); d++)
                        P[s, d] = B[s, d] / sum;
            return P;
        }
        /// <summary>
        /// Computes the baseline betweenness preference matrix of a node under the assumption 
        /// that the temporal network does not contain a betweenness preference correlation. This corresponds to 
        /// equation (5) in the paper.
        /// </summary>
        /// <param name="v">The node to compute the baseline betweenness preference for</param>
        /// <param name="aggregate_net">The weighted, aggregate ego network of node x based on which the matrix will be computed</param>
        /// <param name="index_pred">Indices of predecessor nodes in the betweenness preference matrix</param>
        /// <param name="index_succ">Indices of successor nodes in the betweenness preference matric</param>
        /// <param name="normalize">Whether or not to normalize the betweenness preference matrix (i.e. whether B or P shall be returned)</param>
        /// <returns>Depending on the normalization, a betweenness preference matrix B or the normalized version P will be returned</returns>
        public static double[,] GetUncorrelatedBetweennessPrefMatrix(WeightedNetwork aggregate_net, string v, out Dictionary<string, int> index_pred, out Dictionary<string, int> index_succ)
        {
            // Use a mapping of indices to node labels
            index_pred = new Dictionary<string, int>();
            index_succ = new Dictionary<string, int>();

            // Create an empty matrix
            double[,] P = new double[aggregate_net.GetIndeg(v), aggregate_net.GetOutdeg(v)];

            // Create the index-to-node mapping
            int i = 0;
            foreach (string u in aggregate_net.GetPredecessors(v))
                index_pred[u] = i++;

            i = 0;
            foreach (string w in aggregate_net.GetSuccessors(v))
                index_succ[w] = i++;

            // Sum over the weights of all source nodes
            double sum_source_weights = 0d;
            foreach (string s_prime in aggregate_net.GetPredecessors(v))
                sum_source_weights += aggregate_net.GetWeight(s_prime, v);

            // Normalization factor for d
            double sum_dest_weights = 0d;
            foreach (string d_prime in aggregate_net.GetSuccessors(v))
                sum_dest_weights += aggregate_net.GetWeight(v, d_prime);

            double min_p = double.MaxValue;

            // Equation (5) in the paper
            foreach (string s in aggregate_net.GetPredecessors(v))
                foreach (string d in aggregate_net.GetSuccessors(v))
                {
                    P[index_pred[s], index_succ[d]] = (aggregate_net.GetWeight(s,v) / sum_source_weights)  * (aggregate_net.GetWeight(v,d) / sum_dest_weights);

                    min_p = Math.Min(P[index_pred[s], index_succ[d]], min_p);

                }
            return P;
        }
        public static void Run(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: TempNet scc [temporal_network_original] [temporal_network_new] [undirected=false] [absolutTime=false]");
                return;
            }

            string file_orig = args[1];
            string file_new  = args[2];

            bool undirected = false;

            bool absoluteTime = false;

            if (args.Length >= 4)
            {
                undirected = Boolean.Parse(args[3]);
            }

            if (args.Length >= 5)
            {
                absoluteTime = Boolean.Parse(args[4]);
            }

            Console.Write("Reading temporal network as {0} network...", undirected?"undirected":"directed");
            TemporalNetwork temp_net = TemporalNetwork.ReadFromFile(file_orig, undirected: undirected);

            Console.WriteLine("done.");

            Console.Write("Extracting two paths and reducing original sequence...");
            temp_net.ReduceToTwoPaths(false, absoluteTime);
            Console.WriteLine("done.");

            Console.Write("Building second order aggregate network...");
            WeightedNetwork net = temp_net.SecondOrderAggregateNetwork;

            Console.WriteLine("done.");

            Console.Write("Extracting largest SCC...");
            net.ReduceToLargestStronglyConnectedComponent();
            Console.WriteLine("done.");

            Console.WriteLine("SCC has {0} nodes", net.VertexCount);

            Console.WriteLine("Filtering disconnected edges in temporal network ... ");
            foreach (var t in temp_net.Keys)
            {
                // Iterate through all edges in this time step
                foreach (var edge in temp_net[t].ToArray())
                {
                    string node = "(" + edge.Item1 + ";" + edge.Item2 + ")";
                    // If this edge is not a node in the second order network
                    if (!net.Vertices.Contains(node))
                    {
                        temp_net[t].Remove(edge);
                    }
                }
            }
            Console.WriteLine("done.");

            Console.Write("Saving new temporal network ... ");
            TemporalNetwork.SaveToFile(file_new, temp_net);
            Console.WriteLine("done.");
        }
Exemple #9
0
        /// <summary>
        /// Outputs a simple example temporal network
        /// </summary>
        /// <param name="args"></param>
        public static void Run(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: TempNet aggregate [temporal_network_file] [output_file] [aggregationWindow=1] [weighted_aggregate_networks=false]");
                return;
            }

            string out_file          = args[2];
            bool   two_path          = false;
            int    aggregationWindow = 1;

            if (args.Length >= 4)
            {
                aggregationWindow = int.Parse(args[3]);
            }

            if (args.Length >= 5)
            {
                two_path = bool.Parse(args[4]);
            }

            if (!CmdlTools.PromptExistingFile(out_file))
            {
                Console.WriteLine("User opted to exit.");
                return;
            }

            Console.Write("Reading temporal network as undirected...");
            TemporalNetwork temp_net = TemporalNetwork.ReadFromFile(args[1], undirected: true);

            Console.WriteLine(" done.");

            Console.WriteLine(temp_net.Length);
            Console.Write("Applying agggregation window [{0}] ...", aggregationWindow);
            temp_net.AggregateTime(aggregationWindow);
            Console.WriteLine("done.");
            Console.WriteLine(temp_net.Length);

            Console.Write("Reducing to two path networks ...");
            temp_net.ReduceToTwoPaths();
            Console.WriteLine("done.");

            if (!two_path)
            {
                Console.Write("Saving temporal network ...");
                TemporalNetwork.SaveToFile(out_file, temp_net);
                Console.WriteLine(" done.");
            }
            else
            {
                //WeightedNetwork net = new WeightedNetwork();
                //foreach(string tp in temp_net.TwoPathWeights.Keys)
                //{
                //    string[] comps = tp.Split(',');
                //    net.AddEdge(comps[0], comps[2], EdgeType.Directed, temp_net.TwoPathWeights[tp]);
                //}
                Console.Write("Saving weighted first-order aggregate network ...");
                WeightedNetwork.SaveToFile(out_file + ".1.edges", temp_net.AggregateNetwork);
                Console.WriteLine(" done.");

                Console.Write("Saving weighted second-order aggregate network ...");
                WeightedNetwork.SaveToFile(out_file + ".2.edges", temp_net.SecondOrderAggregateNetwork);
                Console.WriteLine(" done.");
            }
        }
Exemple #10
0
        static void Main(string[] args)
        {
            /// Create a simple temporal network consisting of 11 repeated two-paths (this network corresponds two Fig. 2 (right part) in the paper)
            TemporalNetwork temporal_net = new TemporalNetwork();

            int k = 0;

            for (int i = 0; i < 100; i++)
            {
                // Add edges according to two paths
                temporal_net.AddTemporalEdge(k++, "c", "e");
                temporal_net.AddTemporalEdge(k++, "e", "f");

                temporal_net.AddTemporalEdge(k++, "a", "e");
                temporal_net.AddTemporalEdge(k++, "e", "g");

                temporal_net.AddTemporalEdge(k++, "c", "e");
                temporal_net.AddTemporalEdge(k++, "e", "f");

                temporal_net.AddTemporalEdge(k++, "a", "e");
                temporal_net.AddTemporalEdge(k++, "e", "g");

                temporal_net.AddTemporalEdge(k++, "c", "e");
                temporal_net.AddTemporalEdge(k++, "e", "f");

                // Note that the next added edge additionally continues a two-path e -> f -> e
                temporal_net.AddTemporalEdge(k++, "f", "e");
                temporal_net.AddTemporalEdge(k++, "e", "b");

                // An additional edge that should be filtered during preprocessing ...
                temporal_net.AddTemporalEdge(k++, "e", "b");

                // And one case where we have multiple edges in a single time step
                temporal_net.AddTemporalEdge(k, "g", "e");
                temporal_net.AddTemporalEdge(k++, "c", "e");
                temporal_net.AddTemporalEdge(k++, "e", "f");

                temporal_net.AddTemporalEdge(k++, "b", "e");
                temporal_net.AddTemporalEdge(k++, "e", "g");

                temporal_net.AddTemporalEdge(k++, "c", "e");
                temporal_net.AddTemporalEdge(k++, "e", "f");

                temporal_net.AddTemporalEdge(k++, "c", "e");
                temporal_net.AddTemporalEdge(k++, "e", "f");
            }

            // Preprocess two-paths and the aggregate network of the temporal network, if this is skipped it will be done automatically when the aggregate network is computed for the first time
            Console.Write("Preparing temporal network...");
            temporal_net.ReduceToTwoPaths();
            Console.WriteLine(" done.");

            // Aggregate the temporal network
            WeightedNetwork aggregate_net = temporal_net.AggregateNetwork;

            // Compute and output betweenness preference of v
            Console.WriteLine("Betw. pref. of e in empirical network = \t\t{0:0.00000}",
                              BetweennessPref.GetBetweennessPref(temporal_net, "e"));

            // Create a random temporal network which only preserves the aggregate network (and destroys bet. pref.)
            TemporalNetwork microstate_random = TemporalNetworkEnsemble.ShuffleEdges(temporal_net, temporal_net.Length);

            microstate_random.ReduceToTwoPaths();

            // Create a random temporal network that preserves both the aggregate network and betw. pref.
            TemporalNetwork microstate_betweennessPref = TemporalNetworkEnsemble.ShuffleTwoPaths(temporal_net, temporal_net.Length);

            microstate_betweennessPref.ReduceToTwoPaths();

            // Compute and output betweenness preference of v in random temporal network
            Console.WriteLine("Betw. pref. of e with shuffled edges = \t\t\t{0:0.00000}",
                              BetweennessPref.GetBetweennessPref(microstate_random, "e"));

            // Compute and output betweenness preference of v in temporal network preserving betw. pref.
            Console.WriteLine("Betw. pref. of e with shuffled two paths = \t\t{0:0.00000}",
                              BetweennessPref.GetBetweennessPref(microstate_betweennessPref, "e"));

            // Compute the betweenness preference matrices of the networks
            Dictionary <string, int> ind_pred;
            Dictionary <string, int> ind_succ;

            double[,] m1 = BetweennessPref.GetBetweennessPrefMatrix(temporal_net, "e", out ind_pred, out ind_succ, normalized: false);

            double[,] m2 = BetweennessPref.GetBetweennessPrefMatrix(microstate_betweennessPref, "e", out ind_pred, out ind_succ, normalized: false);

            // Get the betweenness preference distribution
            IEnumerable <double> dist = BetweennessPref.GetBetweennessPrefDist(temporal_net);
        }