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
//! This module provides some utility functions for working with assignments
//! and RLE encoding. It also provides a function to sort a JSON file by a key
//! so as to make the BEN encoding more efficient.

use super::{log, logln};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{Read, Result, Write};
use std::result::Result as StdResult;

/// Convert a vector of assignments to a run-length encoded (RLE) vector.
///
/// # Arguments
///
/// * `assign_vec` - A vector of assignments to convert to RLE.
///
/// # Returns
///
/// A vector of tuples where the first element is the value and the second element is
/// the length of the run.
pub fn assign_to_rle(assign_vec: Vec<u16>) -> Vec<(u16, u16)> {
    let mut prev_assign: u16 = 0;
    let mut count: u16 = 0;
    let mut first = true;
    let mut rle_vec: Vec<(u16, u16)> = Vec::new();

    for assign in assign_vec {
        if first {
            prev_assign = assign;
            count = 1;
            first = false;
            continue;
        }
        if assign == prev_assign {
            count += 1;
        } else {
            rle_vec.push((prev_assign, count));
            // Reset for next run
            prev_assign = assign;
            count = 1;
        }
    }

    // Handle the last run
    if count > 0 {
        rle_vec.push((prev_assign, count));
    }
    rle_vec
}

/// Convert a run-length encoded (RLE) vector to a vector of assignments.
///
/// # Arguments
///
/// * `rle_vec` - A vector of tuples where the first element is the value and the second element is
/// the length of the run.
///
/// # Returns
///
/// A vector of assignments.
pub fn rle_to_vec(rle_vec: Vec<(u16, u16)>) -> Vec<u16> {
    let mut output_vec: Vec<u16> = Vec::new();
    for (val, len) in rle_vec {
        for _ in 0..len {
            output_vec.push(val);
        }
    }
    output_vec
}

/// Sorts a JSON-formatted NetworkX graph file by a key.
/// This function will sort the nodes in the graph by the key provided and
/// then relabel the nodes in the graph from 0 to n-1 where n is the number
/// of nodes in the graph. It will also relabel the edges in the graph to
/// match the new node labels.
///
/// # Arguments
///
/// * `reader` - A reader for the JSON file to sort.
/// * `writer` - A writer for the new JSON file.
/// * `key` - The key to sort the nodes by.
///
/// # Returns
///
/// A Result containing a HashMap from the old node labels to the new node labels.
pub fn sort_json_file_by_key<R: Read, W: Write>(
    reader: R,
    mut writer: W,
    key: &str,
) -> Result<HashMap<usize, usize>> {
    logln!("Loading JSON file...");
    let mut data: Value = serde_json::from_reader(reader).unwrap();

    logln!("Sorting JSON file by key: {}", key);
    if let Some(nodes) = data["nodes"].as_array_mut() {
        nodes.sort_by(|a, b| {
            let extract_value = |val: &Value| -> StdResult<u64, String> {
                match &val[key] {
                    Value::String(s) => s.parse::<u64>().map_err(|_| s.clone()),
                    Value::Number(n) => n.as_u64().ok_or_else(|| n.to_string()),
                    _ => Err(val[key].to_string()),
                }
            };

            match (extract_value(a), extract_value(b)) {
                (Ok(a_num), Ok(b_num)) => a_num.cmp(&b_num),
                (Err(a_str), Err(b_str)) => a_str.cmp(&b_str),
                (Err(a_str), Ok(b_num)) => a_str.cmp(&b_num.to_string()),
                (Ok(a_num), Err(b_str)) => a_num.to_string().cmp(&b_str),
            }
        });
    }

    let mut node_map = HashMap::new();
    let mut rev_node_map = HashMap::new();
    if let Some(nodes) = data["nodes"].as_array_mut() {
        for (i, node) in nodes.iter_mut().enumerate() {
            log!("Relabeling node: {}\r", i + 1);
            node_map.insert(node["id"].to_string().parse::<usize>().unwrap(), i);
            rev_node_map.insert(i, node["id"].to_string().parse::<usize>().unwrap());
            node["id"] = json!(i);
        }
    }
    logln!();

    let mut edge_array = Vec::new();
    if let Some(edges) = data["adjacency"].as_array() {
        for i in 0..edges.len() {
            log!("Relabeling edge: {}\r", i + 1);
            let edge_list_location =
                rev_node_map[&data["nodes"][i]["id"].to_string().parse::<usize>().unwrap()];
            let mut new_edge_lst = edges[edge_list_location].as_array().unwrap().clone();
            for link in new_edge_lst.iter_mut() {
                let new = node_map[&link["id"].to_string().parse::<usize>().unwrap()];
                link["id"] = json!(new);
            }
            edge_array.push(new_edge_lst);
        }
    }
    logln!();

    data["adjacency"] = json!(edge_array);

    logln!("Writing new json to file...");
    writer.write_all(serde_json::to_string(&data).unwrap().as_bytes())?;

    Ok(node_map)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_assign_to_rle() {
        let assign_vec: Vec<u16> = vec![1, 1, 1, 2, 2, 3];

        let result: Vec<(u16, u16)> = vec![(1, 3), (2, 2), (3, 1)];

        assert_eq!(assign_to_rle(assign_vec), result);
    }

    #[test]
    fn test_rle_to_vec() {
        let rle_vec: Vec<(u16, u16)> = vec![(1, 3), (2, 2), (3, 1)];

        let result: Vec<u16> = vec![1, 1, 1, 2, 2, 3];

        assert_eq!(rle_to_vec(rle_vec), result);
    }

    #[test]
    fn test_relabel_small_file() {
        //
        // 6 -- 7 -- 8
        // |    |    |
        // 3 -- 4 -- 5
        // |    |    |
        // 0 -- 1 -- 2
        //
        let input = r#"{
    "adjacency": [
        [ { "id": 3 }, { "id": 1 } ],
        [ { "id": 0 }, { "id": 4 }, { "id": 2 } ],
        [ { "id": 1 }, { "id": 5 } ],
        [ { "id": 0 }, { "id": 6 }, { "id": 4 } ],
        [ { "id": 1 }, { "id": 3 }, { "id": 7 }, { "id": 5 } ],
        [ { "id": 2 }, { "id": 4 }, { "id": 8 } ],
        [ { "id": 3 }, { "id": 7 } ],
        [ { "id": 4 }, { "id": 6 }, { "id": 8 } ],
        [ { "id": 5 }, { "id": 7 } ]
    ],
    "directed": false,
    "graph": [],
    "multigraph": false,
    "nodes": [
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288005",
            "id": 0
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288004",
            "id": 1
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288003",
            "id": 2
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288006",
            "id": 3
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": false,
            "boundary_perim": 0,
            "GEOID20": "20258288001",
            "id": 4
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288002",
            "id": 5
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288007",
            "id": 6
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288008",
            "id": 7
        },
        {
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "GEOID20": "20258288009",
            "id": 8
        }
    ]
}
"#;

        let reader = input.as_bytes();

        let mut output = Vec::new();
        let writer = &mut output;

        let key = "GEOID20";

        let _ = sort_json_file_by_key(reader, writer, key).unwrap();

        //
        // 6 -- 7 -- 8
        // |    |    |
        // 5 -- 0 -- 1
        // |    |    |
        // 4 -- 3 -- 2
        //
        let expected_output = r#"{
    "adjacency": [
        [ { "id": 3 }, { "id": 5 }, { "id": 7 }, { "id": 1 } ],
        [ { "id": 2 }, { "id": 0 }, { "id": 8 } ], [ { "id": 3 }, { "id": 1 } ],
        [ { "id": 4 }, { "id": 0 }, { "id": 2 } ],
        [ { "id": 5 }, { "id": 3 } ],
        [ { "id": 4 }, { "id": 6 }, { "id": 0 } ],
        [ { "id": 5 }, { "id": 7 } ],
        [ { "id": 0 }, { "id": 6 }, { "id": 8 } ],
        [ { "id": 1 }, { "id": 7 } ]
    ],
    "directed": false,
    "graph": [],
    "multigraph": false,
    "nodes": [
        {
            "GEOID20": "20258288001",
            "TOTPOP": 1,
            "boundary_nodes": false,
            "boundary_perim": 0,
            "id": 0
        },
        {
            "GEOID20": "20258288002",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 1
        },
        {
            "GEOID20": "20258288003",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 2
        },
        {
            "GEOID20": "20258288004",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 3
        },
        {
            "GEOID20": "20258288005",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 4
        },
        {
            "GEOID20": "20258288006",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 5
        },
        {
            "GEOID20": "20258288007",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 6
        },
        {
            "GEOID20": "20258288008",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 7
        },
        {
            "GEOID20": "20258288009",
            "TOTPOP": 1,
            "boundary_nodes": true,
            "boundary_perim": 1,
            "id": 8
        }
    ]
}
"#;

        logln!();
        let output_json: Value = serde_json::from_slice(&output).unwrap();
        let expected_output_json: Value = serde_json::from_str(expected_output).unwrap();

        assert_eq!(output_json, expected_output_json);
    }
}