main
John Lauer Full write-up: design, simulation (ngspice and TI PSpice), sourcing, board, thermal and current, scaffold with probe pl… ccbfcc5
#!/usr/bin/env python3
"""Write buck-12v5v-molecule.kicad_sch from netlist.json (same source as the board).

Symbols are lifted from KiCad's libraries (and Adom's molecule library) and embedded; every pin
gets a 2.54 mm wire stub ending in a net label, so the schematic's netlist equals the board's by
construction. Parts are grouped by function block.
"""
import json, math, os, uuid
import sexp
from sexp import Sym as S

HERE = os.path.dirname(os.path.abspath(__file__))
NAME = "buck-12v5v-molecule"
net = json.load(open(os.path.join(HERE, "netlist.json")))
LIBS = {
    "Device": "lib/Device.kicad_sym",
    "Regulator_Switching": "lib/Regulator_Switching.kicad_sym",
    "power": "lib/power.kicad_sym",
    "Connector": "lib/Connector.kicad_sym",
    "Molecule": "lib/Molecule.kicad_sym",
}
ALIAS = {"Molecule:Contact": "Molecule:MachineContact"}
ROOT = str(uuid.uuid5(uuid.NAMESPACE_URL, "adom/" + NAME + "/root"))


def uid(s):
    return str(uuid.uuid5(uuid.NAMESPACE_URL, f"adom/{NAME}/{s}"))


cache = {}


def symdef(lib_id):
    lib, name = lib_id.split(":")
    if lib not in cache:
        cache[lib] = sexp.lib_symbols(os.path.join(HERE, LIBS[lib]))
    return sexp.flatten(name, cache[lib], lib)


def fnt(size=1.27, hide=False, justify=None):
    e = [S("effects"), [S("font"), [S("size"), size, size]]]
    if justify:
        e.append([S("justify")] + [S(j) for j in justify])
    if hide:
        e.append([S("hide"), S("yes")])
    return e


def g(v):  # snap to the 1.27 mm schematic grid
    return round(v / 1.27) * 1.27


# ---- block layout (schematic mm, y down) --------------------------------------------------
BLOCKS = {  # origin, columns
    "input": (30, 40), "core": (90, 45), "output": (140, 40), "feedback": (185, 45),
    "enable": (60, 95), "indicator": (120, 95), "monitor": (160, 95), "molecule": (30, 140), "probe": (190, 140),
}
counts = {}
lib_ids, body = {}, []
pin_count = 0
for c in net["components"]:
    lib_id = ALIAS.get(c["sym"], c["sym"])
    lib_ids[lib_id] = symdef(lib_id)
    bx, by = BLOCKS.get(c["block"], (30, 190))
    k = counts.get(c["block"], 0); counts[c["block"]] = k + 1
    per_row = 6 if c["block"] == "molecule" else 3
    sx, sy = g(bx + (k % per_row) * 17.78), g(by + (k // per_row) * 22.86)
    if lib_id.startswith("Regulator"):
        sx, sy = g(bx), g(by)
    sym = [S("symbol"), [S("lib_id"), lib_id], [S("at"), sx, sy, 0], [S("unit"), 1],
           [S("exclude_from_sim"), S("no")], [S("in_bom"), S("no") if c["block"] in ("probe",) else S("yes")],
           [S("on_board"), S("yes")], [S("dnp"), S("no")], [S("uuid"), uid("sym/" + c["ref"])]]
    props = [("Reference", c["ref"], (sx + 2.54, sy - 3.81), False), ("Value", c["value"], (sx + 2.54, sy + 3.81), False),
             ("Footprint", c["fp"], (sx, sy), True), ("Datasheet", "~", (sx, sy), True),
             ("MPN", c.get("mpn", ""), (sx, sy), True), ("Manufacturer", c.get("mfr", ""), (sx, sy), True),
             ("Source", c.get("src", ""), (sx, sy), True)]
    for i, (k2, v, (px, py), hide) in enumerate(props):
        sym.append([S("property"), k2, v, [S("at"), g(px), g(py), 0], fnt(hide=hide, justify=None if hide else ["left"])])
    pins = sexp.pins(lib_ids[lib_id])
    for (num, pname, px, py, ang) in pins:
        sym.append([S("pin"), num, [S("uuid"), uid(f"pin/{c['ref']}/{num}")]])
    sym.append([S("instances"), [S("project"), NAME, [S("path"), "/" + ROOT, [S("reference"), c["ref"]], [S("unit"), 1]]]])
    body.append(sym)
    # stubs + labels
    for (num, pname, px, py, ang) in pins:
        key = f"{c['ref']}.{num}"
        netname = next((n for n, ps in net["nets"].items() if key in ps), None)
        if not netname:
            continue
        tx, ty = sx + px, sy - py                      # pin tip in schematic coords
        a = math.radians(ang)
        ox, oy = -math.cos(a), math.sin(a)             # outward, schematic y down
        ex, ey = round(tx + 2.54 * ox, 2), round(ty + 2.54 * oy, 2)
        body.append([S("wire"), [S("pts"), [S("xy"), round(tx, 2), round(ty, 2)], [S("xy"), ex, ey]],
                     [S("stroke"), [S("width"), 0], [S("type"), S("default")]], [S("uuid"), uid(f"wire/{key}")]])
        lang = {(1, 0): 0, (-1, 0): 180, (0, -1): 90, (0, 1): 270}[(round(ox), round(oy))]
        just = {0: ["left", "bottom"], 180: ["right", "bottom"], 90: ["left", "bottom"], 270: ["right", "bottom"]}[lang]
        body.append([S("label"), netname, [S("at"), ex, ey, lang], [S("fields_autoplaced"), S("yes")],
                     fnt(justify=just), [S("uuid"), uid(f"label/{key}")]])
        pin_count += 1

# PWR_FLAG on the rails that arrive from off-board
flag = "power:PWR_FLAG"
lib_ids[flag] = symdef(flag)
for i, rail in enumerate(("VIN", "GND")):
    fx, fy = g(30 + i * 15.24), g(20)
    body.append([S("symbol"), [S("lib_id"), flag], [S("at"), fx, fy, 0], [S("unit"), 1],
                 [S("exclude_from_sim"), S("no")], [S("in_bom"), S("no")], [S("on_board"), S("no")], [S("dnp"), S("no")],
                 [S("uuid"), uid("flag/" + rail)],
                 [S("property"), "Reference", f"#FLG0{i + 1}", [S("at"), fx, fy - 2.54, 0], fnt(hide=True)],
                 [S("property"), "Value", "PWR_FLAG", [S("at"), fx, fy - 3.81, 0], fnt()],
                 [S("property"), "Footprint", "", [S("at"), fx, fy, 0], fnt(hide=True)],
                 [S("property"), "Datasheet", "~", [S("at"), fx, fy, 0], fnt(hide=True)],
                 [S("pin"), "1", [S("uuid"), uid("flagpin/" + rail)]],
                 [S("instances"), [S("project"), NAME, [S("path"), "/" + ROOT, [S("reference"), f"#FLG0{i + 1}"], [S("unit"), 1]]]]])
    body.append([S("wire"), [S("pts"), [S("xy"), fx, fy], [S("xy"), fx, fy + 2.54]],
                 [S("stroke"), [S("width"), 0], [S("type"), S("default")]], [S("uuid"), uid("flagwire/" + rail)]])
    body.append([S("label"), rail, [S("at"), fx, fy + 2.54, 270], [S("fields_autoplaced"), S("yes")],
                 fnt(justify=["right", "bottom"]), [S("uuid"), uid("flaglabel/" + rail)]])

# design notes on the sheet
notes = ("TPS54202 12 V -> 5 V / 1 A buck molecule. VOUT = 0.596 x (1 + (R1+R2)/R3) = 4.98 V. "
         "Cff C9 68 pF (ngspice loop sweep, fc ~29 kHz). EN UVLO R4/R5: start 8.6 V, stop 6.9 V. "
         "VMON (J6) = VOUT/2 for a 3.3 V ADC. EN (J3): pull low to disable. Corner machine pins MP1-4 = GND.")
body.append([S("text"), notes, [S("exclude_from_sim"), S("no")], [S("at"), 30, 12, 0], fnt(justify=["left", "bottom"]),
             [S("uuid"), uid("notes")]])

sch = [S("kicad_sch"), [S("version"), 20250114], [S("generator"), "buck12v5v-gen"], [S("generator_version"), "1.0"],
       [S("uuid"), ROOT], [S("paper"), "A3"],
       [S("title_block"), [S("title"), net["title"]], [S("company"), "Adom"], [S("rev"), "A"],
        [S("comment"), 1, "Generated from netlist.json; same source as the board"]],
       [S("lib_symbols")] + list(lib_ids.values())] + body + \
      [[S("sheet_instances"), [S("path"), "/", [S("page"), "1"]]]]
open(os.path.join(HERE, NAME + ".kicad_sch"), "w", encoding="utf-8").write(sexp.dump(sch) + "\n")
print(json.dumps({"symbols": len(net["components"]), "labels": pin_count, "lib_symbols": len(lib_ids)}))