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
use simd_csv::StringRecord;

use crate::collections::IncrementalId;
use crate::config::{Config, Delimiter};
use crate::graph::{GraphBuilder, GraphBuilderOptions};
use crate::json::{Attributes, JSONEmptyMode, JSONTypeInferrenceBuffer};
use crate::select::{SelectedColumns, Selection};
use crate::util;
use crate::CliResult;

static USAGE: &str = "
Process CSV data to build a network (nodes & edges) so you can produce a variety
of output ranging from graph data formats (e.g. json or gexf) or other CSV
outputs that can be useful to interpret network information easily when piped
into other xan commands.

Supported input modes:
    `edgelist`:  converts a CSV of edges with a column representing
                 sources and another column targets.
    `bipartite`: converts a CSV with two columns representing the
                 edges between both parts of a bipartite graph.

Supported output formats (-f, --format):
    `json`       - Graphology JSON serialization format
                   ref: https://graphology.github.io/serialization.html
    `gexf`       - Graph eXchange XML Format
                   ref: https://gexf.net/
    `nodelist`   - CSV nodelist, with optional degrees if using -D/--degrees
    `components` - CSV listing connected component sizes and an arbitrary
                   representative node
    `stats`      - Single CSV row of useful graph statistics (number of nodes, edges,
                   graph type, density etc.)

Tips & tricks:

You can restrict node and/or edge attributes by using `xan select` ahead
of this command:

    $ xan select source,target,weight edges.csv | xan network edgelist source target

You can merge edges of a multiple graph using `xan groubpy` etc. ahead of this
command:

    $ xan groupby source,target 'sum(weight) as weight' edges.csv | xan network edgelist source target

You can easily find duplicated (source, target) pairs using `xan dedup`:

    $ xan dedup -s source,target --keep-duplicates edges.csv

Usage:
    xan network edgelist [options] <source> <target> [<input>]
    xan network bipartite [options] <part1> <part2> [<input>]
    xan network --help

output format options:
    -f, --format <format>     One of \"json\", \"gexf\", \"stats\", \"components\"
                              or \"nodelist\".
                              [default: json]
    --gexf-version <version>  GEXF version to output. Can be one of \"1.2\"
                              or \"1.3\".
                              [default: 1.2]
    --minify                  Whether to minify json or gexf output.

xan network options:
    -L, --largest-component  Only keep the largest connected component
                             in the resulting graph.
    -S, --simple             Use to indicate you know beforehand that processed
                             graph is simple, i.e. it does not contains multiple
                             edges for a same (source, target) pair. This can
                             improve performance of the overall process.
    --sample-size <n>        Number of records to sample for node or edge type inference.
                             Set to -1 to sample ALL records. This will cost a lot of memory
                             but will ensure better fitting output types.
                             [default: 64]

edgelist options:
    -U, --undirected       Whether the graph is undirected.
    --nodes <path>         Path to a CSV file containing node metadata
                           (use \"-\" to feed the file from stdin).
    --node-column <name>   Name of the column containing node keys.
                           [default: node]

bipartite options:
    --disjoint-keys  Pass this if you know both partitions of the graph
                         use disjoint sets of keys (i.e. if you know they share
                         no common keys at all). Incorrect graphs will be produced
                         if some keys are used by both partitions!

xan network -f \"nodelist\" options:
    -D, --degrees  Whether to compute node degrees so it can be added
                   to relevant outputs. Currently only relevant
                   when using -f \"nodelist\".
    --union-find   Whether to add a \"component\" column to the output indicating
                   the label of the component each node belongs to.

Common options:
    -h, --help             Display this message
    -o, --output <file>    Write output to <file> instead of stdout.
    -n, --no-headers       When set, the file will be considered as having no
                           headers.
    -d, --delimiter <arg>  The field delimiter for reading CSV data.
                           Must be a single character.
";

#[derive(Deserialize, Debug)]
struct Args {
    cmd_edgelist: bool,
    cmd_bipartite: bool,
    arg_input: Option<String>,
    arg_source: Option<SelectedColumns>,
    arg_target: Option<SelectedColumns>,
    arg_part1: Option<SelectedColumns>,
    arg_part2: Option<SelectedColumns>,
    flag_format: String,
    flag_gexf_version: String,
    flag_minify: bool,
    flag_largest_component: bool,
    flag_simple: bool,
    flag_undirected: bool,
    flag_nodes: Option<String>,
    flag_node_column: SelectedColumns,
    flag_disjoint_keys: bool,
    flag_sample_size: isize,
    flag_degrees: bool,
    flag_union_find: bool,
    flag_no_headers: bool,
    flag_delimiter: Option<Delimiter>,
    flag_output: Option<String>,
}

impl Args {
    fn sample_size(&self) -> Option<usize> {
        if self.flag_sample_size <= 0 {
            None
        } else {
            Some(self.flag_sample_size as usize)
        }
    }

    fn edge_attributes_irrelevant(&self) -> bool {
        ["nodelist", "stats", "components"].contains(&self.flag_format.as_str())
    }

    fn edges_irrelevant(&self) -> bool {
        self.flag_format == "nodelist" && !self.flag_degrees && !self.flag_union_find
    }

    fn graph_builder(&self) -> GraphBuilder {
        // NOTE: we only need to track edge duplicates if:
        //  1. we have to merge edge data to make it simple
        //  2. we have to know if the graph is multi
        // Ultimately this means we need it only for -f=(json|stats) for now

        let output_needs_to_track_multi = ["json", "stats"].contains(&self.flag_format.as_str());

        let mut linear_edge_store = true;

        if output_needs_to_track_multi {
            linear_edge_store = false;
        }

        if self.flag_simple {
            linear_edge_store = true;
        }

        let options = GraphBuilderOptions {
            undirected: self.flag_undirected,
            linear_edge_store,
        };

        GraphBuilder::new(options)
    }

    fn edgelist(&self) -> CliResult<GraphBuilder> {
        let edges_rconf = Config::new(&self.arg_input)
            .delimiter(self.flag_delimiter)
            .no_headers(self.flag_no_headers);

        let mut graph_builder = self.graph_builder();

        let mut record = StringRecord::new();

        if let Some(nodes_path) = &self.flag_nodes {
            let nodes_rconf = Config::new(&Some(nodes_path.clone()))
                .delimiter(self.flag_delimiter)
                .no_headers(self.flag_no_headers);

            let mut node_reader = nodes_rconf.simd_reader()?;
            let node_headers = node_reader.byte_headers()?.clone();

            let node_column_index = self
                .flag_node_column
                .single_selection(&node_headers, !nodes_rconf.no_headers)?;

            let node_attr_sel =
                Selection::without_indices(node_headers.len(), &[node_column_index]);

            let mut node_attr_inferrence = JSONTypeInferrenceBuffer::new(
                node_attr_sel.clone(),
                self.sample_size(),
                JSONEmptyMode::Empty,
            );

            node_attr_inferrence.read(&mut node_reader)?;

            let node_headers = node_reader.byte_headers()?.clone().into_string_record()?;

            graph_builder.set_node_model(
                node_attr_sel.select(&node_headers),
                node_attr_inferrence.types(),
            );

            let mut process_node_record = |record: &StringRecord| {
                let key = record[node_column_index].to_string();

                let mut attributes = Attributes::with_capacity(node_attr_sel.len());

                for (k, v) in node_attr_inferrence.cast(&node_headers, record).flatten() {
                    attributes.insert(k, v);
                }

                graph_builder.add_node(key, attributes);
            };

            for buffered_record in node_attr_inferrence.records() {
                process_node_record(buffered_record);
            }

            while node_reader.read_record(&mut record)? {
                process_node_record(&record);
            }
        }

        let mut edge_reader = edges_rconf.simd_reader()?;
        let edge_headers = edge_reader.byte_headers()?.clone();

        let source_column_index = self
            .arg_source
            .as_ref()
            .unwrap()
            .single_selection(&edge_headers, !edges_rconf.no_headers)?;
        let target_column_index = self
            .arg_target
            .as_ref()
            .unwrap()
            .single_selection(&edge_headers, !edges_rconf.no_headers)?;

        let edge_attr_sel = Selection::without_indices(
            edge_headers.len(),
            &[source_column_index, target_column_index],
        );

        let mut edge_attr_inferrence = JSONTypeInferrenceBuffer::new(
            edge_attr_sel.clone(),
            if self.edge_attributes_irrelevant() {
                Some(1)
            } else {
                self.sample_size()
            },
            JSONEmptyMode::Empty,
        );

        edge_attr_inferrence.read(&mut edge_reader)?;

        let edge_headers = edge_reader.byte_headers()?.clone().into_string_record()?;

        graph_builder.set_edge_model(
            edge_attr_sel.select(&edge_headers),
            edge_attr_inferrence.types(),
        );

        let edge_attributes_irrelevant = self.edge_attributes_irrelevant();
        let edges_irrelevant = self.edges_irrelevant();

        let mut process_edge_record = |record: &StringRecord| {
            let source = record[source_column_index].to_string();
            let target = record[target_column_index].to_string();

            let source_id = graph_builder.get_source_node_id(source);
            let target_id = graph_builder.get_target_node_id(target);

            let attributes = if edge_attributes_irrelevant {
                Attributes::default()
            } else {
                let mut attributes = Attributes::with_capacity(edge_attr_sel.len());

                for (k, v) in edge_attr_inferrence.cast(&edge_headers, record).flatten() {
                    attributes.insert(k, v);
                }

                attributes
            };

            if !edges_irrelevant {
                graph_builder.add_edge_with_attributes(source_id, target_id, attributes);
            }
        };

        for buffered_record in edge_attr_inferrence.records() {
            process_edge_record(buffered_record);
        }

        while edge_reader.read_record(&mut record)? {
            process_edge_record(&record);
        }

        Ok(graph_builder)
    }

    fn bipartite(&self) -> CliResult<GraphBuilder> {
        let rconf = Config::new(&self.arg_input)
            .delimiter(self.flag_delimiter)
            .no_headers(self.flag_no_headers);

        let mut graph_builder = self.graph_builder();

        let mut reader = rconf.reader()?;
        let mut record = csv::StringRecord::new();

        let headers = reader.byte_headers()?.clone();

        let first_part_index = self
            .arg_part1
            .as_ref()
            .unwrap()
            .single_selection(&headers, !rconf.no_headers)?;

        let second_part_index = self
            .arg_part2
            .as_ref()
            .unwrap()
            .single_selection(&headers, !rconf.no_headers)?;

        let mut incremental_id =
            (!self.flag_disjoint_keys).then(IncrementalId::<(usize, String)>::new);

        while reader.read_record(&mut record)? {
            let mut first_part_node = record[first_part_index].to_string();
            let mut second_part_node = record[second_part_index].to_string();

            if let Some(id) = incremental_id.as_mut() {
                first_part_node = id.get((0, first_part_node)).to_string();
                second_part_node = id.get((1, second_part_node)).to_string();
            }

            let first_part_node_id = graph_builder.get_source_node_id(first_part_node);

            let second_part_node_id = graph_builder.get_target_node_id(second_part_node);

            graph_builder.add_edge(first_part_node_id, second_part_node_id);
        }

        Ok(graph_builder)
    }
}

pub fn run(argv: &[&str]) -> CliResult<()> {
    let args: Args = util::get_args(USAGE, argv)?;

    if args.flag_degrees && args.flag_format != "nodelist" {
        Err("-D/--degrees is only relevant with -f nodelist!")?;
    }

    if args.flag_union_find && args.flag_format != "nodelist" {
        Err("--union-find is only relevant with -f nodelist!")?;
    }

    if args.flag_minify && !(args.flag_format == "json" || args.flag_format == "gexf") {
        Err("--minify is only relevant with -f (json|gexf)!")?;
    }

    if args.flag_format == "components" && args.flag_largest_component {
        Err("-L/--largest-component is not relevant with -f components!")?;
    }

    let wconf = Config::new(&args.flag_output);

    if !["1.2", "1.3"].contains(&args.flag_gexf_version.as_str()) {
        Err(format!(
            "unsupported gexf version: {}",
            args.flag_gexf_version
        ))?;
    }

    let builder = (if args.cmd_edgelist {
        args.edgelist()
    } else if args.cmd_bipartite {
        args.bipartite()
    } else {
        unreachable!()
    })?;

    match args.flag_format.as_str() {
        "stats" => builder.write_csv_stats(&wconf, args.flag_largest_component),
        "nodelist" => builder.write_csv_nodelist(
            &wconf,
            args.flag_largest_component,
            args.flag_degrees,
            args.flag_union_find,
        ),
        "components" => builder.write_csv_components(&wconf),
        "gexf" => builder.write_gexf(
            &wconf,
            &args.flag_gexf_version,
            args.flag_minify,
            args.flag_largest_component,
        ),
        "json" => builder.write_json(&wconf, args.flag_minify, args.flag_largest_component),
        _ => Err(format!("unsupported output format: {}!", &args.flag_format))?,
    }
}