gras 2.0.1

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
//! ASCII diagram primitives used by [`super::markdown`] — the Manhattan-wire rendering and compact
//! edge list.

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

/// Per-node description consumed by [`render_wire_diagram`].
#[derive(Clone, Copy)]
pub(crate) struct AsciiNode {
    /// Stable id (index in `Topology::nodes`).
    pub id: usize,
    /// Input/Hidden/Output role.
    pub kind: NodeKind,
    /// Input ports.
    pub num_inputs: usize,
    /// Output ports.
    pub num_outputs: usize,
    /// Output dimension (from node_dims), shown in parentheses.
    pub out_dim: Option<usize>,
    /// Wires ARRIVING at this node — equals `num_inputs` on a finalized graph
    /// (one wire per input port; a port is a socket, not a bucket).
    pub in_wires: usize,
    /// Wires LEAVING this node (may exceed `num_outputs`: the Input node's ports
    /// fan out to many targets by design — it is the only fan-out node).
    pub out_wires: usize,
}

/// Render the ASCII wire diagram for `nodes` and their `connections`.
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| {
            // Wires vs ports on both sides. In = Out on the input side (`2w→2i`:
            // one wire per port); the output side can fan out (`1o→5w`).
            let in_part = format!("{}w→{}i", n.in_wires.max(n.num_inputs), n.num_inputs);
            let out_part = format!("{}o→{}w", n.num_outputs, n.out_wires.max(n.num_outputs));
            match n.out_dim {
                Some(dim) => format!(
                    "n{} {} {}/{} ->{}",
                    n.id,
                    kind_name(n.kind),
                    in_part,
                    out_part,
                    dim
                ),
                None => format!("n{} {} {}/{}", n.id, kind_name(n.kind), in_part, out_part),
            }
        })
        .collect();

    let label_w = labels.iter().map(|l| l.chars().count()).max().unwrap_or(0) + 2;

    // ── 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();

    // ── Port slots: ONE PER WIRE, so each wire is drawn one-to-one.
    let mut out_slots: Vec<Vec<(usize, Option<usize>)>> = Vec::with_capacity(nodes.len());
    let mut in_slots: Vec<Vec<(usize, Option<usize>)>> = Vec::with_capacity(nodes.len());
    let mut src_slot = vec![0usize; connections.len()];
    let mut tgt_slot = vec![0usize; connections.len()];
    for (i, node) in nodes.iter().enumerate() {
        let mut slots: Vec<(usize, Option<usize>)> = Vec::new();
        for p in 0..node.num_outputs {
            let mut wired = false;
            for (j, c) in connections.iter().enumerate() {
                if valid[j] && c.from.node == i && c.from.index == p {
                    src_slot[j] = slots.len();
                    slots.push((p, Some(j)));
                    wired = true;
                }
            }
            if !wired {
                slots.push((p, None));
            }
        }
        out_slots.push(slots);
    }
    for (i, node) in nodes.iter().enumerate() {
        let mut slots: Vec<(usize, Option<usize>)> = Vec::new();
        for p in 0..node.num_inputs {
            let mut wired = false;
            for (j, c) in connections.iter().enumerate() {
                if valid[j] && c.to.node == i && c.to.index == p {
                    tgt_slot[j] = slots.len();
                    slots.push((p, Some(j)));
                    wired = true;
                }
            }
            if !wired {
                slots.push((p, None));
            }
        }
        in_slots.push(slots);
    }
    // Each wire is labelled with its PORT index; where one port feeds several
    // wires (Input only) the label repeats (`o1 o1` = fan-out).
    let slot_labels = |prefix: char, ports: &[usize]| -> Vec<String> {
        ports.iter().map(|p| format!("{prefix}{p}")).collect()
    };
    let out_labels: Vec<Vec<String>> = out_slots
        .iter()
        .map(|slots| {
            let ports: Vec<usize> = slots.iter().map(|(p, _)| *p).collect();
            slot_labels('o', &ports)
        })
        .collect();
    let in_labels: Vec<Vec<String>> = in_slots
        .iter()
        .map(|slots| {
            let ports: Vec<usize> = slots.iter().map(|(p, _)| *p).collect();
            slot_labels('i', &ports)
        })
        .collect();
    // Offset from a slot's column to its marker: the label's own width.
    let out_off = |i: usize, q: usize| out_labels[i][q].chars().count();
    let in_off = |i: usize, q: usize| in_labels[i][q].chars().count();

    let max_in_slots = in_slots.iter().map(Vec::len).max().unwrap_or(0);
    let max_out_slots = out_slots.iter().map(Vec::len).max().unwrap_or(0);

    let indent = 2usize;
    // A slot's pitch must clear its label plus the `>`/`<` marker.
    let max_in_label = in_labels
        .iter()
        .flatten()
        .map(|l| l.chars().count())
        .max()
        .unwrap_or(1);
    let max_out_label = out_labels
        .iter()
        .flatten()
        .map(|l| l.chars().count())
        .max()
        .unwrap_or(1);
    let in_step = 4usize.max(max_in_label + 2);
    let out_step = 4usize.max(max_out_label + 2);

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

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

    // The canvas must be as wide as the layout it was computed for: `in_col` / `out_col` below are NOT clamped, so a narrower canvas either silently drops labels or slices out…
    const MAX_WIDTH: usize = 4096;
    let raw_width = lane_x0 + n_wires * lane_step + 2;
    let width = raw_width.min(MAX_WIDTH).max(1);

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

    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()
    };

    // Per-node box height: fewest ports → base, most ports → base + MAX_EXTRA,
    // scaling linearly in between. Rows 0..3 are structural and must not move.
    let base_rows = 4usize;
    /// Extra rows the widest node may add (relative box sizing).
    const MAX_EXTRA: usize = 4;
    let ports = |n: &AsciiNode| n.num_inputs.max(n.num_outputs);
    let min_ports = nodes.iter().map(ports).min().unwrap_or(0);
    let max_ports = nodes.iter().map(ports).max().unwrap_or(0);
    let extra_rows = |n: &AsciiNode| -> usize {
        if max_ports == min_ports {
            0
        } else {
            (ports(n) - min_ports) * MAX_EXTRA / (max_ports - min_ports)
        }
    };
    let node_rows: Vec<usize> = nodes.iter().map(|n| base_rows + extra_rows(n)).collect();

    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 += node_rows[i];
        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 in 0..nodes.len() {
        let r0 = block_row[i];
        for (k, ch) in labels[i].chars().enumerate() {
            put(&mut canvas, r0, indent + k, ch);
        }
        // One label per incoming wire — one per input port on a finalized graph.
        for (q, label) in in_labels[i].iter().enumerate() {
            let c = in_col(q);
            for (k, ch) in label.chars().enumerate() {
                put(&mut canvas, r0 + 1, c + k, ch);
            }
        }
        // One label per outgoing wire (`o1 o1` where the Input node fans out).
        for (q, label) in out_labels[i].iter().enumerate() {
            let c = out_col(q);
            for (k, ch) in label.chars().enumerate() {
                put(&mut canvas, r0 + 2, c + 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, &(_, conn)) in in_slots[i].iter().enumerate() {
            if conn.is_none() {
                put(&mut canvas, r1, in_col(q) + in_off(i, q), '*');
            }
        }
        if Some(node.id) != output_node {
            let r2 = block_row[i] + 2;
            for (q, &(_, conn)) in out_slots[i].iter().enumerate() {
                if conn.is_none() {
                    put(&mut canvas, r2, out_col(q) + out_off(i, q), '*');
                }
            }
        }
    }

    // ── 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(src_slot[j]) + out_off(conn.from.node, src_slot[j]);
        put(&mut canvas, src_row, arrow_col, '>');
        put(&mut canvas, tgt_row, in_col(tgt_slot[j]) - 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(src_slot[j]) + out_off(conn.from.node, src_slot[j]);
        let tgt = in_col(tgt_slot[j]) - 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(src_slot[j]) + out_off(conn.from.node, src_slot[j]);
        let tgt = in_col(tgt_slot[j]) - 1;
        let lane = (lane_x0 + j * lane_step).min(width - 1);

        // East run from source port to lane. Both ends are clamped: a column past the canvas
        // edge was already dropped by `put`, and slicing past it would panic.
        let east_end = lane.min(width);
        for slot in canvas[src_track[j]][(src + 1).min(east_end)..east_end].iter_mut() {
            *slot = match *slot {
                '│' => '┼',
                ' ' => '─',
                other => other,
            };
        }

        // West run from lane back to the target port, clamped the same way.
        let west_end = lane.min(width);
        for slot in canvas[tgt_track[j]][(tgt + 1).min(west_end)..west_end]
            .iter_mut()
            .rev()
        {
            *slot = match *slot {
                '│' => '┼',
                ' ' => '─',
                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`] — sorted
/// source node, long-range jumps marked `>>>`.
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
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::topology::Port;

    fn node(
        id: usize,
        kind: NodeKind,
        num_inputs: usize,
        num_outputs: usize,
        in_wires: usize,
        out_wires: usize,
    ) -> AsciiNode {
        AsciiNode {
            id,
            kind,
            num_inputs,
            num_outputs,
            out_dim: Some(2),
            in_wires,
            out_wires,
        }
    }

    /// A graph whose geometry alone needs more than the old 200-column canvas: 60 input ports put `in_col(59)` well past 200, and Phase 3's west run sliced from `tgt + 1` (264)…
    #[test]
    fn a_layout_wider_than_two_hundred_columns_renders_without_panicking() {
        let nodes = [
            node(0, NodeKind::Input, 1, 60, 1, 60),
            node(1, NodeKind::Hidden, 60, 1, 60, 1),
            node(2, NodeKind::Output, 1, 1, 1, 1),
        ];
        let mut connections: Vec<Connection> = (0..60)
            .map(|p| Connection {
                from: Port { node: 0, index: p },
                to: Port { node: 1, index: p },
            })
            .collect();
        connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });

        let out = render_wire_diagram(&nodes, &connections);
        let widest = out.lines().map(|l| l.chars().count()).max().unwrap_or(0);
        assert!(
            widest > 200,
            "the canvas must cover the computed layout, not stop at 200 columns (widest {widest})"
        );
        assert!(
            out.lines().count() >= nodes.len() * 3,
            "every node still gets its box rows"
        );
    }
}