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
use anyhow::Result;
use clap::{arg, crate_version, value_parser, ArgMatches, Command};
use oxygraph::{
BipartiteGraph, BipartiteStats, DerivedGraphStats, DerivedGraphs, InteractionMatrix,
InteractionMatrixStats, LpaWbPlus,
};
use rayon::prelude::*;
use std::path::PathBuf;
pub fn cli() -> Command {
Command::new("oxygraphis")
.bin_name("oxygraphis")
.arg_required_else_help(true)
.version(crate_version!())
.author("Max Brown <euphrasiamax@gmail.com>")
.subcommand(
Command::new("bipartite")
.about("Generate and analyse bipartite graphs.")
.arg_required_else_help(true)
.arg(
arg!(<INPUT_DSV> "An input DSV with three headers only: from, to, and weight.")
.required(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!([DELIMITER] "Specify the delimiter of the DSV; we assume tabs.")
.required(false),
)
.arg(
arg!(-p --plotbp "Render an SVG bipartite graph plot.")
.action(clap::ArgAction::SetTrue)
)
.arg(
arg!(-d --degreedistribution "Return the degree distribution of a bipartite graph.")
.action(clap::ArgAction::SetTrue)
)
.arg(
arg!(-b --bivariatedistribution "Return the bivariate degree distribution of a bipartite graph.")
.action(clap::ArgAction::SetTrue)
)
.subcommand(
Command::new("interaction-matrix")
.about("Coerce a bipartite graph into an interaction matrix.")
.arg(
arg!(--print "Print the inner matrix as a TSV. Mainly for debugging.")
.action(clap::ArgAction::SetTrue)
)
.arg(
arg!(-p --plotim "Render an SVG interaction matrix plot.")
.action(clap::ArgAction::SetTrue)
)
.arg(
arg!(-n --nodf "Compute the NODF number of a *sorted* interaction matrix.")
.action(clap::ArgAction::SetTrue)
),
)
.subcommand(Command::new("derived-graphs")
.about("Coerce a bipartite graph into two derived graphs.")
.arg(
arg!(-p --plotdg "Render an SVG derived graph of a stratum.")
.action(clap::ArgAction::SetTrue)
)
.arg(
arg!(-s --stratum [STRATUM] "The stratum to display.")
.default_value("host")
.value_parser(["host", "parasite"])
)
.arg(
arg!(-r --remove [REMOVE] "Edges with fewer than this number of connections are removed from the graph.")
.default_value("2.0")
.value_parser(value_parser!(f64))
)
)
.subcommand(Command::new("modularity")
.about("Derive the modularity of a bipartite graph.")
.arg(
arg!(-l --lpawbplus "Compute the modularity of a bipartite network using LPAwb+ algorithm.")
.action(clap::ArgAction::SetTrue)
.conflicts_with("dirtlpawbplus")
)
.arg(
arg!(-d --dirtlpawbplus "Compute the modularity of a bipartite network using DIRTLPAwb+ algorithm.")
.action(clap::ArgAction::SetTrue)
.conflicts_with("lpawbplus")
)
.arg(
arg!(-p --plotmod "Plot the interaction matrix of a bipartite network, sorted to maximise modularity.")
.action(clap::ArgAction::SetTrue)
)
)
)
.subcommand(Command::new("simulate")
.about("Simulate a number of graphs, and return calculations over the samples.")
.arg(
arg!(--parasitenumber <PARASITENUMBER> "Number of parasite nodes in the graph.")
.required(true)
.value_parser(value_parser!(usize))
)
.arg(
arg!(--hostnumber <HOSTNUMBER> "Number of host nodes in the graph.")
.required(true)
.value_parser(value_parser!(usize))
)
.arg(
arg!(-e --edgecount <EDGECOUNT> "Number of edges in the graph.")
.required(true)
.value_parser(value_parser!(usize))
)
.arg(
arg!(-n --nsims [NSIMS] "Number of random samples to make.")
.value_parser(value_parser!(i32))
.default_value("1000")
)
.arg(
arg!(-c --calculation [CALCULATION] "The calculation to make.")
.default_value("nodf")
.value_parser(["nodf", "lpawbplus", "dirtlpawbplus", "degree-distribution", "bivariate-distribution"])
)
.arg(
arg!(--plot "Plot the simulated bipartite network.")
.action(clap::ArgAction::SetTrue)
)
)
}
pub fn process_matches(matches: &ArgMatches) -> Result<()> {
match matches.subcommand() {
Some(("bipartite", sub_matches)) => {
let input = sub_matches
.get_one::<PathBuf>("INPUT_DSV")
.expect("required");
let delimiter = match sub_matches.get_one::<String>("DELIMITER") {
Some(d) => d.bytes().next().unwrap_or(b'\t'),
None => b'\t',
};
let bipartite_plot = *sub_matches
.get_one::<bool>("plotbp")
.expect("defaulted by clap.");
let degee_distribution = *sub_matches
.get_one::<bool>("degreedistribution")
.expect("defaulted by clap.");
let bivariate_distribution = *sub_matches
.get_one::<bool>("bivariatedistribution")
.expect("defaulted by clap.");
let bpgraph = BipartiteGraph::from_dsv(input, delimiter)?;
match bpgraph.is_bipartite() {
oxygraph::bipartite::Strata::Yes(_) => (),
oxygraph::bipartite::Strata::No => {
eprintln!("Warning: The input graph is not (fully) bipartite.");
}
}
match sub_matches.subcommand() {
None => {
if bipartite_plot {
bpgraph.plot(1600, 700);
} else if degee_distribution {
let dist = bpgraph.degree_distribution();
println!("spp\tvalue");
for (s, v) in dist {
println!("{}\t{}", s, v);
}
} else if bivariate_distribution {
let biv_dist = bpgraph.bivariate_degree_distribution();
println!("node1\tnode2");
for (n1, n2) in biv_dist {
println!("{}\t{}", n1, n2);
}
} else {
let BipartiteStats {
no_parasites,
no_hosts,
no_edges,
} = bpgraph.stats();
println!("#_parasite_nodes\t#_host_nodes\t#_total_edges");
println!("{}\t{}\t{}", no_parasites, no_hosts, no_edges);
}
}
Some(("interaction-matrix", im_matches)) => {
let mut im_mat = InteractionMatrix::from_bipartite(bpgraph);
let im_plot = *im_matches
.get_one::<bool>("plotim")
.expect("defaulted by clap.");
let nodf = *im_matches
.get_one::<bool>("nodf")
.expect("defaulted by clap.");
let print = *im_matches
.get_one::<bool>("print")
.expect("defaulted by clap");
if im_plot {
im_mat.sort();
im_mat.plot(1600, None);
} else if nodf {
im_mat.sort();
let nodf = im_mat.nodf()?;
println!("NODF\n{}", nodf);
} else if print {
println!("{}", im_mat);
} else {
let InteractionMatrixStats {
no_rows,
no_cols,
no_poss_ints,
perc_ints,
} = im_mat.stats();
println!("#_rows\t#_cols\t#_poss_ints\tperc_ints");
println!(
"{}\t{}\t{}\t{}",
no_rows,
no_cols,
no_poss_ints,
perc_ints * 100.0
);
}
}
Some(("derived-graphs", dg_matches)) => {
let dgs = DerivedGraphs::from_bipartite(bpgraph);
let dg_plot = *dg_matches
.get_one::<bool>("plotdg")
.expect("defaulted by clap.");
let stratum = &*dg_matches
.get_one::<String>("stratum")
.expect("defaulted by clap.");
let remove = *dg_matches
.get_one::<f64>("remove")
.expect("defaulted by clap.");
if dg_plot {
match stratum.as_str() {
"host" => dgs.hosts.plot(600.0, remove),
"parasite" => dgs.parasites.plot(600.0, remove),
_ => unreachable!("Should never reach here."),
}
} else {
let DerivedGraphStats {
parasite_nodes,
parasite_edges,
parasite_edges_filtered,
host_nodes,
host_edges,
host_edges_filtered,
} = dgs.stats();
println!("p_nodes\tp_edges\tp_edge_fil\th_nodes\th_edges\th_edge_fil");
println!(
"{}\t{}\t{}\t{}\t{}\t{}",
parasite_nodes,
parasite_edges,
parasite_edges_filtered,
host_nodes,
host_edges,
host_edges_filtered
);
}
}
Some(("modularity", mod_matches)) => {
let _lpawbplus = *mod_matches
.get_one::<bool>("lpawbplus")
.expect("defaulted by clap.");
let dirtlpawbplus = *mod_matches
.get_one::<bool>("dirtlpawbplus")
.expect("defaulted by clap.");
let plot = *mod_matches
.get_one::<bool>("plotmod")
.expect("defaulted by clap.");
let int_mat = InteractionMatrix::from_bipartite(bpgraph);
if plot {
let kind: &str;
let modularity_obj = if dirtlpawbplus {
kind = "DIRTLPAwb+";
oxygraph::modularity::dirt_lpa_wb_plus(int_mat.clone(), 2, 2)
} else {
kind = "LPAwb+";
oxygraph::modularity::lpa_wb_plus(int_mat.clone(), None)
};
let modularity = modularity_obj.modularity;
modularity_obj.plot(int_mat);
eprintln!("{} modularity: {}", kind, modularity);
} else if dirtlpawbplus {
let LpaWbPlus { modularity, .. } =
oxygraph::modularity::dirt_lpa_wb_plus(int_mat, 2, 2);
println!("DIRTLPAwb+\n{}", modularity);
} else {
let LpaWbPlus { modularity, .. } =
oxygraph::modularity::lpa_wb_plus(int_mat, None);
println!("LPAwb+\n{}", modularity);
}
}
_ => unreachable!("Should never reach here."),
}
}
Some(("simulate", sm_matches)) => {
let parasite_number = *sm_matches
.get_one::<usize>("parasitenumber")
.expect("defaulted by clap?");
let host_number = *sm_matches
.get_one::<usize>("hostnumber")
.expect("defaulted by clap?");
let edge_count = *sm_matches
.get_one::<usize>("edgecount")
.expect("defaulted by clap?");
let n_sims = *sm_matches
.get_one::<i32>("nsims")
.expect("defaulted by clap?");
let plot = *sm_matches
.get_one::<bool>("plot")
.expect("defaulted by clap?");
let calculation = &*sm_matches
.get_one::<String>("calculation")
.expect("defaulted by clap.");
if plot {
let rand_graph = BipartiteGraph::random(parasite_number, host_number, edge_count)?;
rand_graph.plot(1000, 400);
return Ok(());
}
(0..n_sims).into_par_iter().for_each(|_| {
{
let rand_graph =
BipartiteGraph::random(parasite_number, host_number, edge_count).unwrap();
match calculation.as_str() {
"nodf" => {
let mut im_mat = InteractionMatrix::from_bipartite(rand_graph);
im_mat.sort();
let nodf = im_mat.nodf().unwrap();
if !nodf.is_nan() {
println!("{}", nodf);
}
}
"lpawbplus" => {
let im_mat = InteractionMatrix::from_bipartite(rand_graph);
let LpaWbPlus { modularity, .. } =
oxygraph::modularity::lpa_wb_plus(im_mat, None);
println!("{}", modularity);
}
"dirtlpawbplus" => {
let im_mat = InteractionMatrix::from_bipartite(rand_graph);
let LpaWbPlus { modularity, .. } =
oxygraph::modularity::dirt_lpa_wb_plus(im_mat, 2, 2);
println!("{}", modularity);
}
"degree-distribution" => {
unimplemented!()
}
"bivariate-distribution" => {
unimplemented!()
}
_ => unreachable!("clap should make sure we never reach here."),
}
}
});
}
_ => unreachable!("Should never reach here."),
}
Ok(())
}