← Commit history

0.2.146: switch-node budget measures an external-FET controller's power node (#287)

Colby Knox ·fb7a107330 · ·parent f33b075
9 files changed +171−19
Cargo.lock+11−11
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -28,7 +28,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -39,7 +39,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-sys",  "roxmltree",@@ -49,7 +49,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -59,7 +59,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -70,7 +70,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-board",  "serde",@@ -79,7 +79,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -89,7 +89,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -100,7 +100,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -111,7 +111,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.145"+version = "0.2.146" dependencies = [  "aiflow-sys",  "serde",@@ -120,7 +120,7 @@ dependencies = [  [[package]] name = "aiflow-sys"-version = "0.2.145"+version = "0.2.146" dependencies = [  "serde_json", ]
Cargo.toml+1−1
@@ -15,7 +15,7 @@ members = [ ]  [workspace.package]-version = "0.2.145"+version = "0.2.146" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
SKILL.md+2−1
@@ -230,7 +230,8 @@ the library, simulation, current, thermal, fields and export, Fusion for everyth    hot loop first: the inductor at the regulator's switch pin, the input caps where the switch node    cannot pass under them. `gate` refuses switch copper under another part or a switch node longer than    `switchNodeMaxLengthMm` (12 mm default) and sends you back to placement: fix it there, not with a wider-   trace.+   trace. With external FETs only the power node (the FETs and the inductor) counts; the controller's SW-pin+   branch has its own optional budget, `switchNodeDriveBranchMaxLengthMm` (aiflow-power-layout). 10. **Heatsink vias.** `thermal-vias plan` (a target per hot part from spec.hot watts and the rise     budget, at least 6) and `thermal-vias land`. 11. **Pours**, then **rounded corners**: `outline round` (1.0 mm default, spec outline.cornerRadius).
crates/adom-aiflow/src/switchnode.rs+144−3
@@ -92,15 +92,111 @@ pub fn note(spec: &Value, b: &Board) -> Option<String> {     let f = find(spec, b);     let list = |v: &[String]| v.join(", ");     let override_ = |v: &[String]| format!("\"switchNodes\": [{}]", v.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", "));-    match f.source {+    let split = split_lines(spec, b);+    let head = match f.source {         Source::Name if !f.nets.is_empty() => Some(format!("switch nodes by name only (no inductor pad shares a net with a SW/LX/PH pin): {}. If any is not a converter's switch node, set {} in the spec (spec-amend); `\"switchNodes\": []` for none.{}", list(&f.nets), override_(&f.nets), if f.not_taken.is_empty() { String::new() } else { format!(" Not taken (no inductor or no switching pin on them): {}.", list(&f.not_taken)) })),         _ if !f.not_taken.is_empty() => Some(format!("not judged as switch nodes (named like one, but no inductor pad and switching pin share them): {}{}. To judge one anyway, list it in spec switchNodes.", list(&f.not_taken), if f.nets.is_empty() { String::new() } else { format!("; switch nodes: {}", list(&f.nets)) })),         _ => None,-    }+    };+    let all: Vec<String> = head.into_iter().chain(split).collect();+    (!all.is_empty()).then(|| all.join("\n"))+}++/// Issue #287: one line per switch net of a controller with external FETs, the power node and the controller branch+/// measured apart, so the branch is reported even when the spec sets no budget for it.+pub fn split_lines(spec: &Value, b: &Board) -> Vec<String> {+    let max_len = spec["switchNodeMaxLengthMm"].as_f64().unwrap_or(12.0);+    nets(spec, b).into_iter().filter_map(|net| {+        let pp = power_pads(spec, b, &net);+        if pp.is_empty() { return None; }+        let (power, total) = power_node_length(b, &net, &pp);+        let branch = (total - power).max(0.0);+        let names = pp.iter().map(|(r, n)| format!("{r}.{n}")).collect::<Vec<_>>().join(", ");+        let bbudget = spec["switchNodeDriveBranchMaxLengthMm"].as_f64().map(|v| format!("budget {v} mm")).unwrap_or_else(|| "no budget: spec switchNodeDriveBranchMaxLengthMm sets one".into());+        Some(format!("{net}: power node {power:.1} mm of track joining {names} (budget {max_len} mm); controller branch {branch:.1} mm ({bbudget}; keep it beside the high-side gate net)"))+    }).collect() }  fn in_box(p: (f64, f64), bb: &(f64, f64, f64, f64), grow: f64) -> bool { p.0 > bb.0 - grow && p.0 < bb.2 + grow && p.1 > bb.1 - grow && p.1 < bb.3 + grow } +/// Issue #287 (RobInMaine): the pads that carry the switch current on a net: spec `switchNodePowerPads` {net: ["Q1.3",+/// "L1.1", ...]} when it names them, else, on a controller with external FETs (a transistor Q* on the net), the+/// transistors' and the inductors' pads on it. Empty for a converter with integrated switches: there the regulator's+/// switch pin is the power node and the whole net is measured, as before.+pub fn power_pads(spec: &Value, b: &Board, net: &str) -> Vec<(String, String)> {+    // the issue's own form too: switchNode {"net": "SW", "powerPads": [...]} (or a list of them)+    fn one<'a>(e: &'a Value, net: &str) -> Option<&'a Vec<Value>> { if e["net"].as_str() == Some(net) { e["powerPads"].as_array() } else { None } }+    let named = spec["switchNodePowerPads"][net].as_array()+        .or_else(|| one(&spec["switchNode"], net))+        .or_else(|| spec["switchNode"].as_array().and_then(|a| a.iter().find_map(|e| one(e, net))));+    if let Some(list) = named {+        return list.iter().filter_map(|v| v.as_str()?.split_once('.').map(|(r, n)| (r.to_string(), n.to_string()))).collect();+    }+    let on: Vec<&aiflow_board::Pad> = b.pads.iter().filter(|p| p.net == net).collect();+    let fet = |r: &str| { let x = r.as_bytes(); x.len() >= 2 && x[0] == b'Q' && x[1].is_ascii_digit() };+    if !on.iter().any(|p| fet(&p.reference)) { return Vec::new(); }+    let libs: std::collections::BTreeMap<&str, &str> = b.footprints.iter().map(|(r, f)| (r.as_str(), f.lib.as_str())).collect();+    on.iter().filter(|p| fet(&p.reference) || inductor(&p.reference, libs.get(p.reference.as_str()).copied().unwrap_or("")))+        .map(|p| (p.reference.clone(), p.name.clone())).collect()+}++/// The track length (mm) on the shortest copper paths joining `pads` on `net` (the power node), and the whole net's.+/// Track ends meeting within 0.01 mm join (a via joins its layers); a track end on a pad joins the pad. Pours are area,+/// not length: pads joined only by a pour add nothing.+pub fn power_node_length(b: &Board, net: &str, pads: &[(String, String)]) -> (f64, f64) {+    let tracks: Vec<aiflow_board::Track> = b.tracks().into_iter().filter(|t| t.net == net).collect();+    let total: f64 = tracks.iter().map(|t| (t.b.0 - t.a.0).hypot(t.b.1 - t.a.1)).sum();+    if pads.len() < 2 || tracks.is_empty() { return (0.0, total); }+    let key = |p: (f64, f64)| ((p.0 * 100.0).round() as i64, (p.1 * 100.0).round() as i64);+    let mut ids: std::collections::HashMap<(i64, i64), usize> = Default::default();+    let mut node = |p: (f64, f64), ids: &mut std::collections::HashMap<(i64, i64), usize>| { let n = ids.len(); *ids.entry(key(p)).or_insert(n) };+    // edges: (to, length, track index or usize::MAX for a pad link)+    let mut adj: Vec<Vec<(usize, f64, usize)>> = Vec::new();+    let mut link = |adj: &mut Vec<Vec<(usize, f64, usize)>>, a: usize, c: usize, w: f64, i: usize| {+        let need = a.max(c) + 1; if adj.len() < need { adj.resize(need, Vec::new()); }+        adj[a].push((c, w, i)); adj[c].push((a, w, i));+    };+    let mut ends: Vec<(usize, (f64, f64), f64)> = Vec::new();+    for (i, tr) in tracks.iter().enumerate() {+        let (a, c) = (node(tr.a, &mut ids), node(tr.b, &mut ids));+        link(&mut adj, a, c, (tr.b.0 - tr.a.0).hypot(tr.b.1 - tr.a.1), i);+        ends.push((a, tr.a, tr.width)); ends.push((c, tr.b, tr.width));+    }+    let mut pad_node: Vec<usize> = Vec::new();+    for (r, n) in pads {+        let Some(pd) = b.pads.iter().find(|p| &p.reference == r && &p.name == n && p.net == net) else { continue };+        let me = ids.len() + pad_node.len() + 1_000_000; // a node id no track end uses+        let reach = (pd.size.0.max(pd.size.1)) / 2.0;+        for (e, at, w) in &ends {+            if (at.0 - pd.x).hypot(at.1 - pd.y) <= reach + w / 2.0 + 0.01 { link(&mut adj, me, *e, 0.0, usize::MAX); }+        }+        pad_node.push(me);+    }+    if pad_node.len() < 2 { return (0.0, total); }+    // shortest paths from the first power pad to every other one; the tracks on them are the power node+    let n = adj.len();+    let start = pad_node[0];+    let mut dist = vec![f64::INFINITY; n];+    let mut prev: Vec<Option<(usize, usize)>> = vec![None; n];+    let mut heap = std::collections::BinaryHeap::new();+    if start < n { dist[start] = 0.0; heap.push(std::cmp::Reverse(((0.0f64).to_bits(), start))); }+    while let Some(std::cmp::Reverse((d, u))) = heap.pop() {+        let d = f64::from_bits(d);+        if d > dist[u] { continue; }+        for &(v, w, i) in &adj[u] {+            let nd = d + w;+            if nd < dist[v] { dist[v] = nd; prev[v] = Some((u, i)); heap.push(std::cmp::Reverse((nd.to_bits(), v))); }+        }+    }+    let mut used = std::collections::BTreeSet::new();+    for &goal in &pad_node[1..] {+        let mut at = goal;+        while let Some((u, i)) = prev.get(at).copied().flatten() { if i != usize::MAX { used.insert(i); } at = u; }+    }+    let power: f64 = used.iter().map(|&i| { let tr = &tracks[i]; (tr.b.0 - tr.a.0).hypot(tr.b.1 - tr.a.1) }).sum();+    (power, total)+}+ /// What is wrong with the switch node's copper, in words the AI can act on. pub fn findings(spec: &Value, b: &Board) -> Vec<String> {     let max_len = spec["switchNodeMaxLengthMm"].as_f64().unwrap_or(12.0);@@ -138,7 +234,20 @@ pub fn findings(spec: &Value, b: &Board) -> Vec<String> {             }         }         if !under.is_empty() { out.push(format!("{net} copper runs under {}", under.join(", "))); }-        if length > max_len { out.push(format!("{net} traces total {length:.1} mm (budget {max_len} mm, spec switchNodeMaxLengthMm): the regulator's switch pin and the inductor are too far apart")); }+        // issue #287: on a controller with external FETs only the power node (FETs and inductor) is under the budget;+        // the controller's SW-pin branch (the high-side driver return) has its own, when the spec sets one+        let pp = power_pads(spec, b, &net);+        if pp.is_empty() {+            if length > max_len { out.push(format!("{net} traces total {length:.1} mm (budget {max_len} mm, spec switchNodeMaxLengthMm): the regulator's switch pin and the inductor are too far apart")); }+        } else {+            let (power, total) = power_node_length(b, &net, &pp);+            let names = pp.iter().map(|(r, n)| format!("{r}.{n}")).collect::<Vec<_>>().join(", ");+            if power > max_len { out.push(format!("{net} power node (the tracks joining {names}) runs {power:.1} mm (budget {max_len} mm, spec switchNodeMaxLengthMm): the switches and the inductor are too far apart")); }+            if let Some(bmax) = spec["switchNodeDriveBranchMaxLengthMm"].as_f64() {+                let branch = (total - power).max(0.0);+                if branch > bmax { out.push(format!("{net} controller branch (the rest of the net: the driver return and the bootstrap capacitor) runs {branch:.1} mm (budget {bmax} mm, spec switchNodeDriveBranchMaxLengthMm): route it short, beside the high-side gate net")); }+            }+        }     }     out }@@ -174,6 +283,38 @@ mod tests {         Board::from_text("t.kicad_pcb", format!("(kicad_pcb {nets} (gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\")) {parts})")).unwrap()     } +    #[test]+    fn an_external_fet_controller_budgets_only_its_power_node() {+        // issue #287: Q1/Q2 and L1 join in 6 mm; the controller U1's SW pin is 30 mm away on the same net+        let b = Board::from_text("fixture", r#"(kicad_pcb (net 0 "") (net 1 "SW")+          (gr_rect (start 0 0) (end 60 20) (layer "Edge.Cuts"))+          (footprint "Package_TO_SOT_SMD:TO-252-2" (layer "F.Cu") (at 40 10) (property "Reference" "Q1") (pad "2" smd rect (at 0 0) (size 2 2) (layers "F.Cu") (net 1 "SW")))+          (footprint "Package_TO_SOT_SMD:TO-252-2" (layer "F.Cu") (at 43 10) (property "Reference" "Q2") (pad "3" smd rect (at 0 0) (size 2 2) (layers "F.Cu") (net 1 "SW")))+          (footprint "Inductor_SMD:L_12x12mm" (layer "F.Cu") (at 46 10) (property "Reference" "L1") (pad "1" smd rect (at 0 0) (size 2 2) (layers "F.Cu") (net 1 "SW")))+          (footprint "Package_SO:TSSOP-20" (layer "F.Cu") (at 10 10) (property "Reference" "U1") (pad "17" smd rect (at 0 0) (size 0.4 1) (layers "F.Cu") (net 1 "SW") (pinfunction "SW")))+          (segment (start 40 10) (end 43 10) (width 1) (layer "F.Cu") (net 1))+          (segment (start 43 10) (end 46 10) (width 1) (layer "F.Cu") (net 1))+          (segment (start 10 10) (end 40 10) (width 0.3) (layer "F.Cu") (net 1)))"#.to_string()).unwrap();+        let spec = json!({"switchNodes": ["SW"]});+        let pp = power_pads(&spec, &b, "SW");+        assert_eq!(pp.len(), 3, "{pp:?}");+        let (power, total) = power_node_length(&b, "SW", &pp);+        assert!((power - 6.0).abs() < 1e-6 && (total - 36.0).abs() < 1e-6, "{power} {total}");+        let f = findings(&spec, &b);+        assert!(!f.iter().any(|x| x.contains("mm (budget")), "the 36 mm net passes: only 6 mm is power node: {f:?}");+        assert!(note(&spec, &b).is_some_and(|n| n.contains("SW: power node 6.0 mm") && n.contains("controller branch 30.0 mm (no budget")), "{:?}", note(&spec, &b));+        let tight = json!({"switchNodes": ["SW"], "switchNodeDriveBranchMaxLengthMm": 20});+        assert!(findings(&tight, &b).iter().any(|x| x.contains("controller branch") && x.contains("30.0 mm")), "{:?}", findings(&tight, &b));+        // the spec can name the power pads outright+        let named = json!({"switchNodes": ["SW"], "switchNodePowerPads": {"SW": ["Q1.2", "U1.17"]}, "switchNodeMaxLengthMm": 12});+        assert!(findings(&named, &b).iter().any(|x| x.contains("power node") && x.contains("30.0 mm")), "{:?}", findings(&named, &b));+        let issue_form = json!({"switchNodes": ["SW"], "switchNode": {"net": "SW", "powerPads": ["Q1.2", "U1.17"]}});+        assert_eq!(power_pads(&issue_form, &b, "SW").len(), 2);+        // power pads joined only by a pour: nothing of the power node is track length+        let pour = Board::from_text("fixture", b.text.replace("(segment (start 40 10) (end 43 10) (width 1) (layer \"F.Cu\") (net 1))", "").replace("(segment (start 43 10) (end 46 10) (width 1) (layer \"F.Cu\") (net 1))", "")).unwrap();+        assert_eq!(power_node_length(&pour, "SW", &power_pads(&spec, &pour, "SW")).0, 0.0);+    }+     #[test]     fn analogue_switch_control_nets_are_not_switch_nodes() {         // no inductor anywhere, pins with functions: none of SW_DAY* is a switch node
docs/release-0.2.146.mdadded+8
@@ -0,0 +1,8 @@+# adom-aiflow 0.2.146++Fixes adom/adom-aiflow#287 (RobInMaine): the switch-node budget counted a controller's SW-pin branch as the power node.++- **External-FET controllers: only the power node is under the budget.** When a transistor (Q*) sits on the switch net, `gate` and `finish` measure the tracks on the shortest copper paths joining the FETs' and the inductor's pads, and only that length is held to `switchNodeMaxLengthMm` (12 mm). A pour joining them adds no length. A converter with integrated switches is measured as before: the whole net.+- **The spec can name the power pads:** `"switchNodePowerPads": {"SW": ["Q1.3", "Q2.2", "L1.1"]}`, or the issue's form `"switchNode": {"net": "SW", "powerPads": [...]}`.+- **The controller branch is reported apart:** the gate prints `SW: power node X mm ...; controller branch Y mm ...` for each such net. `switchNodeDriveBranchMaxLengthMm` gives the branch its own budget, a gate finding when it is exceeded.+- Skills: aiflow-power-layout and adom-aiflow describe the split.
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.145",+  "version": "0.2.146",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.145",+  "version": "0.2.146",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/adom-aiflow/SKILL.md+2−1
@@ -248,7 +248,8 @@ the library, simulation, current, thermal, fields and export, Fusion for everyth    hot loop first: the inductor at the regulator's switch pin, the input caps where the switch node    cannot pass under them. `gate` refuses switch copper under another part or a switch node longer than    `switchNodeMaxLengthMm` (12 mm default) and sends you back to placement: fix it there, not with a wider-   trace.+   trace. With external FETs only the power node (the FETs and the inductor) counts; the controller's SW-pin+   branch has its own optional budget, `switchNodeDriveBranchMaxLengthMm` (aiflow-power-layout). 10. **Heatsink vias.** `thermal-vias plan` (a target per hot part from spec.hot watts and the rise     budget, at least 6) and `thermal-vias land`. A hot part with no exposed tab (an LED, an     inductor, a small leaded IC) is listed with its watts and no tabNet: it is lead-cooled, gets no via
skills/aiflow-power-layout/SKILL.md+1
@@ -36,6 +36,7 @@ Write `aiflow/spec.json` from the schematic before `start`, with a note on every  - Input caps, IC VIN and IC GND form the hot loop: smallest possible loop on F.Cu, the high-frequency cap closest to the pins. - Inductor right after SW; output caps right after the inductor; the feedback network on the quiet side, away from SW.+- **A controller with external FETs (0.2.146).** The switch-node budget (`switchNodeMaxLengthMm`, 12 mm) covers the power node: the tracks joining the high-side FET, the low-side FET and the inductor. The gate finds those pads itself when a transistor (Q*) sits on the switch net, or the spec names them, `"switchNodePowerPads": {"SW": ["Q1.3", "Q2.2", "L1.1"]}` (or `"switchNode": {"net": "SW", "powerPads": [...]}`). A pour joining them adds no length. The controller's SW-pin branch (the high-side driver return and the bootstrap capacitor) is not under that budget: keep it short and beside the HO gate net, and give it its own with `switchNodeDriveBranchMaxLengthMm` when you want the gate to hold it. A converter with integrated switches is measured as before: the whole net. - **Series chains get ONE rotation.** Before `spec.chains`, `place pack` picked 90/270 per part independently and knotted a chain: R1/R2/C9 came out VOUT-bottom, FBM-top, forcing FBM to loop round and a via into an 0402 pad. Turned 180 together, the column read VOUT, R1, FBM, R2, FB top to bottom and FBM became a 1 mm straight link. Now declare the chain in electrical order, `"chains": [{"refs": ["R1", "R2", "R3"], "direction": "down"}]` (VOUT-R1-FBM-R2-FB-R3-GND), give every member a wish, and `place pack` lays them on one line from the first member's wish, each turned so the shared-net pads face (a part numbered the other way round turns 180), and reports `chains: N of M honoured` with the facing pads. A chain not honoured says why (a member with no spot, no wish, or no common net). Then `place check --moves` and `place land --moves`. - **Connectors and holes are service features.** Place a harness connector near where its wire leaves the fan or sensor before choosing a long lead, keep each connector's mating, withdrawal and latch-release corridor clear of neighbouring wires and parts, and give every service screw a straight tool path. When the spec declares `mechanicalReview` or `wiringReview`, update the review file as you move these parts and run `review mechanical` / `review wiring` in its step before finish. Moving a named connector or any hole after a review voids the reviews and the test plan (and, through the copper change, routing, DRC, current and thermal evidence): run them again. See docs/mechanical-wiring-reviews.md.