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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use csv::ReaderBuilder;
use petgraph::{
dot::{Config, Dot},
graph::NodeIndex,
visit::{EdgeRef, IntoNodeReferences, NodeRef},
Direction::{Incoming, Outgoing},
Graph,
};
use rand::{self, seq::SliceRandom};
use serde_derive::Deserialize;
use std::collections::HashMap;
use std::path::PathBuf;
use thiserror::Error;
use crate::{scale_fit, MARGIN_LR};
#[derive(Error, Debug)]
pub enum ReadDSVError {
#[error("Problem reading from path.")]
FromPath { source: csv::Error },
#[error("Problem with StringRecord: {source}")]
StringRecordParseError { source: csv::Error },
}
#[derive(Error, Debug)]
pub enum RandomError {
#[error("More edges than is possible for a bipartite graph ({0}).")]
MaxEdges(usize),
#[error("Number of nodes for a graph must be non-zero.")]
NoNodes,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct Row {
pub from: String,
pub to: String,
pub weight: f64,
}
pub type Species = String;
pub type Fitness = f64;
pub struct BipartiteGraph(pub Graph<Species, Fitness>);
pub enum Strata {
Yes(HashMap<NodeIndex, bool>),
No,
}
impl BipartiteGraph {
pub fn is_bipartite(&self) -> Strata {
let mut colour_map: HashMap<NodeIndex, bool> = HashMap::new();
for (node, _) in self.0.node_references() {
let contains_node = colour_map.contains_key(&node);
let neighbours: Vec<NodeIndex> = self.0.neighbors_undirected(node).collect();
let no_neighbours = neighbours.len();
if contains_node || no_neighbours == 0 {
continue;
}
let mut queue = vec![node];
colour_map.insert(node, true);
while queue.len() > 0 {
let v = queue.pop().unwrap();
let c = !colour_map.get(&v).unwrap();
let inner_neighbours: Vec<NodeIndex> = self.0.neighbors_undirected(v).collect();
for w in &inner_neighbours {
let contains_node_inner = colour_map.contains_key(w);
if contains_node_inner {
if colour_map.get(w).unwrap() == colour_map.get(&v).unwrap() {
return Strata::No;
}
} else {
colour_map.insert(*w, c);
queue.push(*w);
}
}
}
}
Strata::Yes(colour_map)
}
pub fn random(parasite_no: usize, host_no: usize, edge_no: usize) -> Result<Self, RandomError> {
let max_edges = parasite_no * host_no;
if edge_no > max_edges {
return Err(RandomError::MaxEdges(max_edges));
}
let mut graph: Graph<Species, Fitness> = Graph::new();
if parasite_no == 0 || host_no == 0 {
return Err(RandomError::NoNodes);
}
let mut p_node_indices = Vec::new();
for _ in 0..parasite_no {
let nidx = graph.add_node("".into());
p_node_indices.push(nidx);
}
let mut h_node_indices = Vec::new();
for _ in 0..host_no {
let nidx = graph.add_node("".into());
h_node_indices.push(nidx);
}
let mut edge_count = 0;
while edge_count < edge_no {
let p = *p_node_indices.choose(&mut rand::thread_rng()).unwrap();
let h = *h_node_indices.choose(&mut rand::thread_rng()).unwrap();
if graph.contains_edge(p, h) {
continue;
}
graph.add_edge(p, h, 0.0);
edge_count += 1;
}
Ok(BipartiteGraph(graph))
}
pub fn stats(&self) -> (usize, usize, usize) {
let (parasites, hosts) = &self.get_parasite_host_from_graph();
let no_parasites = parasites.len();
let no_hosts = hosts.len();
let no_edges = &self.0.edge_count();
(no_parasites, no_hosts, *no_edges)
}
pub fn from_dsv(input: &PathBuf, delimiter: u8) -> Result<Self, ReadDSVError> {
let mut rdr = ReaderBuilder::new()
.delimiter(delimiter)
.from_path(input)
.map_err(|s| ReadDSVError::FromPath { source: s })?;
let mut edges = Vec::new();
for result in rdr.deserialize() {
let record: Row =
result.map_err(|s| ReadDSVError::StringRecordParseError { source: s })?;
edges.push(record);
}
Ok(Self::create_graph_from_dsv(edges))
}
fn create_graph_from_dsv(input: Vec<Row>) -> Self {
let froms: Vec<&String> = input.iter().map(|e| &e.from).collect();
let tos: Vec<&String> = input.iter().map(|e| &e.to).collect();
let mut nodes: Vec<&String> = froms.into_iter().chain(tos.into_iter()).collect();
nodes.sort();
nodes.dedup();
let mut graph: Graph<String, f64> = petgraph::Graph::new();
let mut node_index_map = HashMap::new();
for node in nodes {
let node = node.clone();
let node_index = graph.add_node(node.clone());
node_index_map.insert(node, node_index);
}
for Row { from, to, weight } in input {
let from_node_index = node_index_map.get(&from).unwrap();
let to_node_index = node_index_map.get(&to).unwrap();
graph.add_edge(*from_node_index, *to_node_index, weight);
}
BipartiteGraph(graph)
}
pub fn get_parasite_host_from_graph(
&self,
) -> (Vec<(NodeIndex, &String)>, Vec<(NodeIndex, &String)>) {
let graph = &self.0;
let mut hosts = Vec::new();
let mut parasites = Vec::new();
for (node, w) in graph.node_references() {
let out: Vec<NodeIndex> = graph.neighbors_directed(node.id(), Outgoing).collect();
let is_parasite = out.len() > 0;
if is_parasite {
parasites.push((node.id(), w));
} else {
hosts.push((node.id(), w));
}
}
(parasites, hosts)
}
pub fn degree_distribution(&self) -> Vec<(String, usize)> {
let graph = &self.0;
let mut dist = Vec::new();
for (node, spp) in graph.node_references() {
let neighbours: Vec<NodeIndex> = graph.neighbors_undirected(node).collect();
dist.push((spp.clone(), neighbours.len()))
}
dist
}
pub fn bivariate_degree_distribution(&self) -> Vec<(usize, usize)> {
let graph = &self.0;
let edge_list: Vec<(NodeIndex, NodeIndex)> = graph
.edge_references()
.map(|e| (e.source().id(), e.target().id()))
.collect();
let mut biv_dist = Vec::new();
for (node1, node2) in edge_list {
let neighbours1: Vec<NodeIndex> = graph.neighbors_undirected(node1).collect();
let neighbours2: Vec<NodeIndex> = graph.neighbors_undirected(node2).collect();
biv_dist.push((neighbours1.len(), neighbours2.len()))
}
biv_dist
}
pub fn plot(&self, width: i32, height: i32) {
let graph = &self.0;
const NODE_SCALE: f64 = 4.0;
let (parasites, hosts) = &self.get_parasite_host_from_graph();
let mut parasite_nodes = String::new();
let mut parasite_pos = HashMap::new();
let parasite_spacing = (width as f64 - (MARGIN_LR * 2.0)) / parasites.len() as f64;
for (mut i, (node, spp_name)) in parasites.iter().enumerate() {
i += 1;
let x = ((i - 1) as f64 * parasite_spacing) + (parasite_spacing / 2.0) + MARGIN_LR;
let y = height as f64 / NODE_SCALE;
parasite_pos.insert(*node, (x, y));
parasite_nodes += &format!(
"<circle cx=\"{x}\" cy=\"{y}\" r=\"6\" fill=\"green\"><title>{spp_name}</title></circle>\n{}",
if i >= 1 { "\t" } else { "" }
);
}
let mut incoming_nodes_vec = Vec::new();
for (node, _) in hosts.iter() {
let out: Vec<NodeIndex> = graph.neighbors_directed(*node, Outgoing).collect();
if out.len() > 0 {
continue;
} else {
let r_vec: Vec<NodeIndex> = graph.neighbors_directed(*node, Incoming).collect();
incoming_nodes_vec.push(r_vec.len());
}
}
let mut host_nodes = String::new();
let mut host_pos = HashMap::new();
let host_spacing = (width as f64 - (MARGIN_LR * 2.0)) / hosts.len() as f64;
for (mut i, (node, spp_name)) in hosts.iter().enumerate() {
i += 1;
let x = ((i - 1) as f64 * host_spacing) + (host_spacing / 2.0) + MARGIN_LR;
let y = (height as f64 / NODE_SCALE) * 3.0;
let r_vec: Vec<NodeIndex> = graph.neighbors_directed(*node, Incoming).collect();
let r = r_vec.len();
host_pos.insert(*node, (x, y));
host_nodes += &format!(
"<circle cx=\"{x}\" cy=\"{y}\" r=\"{}\" fill=\"red\"><title>{spp_name}</title></circle>\n{}",
scale_fit(
r as f64,
*incoming_nodes_vec.iter().min().unwrap() as f64,
*incoming_nodes_vec.iter().max().unwrap() as f64
) * 5.0,
if i >= 1 { "\t" } else { "" }
);
}
let mut edge_links = String::new();
let mut fitness_vec = Vec::new();
for edge in graph.edge_references() {
fitness_vec.push(*edge.weight());
}
let fit_min = fitness_vec
.iter()
.min_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap();
let fit_max = fitness_vec
.iter()
.max_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap();
for (mut i, edge) in graph.edge_references().enumerate() {
i += 1;
let from = edge.source();
let to = edge.target();
let fitness = *edge.weight();
let (x1, y1) = parasite_pos.get(&from).unwrap();
let (x2, y2) = host_pos
.get(&to)
.unwrap_or(parasite_pos.get(&from).unwrap());
edge_links += &format!(
"<line x1=\"{x1}\" y1=\"{y1}\" x2=\"{x2}\" y2=\"{y2}\" stroke=\"black\" stroke-width=\"{}\"/>\n{}",
scale_fit(fitness, *fit_min, *fit_max),
if i >= 1 { "\t" } else { "" }
);
}
let svg = format!(
r#"<svg version="1.1"
width="{width}" height="{height}"
xmlns="http://www.w3.org/2000/svg">
{edge_links}
{parasite_nodes}
{host_nodes}
</svg>
"#
);
println!("{}", svg);
}
pub fn print_dot(&self) {
println!("{}", Dot::with_config(&self.0, &[Config::GraphContentOnly]));
}
}