```  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
```
```//! 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 node;

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

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

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

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

/// Initialize (or reinitialize) the network's links according to the Erdos-Renyi model.
/// See the [NetworkModel](enum.NetworkModel.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);
}
for i in 0..net_len {
for j in i + 1..net_len {
if rng.gen::<f64>() <= p {
}
}
}
if whole {
algorithms::stitch_together(net);
}
net.model = NetworkModel::ER { p, whole };
}

/// Initialize (or reinitialize) the network's links according to the Barabasi-Albert model.
/// See the [NetworkModel](enum.NetworkModel.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();
// Initial cluster - connect everything to everything
for i in 0..m0 {
for j in i + 1..m0 {
}
}
// 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 {
// Make exactly m connections when attaching
// Try connecting to the already established nodes
for j in 0..i {
// Do not connect to the same node twice
// 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 {
// 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 = NetworkModel::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
}

/// Calculates the arithmetical average of vertex degrees (ie. number of closest neighbors)
/// over 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
}

/// Returns the degree distribution of the network as a `HashMap` of histogram bins where key -
/// degree, value - number of occurences in the network.
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
}

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

/// Returns 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
}

/// Returns 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
}
}
```