gras 0.1.13

A Genetic Programming framework for Neural Architecture Search in Rust
Documentation
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! ASCII pretty-printing helpers for graphs and flodl nets.
//!
//! Rendering is a presentation concern, so it lives outside the core graph
//! types: `topology_ascii` draws a [`Topology`] and `network_ascii`
//! draws a [`Network`], both via the shared Manhattan-wiring diagram
//! `render_wire_diagram`. The types only keep their `Display` impls, which
//! delegate here.

use flodl::nn::Module;

use crate::graph::network::Network;
use crate::graph::node::NodeKind;
use crate::graph::topology::{Connection, Port, Topology};

/// Per-node description consumed by [`render_wire_diagram`].
#[derive(Clone, Copy)]
pub(crate) struct AsciiNode {
    pub id: usize,
    pub kind: NodeKind,
    pub num_inputs: usize,
    pub num_outputs: usize,
    /// Output dimension (from node_dims), shown in parentheses.
    pub out_dim: Option<usize>,
}

/// Render nodes + connections as an ASCII diagram with Manhattan (right-angle)
/// arrows , like a circuit schematic.
///
/// Layout: one node per 4 rows (label / inputs / outputs / blank); each wire
/// gets its own vertical lane on the right, so a long jump (n1 → n7) shows as
/// a tall `│` run. Assumes contiguous node ids (row = id × 4), which our
/// constructors guarantee. Ports beyond index 9 are not rendered faithfully.
///
/// Edges are strictly forward (from.node < to.node) — like the schematic style
/// from GP papers, but WITHOUT the backward edges that figure shows. So the
/// source is always above the target and every arrow points DOWN ⬇; long
/// jumps are fine, backward jumps are not.
pub(crate) fn render_wire_diagram(nodes: &[AsciiNode], connections: &[Connection]) -> String {
    if nodes.is_empty() {
        return "(empty graph)".to_string();
    }

    let kind_name = |kind: NodeKind| match kind {
        NodeKind::Input => "I",
        NodeKind::Hidden => "H",
        NodeKind::Output => "O",
    };

    // ── 1. Clean Label Strings (Pure ASCII) ──
    let labels: Vec<String> = nodes
        .iter()
        .map(|n| match n.out_dim {
            Some(dim) => format!(
                "n{} {} {}i/{}o ->{}",
                n.id,
                kind_name(n.kind),
                n.num_inputs,
                n.num_outputs,
                dim
            ),
            None => format!(
                "n{} {} {}i/{}o",
                n.id,
                kind_name(n.kind),
                n.num_inputs,
                n.num_outputs
            ),
        })
        .collect();

    let label_w = labels.iter().map(|l| l.chars().count()).max().unwrap_or(0) + 2;
    let max_in = nodes.iter().map(|n| n.num_inputs).max().unwrap_or(0);
    let max_out = nodes.iter().map(|n| n.num_outputs).max().unwrap_or(0);

    let indent = 2usize;
    let in_step = 4usize;
    let out_step = 4usize;

    let in_x0 = indent + label_w + 2;
    let out_x0 =
        (in_x0 + max_in * in_step + 2).max(indent + label_w + max_in * in_step + out_step + 4);
    let lane_x0 = out_x0 + max_out * out_step + 2;

    let n_wires = connections.len();
    let lane_step = if n_wires <= 10 {
        3usize
    } else if n_wires <= 25 {
        2usize
    } else {
        1usize
    };

    let max_width = 200usize;
    let raw_width = lane_x0 + n_wires * lane_step + 2;
    let width = raw_width.min(max_width);

    let in_col = |q: usize| in_x0 + q * in_step;
    let out_col = |p: usize| out_x0 + p * out_step;

    // ── 2. Track & Row Allocation ──
    let valid: Vec<bool> = connections
        .iter()
        .map(|c| c.from.node < c.to.node && c.to.node < nodes.len() && c.to.node > 0)
        .collect();

    let out_deg = |i: usize| {
        connections
            .iter()
            .zip(&valid)
            .filter(|(c, ok)| **ok && c.from.node == i)
            .count()
    };
    let in_deg = |i: usize| {
        connections
            .iter()
            .zip(&valid)
            .filter(|(c, ok)| **ok && c.to.node == i)
            .count()
    };

    let rows_per_node = 4usize;
    let mut block_row = vec![0usize; nodes.len()];
    let mut gap_row = vec![0usize; nodes.len().saturating_sub(1)];
    let mut row = 0usize;

    for i in 0..nodes.len() {
        block_row[i] = row;
        row += rows_per_node;
        if i + 1 < nodes.len() {
            gap_row[i] = row;
            row += out_deg(i) + in_deg(i + 1);
        }
    }
    let n_rows = row + 1;

    let mut src_rank = vec![0usize; nodes.len()];
    let mut tgt_rank = vec![0usize; nodes.len()];
    let mut src_track = vec![0usize; connections.len()];
    let mut tgt_track = vec![0usize; connections.len()];

    for (j, c) in connections.iter().enumerate() {
        if !valid[j] {
            continue;
        }
        let s = src_rank[c.from.node];
        src_rank[c.from.node] += 1;
        src_track[j] = gap_row[c.from.node] + s;

        let t = tgt_rank[c.to.node];
        tgt_rank[c.to.node] += 1;
        let gap = c.to.node - 1;
        tgt_track[j] = gap_row[gap] + out_deg(gap) + t;
    }

    let mut canvas = vec![vec![' '; width]; n_rows];

    let put = |cv: &mut Vec<Vec<char>>, r: usize, c: usize, ch: char| {
        if r < cv.len() && c < cv[r].len() {
            let existing = cv[r][c];
            if existing == ' ' {
                cv[r][c] = ch;
            } else if existing == '│' && ch == '│' {
                // vertical meets vertical — keep vertical
            } else if existing == '│' && ch == '─' {
                cv[r][c] = '┼'; // crossing
            } else if existing == '│' && ch == '└' {
                cv[r][c] = '├'; // vertical meets turn-down = T-junction
            }
        }
    };

    // Render Labels & Ports
    for (i, node) in nodes.iter().enumerate() {
        let r0 = block_row[i];
        for (k, ch) in labels[i].chars().enumerate() {
            put(&mut canvas, r0, indent + k, ch);
        }
        for q in 0..node.num_inputs {
            let c = in_col(q);
            put(&mut canvas, r0 + 1, c, 'i');
            if q < 10 {
                put(
                    &mut canvas,
                    r0 + 1,
                    c + 1,
                    char::from_digit(q as u32, 10).unwrap_or('?'),
                );
            } else {
                let dig = format!("{}", q);
                for (k, ch) in dig.chars().enumerate() {
                    put(&mut canvas, r0 + 1, c + 1 + k, ch);
                }
            }
        }
        for p in 0..node.num_outputs {
            let c = out_col(p);
            put(&mut canvas, r0 + 2, c, 'o');
            if p < 10 {
                put(
                    &mut canvas,
                    r0 + 2,
                    c + 1,
                    char::from_digit(p as u32, 10).unwrap_or('?'),
                );
            } else {
                let dig = format!("{}", p);
                for (k, ch) in dig.chars().enumerate() {
                    put(&mut canvas, r0 + 2, c + 1 + k, ch);
                }
            }
        }
    }

    // Render Orphans
    let output_node = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Output)
        .map(|n| n.id)
        .max()
        .or_else(|| nodes.iter().map(|n| n.id).max());

    for (i, node) in nodes.iter().enumerate() {
        let r1 = block_row[i] + 1;
        for q in 0..node.num_inputs {
            let target = Port {
                node: node.id,
                index: q,
            };
            if !connections.iter().any(|c| c.to == target) {
                put(&mut canvas, r1, in_col(q) + 2, '*');
            }
        }
        if Some(node.id) != output_node {
            let r2 = block_row[i] + 2;
            for p in 0..node.num_outputs {
                let source = Port {
                    node: node.id,
                    index: p,
                };
                if !connections.iter().any(|c| c.from == source) {
                    let marker_col = out_col(p) + if p < 10 { 2 } else { 3 };
                    put(&mut canvas, r2, marker_col, '*');
                }
            }
        }
    }

    // ── Phase 1: Arrowheads ──
    for (j, conn) in connections.iter().enumerate() {
        if !valid[j] {
            continue;
        }
        let src_row = block_row[conn.from.node] + 2;
        let tgt_row = block_row[conn.to.node] + 1;
        let arrow_col = out_col(conn.from.index) + if conn.from.index < 10 { 2 } else { 3 };
        put(&mut canvas, src_row, arrow_col, '>');
        put(&mut canvas, tgt_row, in_col(conn.to.index) - 1, '<');
    }

    // ── Phase 2: Complete Port Drops, Vertical Lanes & Corners ──
    for (j, conn) in connections.iter().enumerate() {
        if !valid[j] {
            continue;
        }

        let src_row = block_row[conn.from.node] + 2;
        let tgt_row = block_row[conn.to.node] + 1;
        let src = out_col(conn.from.index) + 2;
        let tgt = in_col(conn.to.index) - 1;
        let lane = (lane_x0 + j * lane_step).min(width - 1);
        let st = src_track[j];
        let tt = tgt_track[j];

        // 1. Source drop: from '>' down to source track row, then turn east
        for r in (src_row + 1)..st {
            put(&mut canvas, r, src, '│');
        }
        put(&mut canvas, st, src, '└'); // Turn east onto horizontal track
        put(&mut canvas, st, lane, '┐'); // Turn south down vertical lane

        // 2. Vertical Lane: down to target track row
        for r in (st + 1)..tt {
            put(&mut canvas, r, lane, '│');
        }
        put(&mut canvas, tt, lane, '┘'); // Turn west off vertical lane

        // 3. Target drop: west on track row, turn south to '<'
        put(&mut canvas, tt, tgt, '┌'); // Turn south to port
        for r in (tt + 1)..tgt_row {
            put(&mut canvas, r, tgt, '│');
        }
    }

    // ── Phase 3: Horizontals with Collision Crossovers (┼) ──
    for (j, conn) in connections.iter().enumerate() {
        if !valid[j] {
            continue;
        }

        let src = out_col(conn.from.index) + 2;
        let tgt = in_col(conn.to.index) - 1;
        let lane = (lane_x0 + j * lane_step).min(width - 1);

        // East run from source port to lane
        for c in (src + 1)..lane.min(width) {
            if c < width {
                let ch = canvas[src_track[j]][c];
                canvas[src_track[j]][c] = match ch {
                    '│' => '┼',
                    ' ' => '─',
                    other => other,
                };
            }
        }

        // West run from lane to target port
        for c in (tgt + 1..lane).rev() {
            if c < width {
                let ch = canvas[tgt_track[j]][c];
                canvas[tgt_track[j]][c] = match ch {
                    '│' => '┼',
                    ' ' => '─',
                    other => other,
                };
            }
        }
    }

    // Assembly Output
    let mut out = String::new();
    for row in &canvas {
        out.push_str(row.iter().collect::<String>().trim_end());
        out.push('\n');
    }
    out
}

/// Compact edge list with distance markers for a [`Topology`].
///
/// Sorts connections by source node, shows the distance (in hops) between
/// source and target, and highlights long-range jumps with `>>>` markers.
pub(crate) fn edge_list(graph: &Topology) -> String {
    let mut out = String::new();
    let n = graph.connections.len();
    out.push_str(&format!("edges ({n} wires):\n"));

    // Sort by (from.node, from.index, to.node, to.index) for scannability.
    let mut sorted: Vec<&Connection> = graph.connections.iter().collect();
    sorted.sort_by_key(|c| (c.from.node, c.from.index, c.to.node, c.to.index));

    for conn in sorted {
        let dist = conn.to.node.saturating_sub(conn.from.node);
        let label = format!(
            "n{}_o{} → n{}_i{}",
            conn.from.node, conn.from.index, conn.to.node, conn.to.index
        );
        let marker = match dist {
            0 => unreachable!("forward-only wiring"),
            1 => "  ·· ".to_string(),
            2 => "  >  ".to_string(),
            _ => format!("  {}>", ">".repeat(dist.saturating_sub(1))),
        };
        let tag = if dist >= 2 {
            format!("  {dist} hops  <<<< long jump")
        } else {
            String::new()
        };
        out.push_str(&format!("  {label}{marker}({dist}){tag}\n"));
    }
    out
}

/// ASCII topology view of a [`Topology`]: a header box plus the Manhattan-wired
/// node diagram.
pub fn topology_ascii(graph: &Topology) -> String {
    let header = format!(
        " Topology #{} · {} nodes · {} input ports · {} output ports · {} wires",
        graph.id,
        graph.nodes.len(),
        graph.graph_inputs.len(),
        graph.graph_outputs.len(),
        graph.connections.len(),
    );
    let mut out = String::new();
    out.push_str(&format!("┌{}┐\n", "─".repeat(header.len() + 4)));
    out.push_str(&format!("│  {}  │\n", header));
    out.push_str(&format!("└{}┘\n", "─".repeat(header.len() + 4)));
    out.push('\n');

    let node_dims = graph.node_dims();
    let nodes: Vec<AsciiNode> = graph
        .nodes
        .iter()
        .enumerate()
        .map(|(i, n)| AsciiNode {
            id: n.id,
            kind: n.kind,
            num_inputs: n.num_inputs,
            num_outputs: n.num_outputs,
            out_dim: node_dims.get(i).map(|&(_, out)| out),
        })
        .collect();
    out.push_str(&render_wire_diagram(&nodes, &graph.connections));

    out.push('\n');
    out.push_str(&edge_list(graph));
    out.push('\n');
    out.push_str("Legend:\n");
    out.push_str("  I=input  H=hidden  O=output\n");
    out.push_str("  0i/4o=input ports / output ports\n");
    out.push_str("  ->dim=output dimension\n");
    out.push_str("  ▶ connected output  ◀ connected input  * orphaned port\n");
    out
}

/// Compact net view of a [`Network`] — derived from the blueprint,
/// focused on what execution actually cares about:
///
/// ```text
///  flodl net (Network) · 7 nodes · 12 wires · 16 param tensors
///      n0 input   : orphan_proj(1→8) · Linear(8 → 8) · act: identity
///      n1 hidden  : Linear(8 → 8) · act: gelu · in 3 · i0←n0_o0 · i1←n0_o1
///      n2 hidden  : orphan_proj(1→16) · Linear(16 → 16) · act: identity · i1*
///      n3 output  : Linear(16 → 10) · act: identity ←  network output
/// ```
///
/// Per node: orphan projection (if any), layer dims, activation, and
/// source wiring. `i{k}*` = orphaned port fed via orphan projection.
pub(crate) fn network_ascii(g: &Network) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        " flodl net (Network) · {} nodes · {} wires · {} param tensors",
        g.layers.len(),
        g.connections.len(),
        g.parameters().len(),
    ));
    out.push('\n');

    let kind_name = |kind: NodeKind| match kind {
        NodeKind::Input => "I",
        NodeKind::Hidden => "H",
        NodeKind::Output => "O",
    };

    for node_id in 0..g.layers.len() {
        let node = &g.nodes[node_id];
        let (in_dim, out_dim) = g.node_dims[node_id];
        let marker = if node_id == g.output_node {
            "   ←  network output"
        } else {
            ""
        };

        // Incoming ops: one entry per input port — its sources (`i0←n1_o0`),
        // or `*` when orphaned (fed net_input). Nodes with no input ports
        // (input nodes) show their output count instead.
        let mut ports: Vec<String> = Vec::new();
        for i in 0..node.num_inputs {
            let target = Port {
                node: node_id,
                index: i,
            };
            let sources: Vec<String> = g
                .connections
                .iter()
                .filter(|c| c.to == target)
                .map(|c| c.from_label())
                .collect();
            ports.push(if sources.is_empty() {
                format!("i{i}*")
            } else {
                format!("i{i}←{}", sources.join("+"))
            });
        }
        let port_str = if ports.is_empty() {
            format!("out {}", node.num_outputs)
        } else {
            format!("in {} · {}", node.num_inputs, ports.join(" · "))
        };

        let std_str = node
            .standardize
            .map_or(String::new(), |s| format!(" · std: {s}"));
        out.push_str(&format!(
            "    n{} {:<7} : Linear({} → {}) · act: {:<8} · {}{}{}\n",
            node_id,
            kind_name(node.kind),
            in_dim,
            out_dim,
            node.activation,
            port_str,
            marker,
            std_str,
        ));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{network_ascii, topology_ascii};
    use crate::graph::network::Network;
    use crate::graph::node::Node;
    use crate::graph::topology::Topology;
    use flodl::Device;

    #[test]
    fn test_render_graph_topology() {
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 3, 1));
        graph.refresh_labels();
        graph.finalize();

        let s = topology_ascii(&graph);
        // Header box with the graph summary
        assert!(s.contains("Topology #1"));
        // One label per node with its port counts
        assert!(s.contains("n0 I"), "label: {s}");
        assert!(s.contains("n1 H"), "label: {s}");
        // Manhattan corners + box border present
        assert!(s.contains('┌'));
        assert!(s.contains('┐'));
        assert!(s.contains('┘'));
        // Every wire is drawn with arrowheads on the canvas.
        let has_arrows = s
            .lines()
            .any(|line| line.contains('>') && !line.contains("->"));
        assert!(has_arrows, "wiring diagram must contain arrowheads");
        // Display impl delegates to the utils function
        assert_eq!(format!("{graph}"), s);
    }

    #[test]
    fn test_render_network_net() {
        let mut graph = Topology::new(0, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_output(1, 2, 1));
        graph.finalize();

        let module = Network::build(&graph, Device::CPU).unwrap();
        let s = network_ascii(&module);

        assert!(!s.contains('▶'));
        assert!(!s.contains('┌'));
        // One Linear per node, with dims + activation (no orphan_proj)
        assert!(s.contains("Linear(1 → 8)"));
        assert!(s.contains("act: identity"));
        assert!(s.contains("n0 I"));
        assert!(s.contains("i0←n0_o0"));
        assert!(s.contains(" network output"));
        assert_eq!(format!("{module}"), s);
    }

    #[test]
    fn test_render_network_all_ports_wired() {
        let mut graph = Topology::new(0, None);
        graph.nodes.push(Node::new_hidden(0, 2, 1));
        graph.nodes.push(Node::new_output(1, 1, 1));
        graph.finalize();

        let module = Network::build(&graph, Device::CPU).unwrap();
        let s = network_ascii(&module);
        // Network builds and forward works even with orphaned ports.
        assert!(!s.is_empty());
    }
}