1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//r This is a library of tools for creating and manipulating complex networks.
//!
//! From [Wikipedia](https://en.wikipedia.org/wiki/Complex_network):
//!
//! > Complex network is a graph-like structure with non-trivial characteristics.
//! > A complex network is a graph (network) with non-trivial topological features—features that do not
//! > occur in simple networks such as lattices or random graphs but often occur in networks representing
//! > real systems. The study of complex networks is a young and active area of scientific
//! > research inspired largely by empirical findings of real-world networks such
//! > as computer networks, biological networks, technological networks, brain networks, climate networks
//! > and social networks.

extern crate rand;
mod algorithms;
mod enums;
mod link;
mod node;

use node::Node;
use rand::prelude::*;
use std::collections::{HashMap, HashSet};

pub use self::algorithms::*;
pub use self::enums::*;
pub use self::link::*;

/// `Network` is the main graph-like data structure.
#[derive(Debug, Clone)]
pub struct Network {
    /// The main data structure.
    nodes: Vec<Node>,
    /// The model used to initialize links between nodes.
    model: Model,
    /// The distribution followed by the link weights.
    weight: Weight,
}

impl Network {
    /// Create a new network of given size and desired model. Use `Model::None` if you want
    /// a network with no connections.
    /// # Examples
    /// Creating a network of chosen model and link weight:
    /// ```
    /// use cnetworks::*;
    /// let net = Network::new(20, Model::ER { p: 0.4, whole: true }, Weight::Uniform);
    /// println!("{:?}", net);
    /// ```
    /// Creating a network with no links and establishing them "by hand":
    /// ```
    /// use cnetworks::*;
    /// let mut net = Network::new(10, Model::None, Weight::Constant { c: 0.25 });
    /// net.link(1, 2);
    /// net.link(4, 7);
    /// println!("{:?}", net);
    /// ```
    pub fn new(size: usize, model: Model, weight: Weight) -> Self {
        // Check for value correctness
        if size == 0 {
            panic!("Attempted creation of network with no nodes.");
        }
        if let Weight::Constant { c } = weight {
            if c <= 0. || c > 1. {
                panic!("Constant link weight cannot be {}", c);
            }
        }
        // Create the network
        let mut net = Network {
            model: Model::None,
            nodes: Vec::new(),
            weight,
        };
        // Fill in the nodes
        for i in 0..size {
            net.nodes.push(Node {
                index: i,
                links: HashMap::new(),
                infected: false,
            });
        }
        // Initialize links according to the desired model
        match model {
            Model::ER { p, whole } => Network::init_er(&mut net, p, whole),
            Model::BA { m0, m } => Network::init_ba(&mut net, m0, m),
            Model::None => (),
        }
        net
    }

    /// Initialize (or reinitialize) the network's links according to the Erdos-Renyi model.
    /// See the [Model](enum.Model.html) for more detailed model explanation.
    ///
    /// If `whole` is `true` then the network is artificially stitched together after
    /// initialization, otherwise there is no guarantee that there are no 'outsiders' or even
    /// separate networks.
    ///
    /// Beware that the network is **not** cleared before linking.
    pub fn init_er(net: &mut Network, p: f64, whole: bool) {
        let net_len = net.len();
        if p <= 0. || p > 1. {
            panic!("The probability of connecting cannot be {}", p);
        }
        let mut rng = rand::thread_rng();
        for i in 0..net_len {
            for j in i + 1..net_len {
                if rng.gen::<f64>() <= p {
                    net._link(i, j, &mut rng);
                }
            }
        }
        if whole {
            algorithms::stitch_together(net);
        }
        net.model = Model::ER { p, whole };
    }

    /// Initialize (or reinitialize) the network's links according to the Barabasi-Albert model.
    /// See the [Model](enum.Model.html) for more detailed model explanation.
    ///
    /// The links *are* cleared before re-linking because of the nautre of initialization algorithm
    pub fn init_ba(net: &mut Network, m0: usize, m: usize) {
        let net_len = net.len();
        if m0 == 0 || m == 0 || m > m0 || m0 > net_len {
            panic!("Incorrrect model parameters: m0 = {}, m = {}", m0, m);
        }
        net.disconnect_all();
        let mut rng = rand::thread_rng();
        // Initial cluster - connect everything to everything
        for i in 0..m0 {
            for j in i + 1..m0 {
                net._link(i, j, &mut rng);
            }
        }
        // Track the total degree for speed
        let mut total_deg = m0 * m0;
        // The rest is attached one by one
        for i in m0..net_len {
            let mut connections_made = 0;
            // Make exactly m connections when attaching
            while connections_made != m {
                // Try connecting to the already established nodes
                for j in 0..i {
                    // Do not connect to the same node twice
                    if !net.nodes[i].links.contains_key(&j) {
                        // Probability of connecting to any node is its deg / total deg
                        let p = net.nodes[j].deg() as f64 / total_deg as f64;
                        if rng.gen::<f64>() <= p {
                            net._link(i, j, &mut rng);
                            connections_made += 1;
                            // Total degree increases by one (current node does not count)
                            total_deg += 1;
                        }
                    }
                }
            }
            // The newly attached node adds m of their own degrees
            total_deg += m;
        }
        net.model = Model::BA { m0, m };
    }

    /// Return the network size, ie. the total number of nodes.
    fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Return the total number of edges in the network.
    pub fn edges(&self) -> usize {
        let mut edges = 0;
        for node in &self.nodes {
            edges += node.deg();
        }
        edges / 2
    }

    /// Calculate the arithmetical average of vertex degrees (ie. number of closest neighbors)
    /// in the network.
    pub fn avg_deg(&self) -> f64 {
        let mut sum = 0;
        for node in &self.nodes {
            sum += node.deg();
        }
        sum as f64 / self.len() as f64
    }

    /// Return the degree distribution of the network as a `HashMap` of (degree, occurences) pairs.
    pub fn deg_distr(&self) -> HashMap<usize, usize> {
        let mut bins: HashMap<usize, usize> = HashMap::new();
        for node in &self.nodes {
            let deg = node.deg();
            match bins.get_key_value(&deg) {
                // If there already is such bin then increment it by 1
                Some((&key, &value)) => bins.insert(key, value + 1),
                // If there isn't create one with single occurence
                None => bins.insert(deg, 1),
            };
        }
        bins
    }

    /// Obtain vector of clusters present in the network, ordered largest to smallest.
    ///
    /// A random element of `net` is chosen as the root and the initial cluster is the first (explored)
    /// set returned by `explore(net, root)`. From the second (unexplored) set a new node is chosen as
    /// the new root, and the process is repeated until there are no more unexplored nodes.
    /// # Examples
    /// ```
    /// use cnetworks::*;
    /// let net = Network::new(100, Model::ER { p: 0.05, whole: false }, Weight::Constant { c: 1.0});
    /// let clusters = net.clusters();
    /// println!("Largest cluster: {:?}", clusters.first().expect("No clusters"));
    /// println!("Smallest cluster: {:?}", clusters.last().expect("No clusters"));
    /// ```
    pub fn clusters(&self) -> Vec<HashSet<usize>> {
        let mut rng = rand::thread_rng();
        let mut clusters: Vec<HashSet<usize>> = Vec::new();
        // Explore from a random node
        let root = self.nodes.choose(&mut rng).expect("Empty network").index;
        // Get explored and unexplored nodes
        let (expl, mut unexpl) = explore(self, root).expect("Failure getting clusters");
        // Add explored to the vector of clusters
        clusters.push(expl);
        loop {
            // Choose a random unexplored node
            match unexpl.iter().choose(&mut rng) {
                Some(&nroot) => {
                    // Establish its cluster
                    let (cls, _) = explore(self, nroot).expect("Failure getting clusters");
                    // Mark everything in the cluster as explored
                    for c in &cls {
                        unexpl.remove(c);
                    }
                    // Add cluster to the vector of clusters
                    clusters.push(cls);
                }
                // The are no unexplored nodes
                None => {
                    // Order cluster largest -> smallest
                    clusters.sort_by_key(|set| -(set.len() as i64));
                    return clusters;
                }
            }
        }
    }

    /// Set the `infected` on all nodes to `false`.
    pub fn clear(&mut self) {
        for node in &mut self.nodes {
            node.infected = false;
        }
    }

    /// Return a `HashSet` with indexes of healthy (not infected) nodes.
    pub fn get_healthy(&self) -> HashSet<usize> {
        let mut hlth: HashSet<usize> = HashSet::new();
        for node in &self.nodes {
            if !node.infected {
                hlth.insert(node.index);
            }
        }
        hlth
    }

    /// Return a `HashSet` with indexes of infected nodes.
    pub fn get_infected(&self) -> HashSet<usize> {
        let mut inf: HashSet<usize> = HashSet::new();
        for node in &self.nodes {
            if node.infected {
                inf.insert(node.index);
            }
        }
        inf
    }

    /// Return the model of the network
    pub fn get_model(&self) -> Model {
        self.model.clone()
    }

    /// Return the type of link weight
    pub fn get_weight(&self) -> Weight {
        self.weight.clone()
    }
}