"""Write a placer result into a copy of a board: footprint positions and turns, no copper. Run with KiCad's bundled Python (pcbnew), with the source board closed or saved: $KPY tools/placer/apply.py board.kicad_pcb placement.json out.kicad_pcb placement.json maps ref -> [x, y, rotation in degrees], at the top level or under "placement" (placer's rank_NN.json). Tracks and vias are deleted (the old routing belongs to the old placement); zones are kept and refilled by the router's write step. The board's .kicad_pro is copied next to the output, because pcbnew.SaveBoard would write default net settings into it (knowledge/tooling/kicad.md, pcbnew quirks). """ import json import os import shutil import sys import pcbnew def main(src, placement, out): d = json.load(open(placement)) d = d.get("placement", d) b = pcbnew.LoadBoard(src) seen = set() for f in b.GetFootprints(): r = f.GetReference() if r in d: x, y, rot = d[r] f.SetPosition(pcbnew.VECTOR2I(pcbnew.FromMM(x), pcbnew.FromMM(y))) f.SetOrientationDegrees(rot) seen.add(r) missing = set(d) - seen if missing: sys.exit("not on the board: %s" % ", ".join(sorted(missing))) for t in list(b.GetTracks()): b.Delete(t) # not Remove: it breaks the board lists (knowledge/tooling/kicad.md) pro_src = src[:-len(".kicad_pcb")] + ".kicad_pro" pro_out = out[:-len(".kicad_pcb")] + ".kicad_pro" keep = open(pro_src).read() pcbnew.SaveBoard(out, b) open(pro_out, "w").write(keep) dru = src[:-len(".kicad_pcb")] + ".kicad_dru" if os.path.exists(dru): shutil.copy(dru, out[:-len(".kicad_pcb")] + ".kicad_dru") print("placed %d footprints -> %s" % (len(seen), out)) if __name__ == "__main__": main(*sys.argv[1:4])