moonplacement

    Audit PCB assembly placement coordinates, register them against anchors and cross-check them with Gerber copper.

    pcb
    smt
    kicad
    gerber
    placement
    Download zip
    Author
    Version
    0.1.1
    License
    MIT
    Last updated
    6 hours ago
    Downloads
    6

    No dependencies

    #MoonPlacement

    MoonPlacement 检查

    PCB 送厂前,用 MoonPlacement 对照设计坐标表和送厂坐标表,找出漏件、多件、贴错面、偏位和角度差。手边有 Gerber 铜层的话,还能检查两张表是否把同一颗器件都标错了位置。

    #安装并运行

    安装 MoonBit 和 Node.js 22.3 或更新版本。CI 使用 moonc v0.10.16+b1a0e846e。不用安装 npm 依赖。

    git clone https://github.com/huahai29/moonplacement.git cd moonplacement moon build --target js node _build/js/debug/build/cmd/main/main.js examples/baseline.csv examples/delivery-ok.csv examples/policy.json

    正常会输出 "status": "pass"。把送厂表换成 examples/delivery-errors.csv,可以看到 C7 漏件和 D1 错面。加上顶层铜文件和 --html,就能在浏览器里查看报告:

    node _build/js/debug/build/cmd/main/main.js examples/baseline.csv examples/delivery-ok.csv examples/policy.json examples/top-copper.gbr --html _build/report.html

    #核对自己的板子

    1. 导出同一版 PCB 的设计表和送厂表,保存为 UTF-8 CSV。支持 KiCad 位置表和嘉立创 CPL 风格的列名。
    2. 复制示例配置,填写单位、底面 X 和角度约定,选至少三颗位置分散且确认正确的器件作为对齐基准。自动判断底面 X 时,选一颗远离 X=0 的底面基准。
    3. 运行上面的命令。核对铜层时,先传顶层、再传底层。Gerber 与设计坐标表须使用同一原点和坐标方向。

    报告先看 status,再看 differences(两表差异)和 pad_evidence(铜层证据)。无法对齐时,查看 frame.anchor_residuals 或 rejected_frames 排查基准。焊盘归属来自 Gerber X2 位号;缺少归属时,附近有铜也不足以确认器件。非对称封装的贴装原点可能和铜形中心不同。

    退出码状态含义
    0pass已完成所要求的核对,未发现差异
    1different已确认差异
    2indeterminate对齐或铜层证据不足,需复查
    64input_error输入文件、参数或数据无效

    #可复现案例

    0.1.1 版本与验收汇总库安装、实导出、拼板复现和性能数据。在 MoonBit 项目中使用时,运行 moon add huahai29/moonplacement@0.1.1。

    Windows 和 Linux 的 CLI 报告会在 CI 中逐项比对,含中文路径下生成 HTML 的案例。一致性检查

    解析、配准和判定由 MoonBit 实现。Gerber 2024.05 是兼容目标,当前覆盖以验收表为准。KiCad 和 PyGerber 只用于验证样例。

    GerberError

    pub(all) suberror GerberError {
    InvalidGerber(String, String)
    }

    Raised when a Gerber file cannot be interpreted.

    InputError

    pub(all) suberror InputError {
    InvalidInput(String, String)
    }

    AuditResult

    pub struct AuditResult {
    verdict : Verdict
    report :
    Json

    }

    CopperPad

    pub struct CopperPad {
    refdes : String?
    shape : Shape
    center : Point
    area : Double
    }

    A dark, flashed pad extracted from a Gerber layer.

    GerberArc

    pub struct GerberArc {
    center : Point
    start_vector : Point
    end_vector : Point
    clockwise : Bool
    sweep : Double
    radius : Double
    deviation : Double
    stroke_radius : Double
    }

    Circular centerline and stroke radius. The deviation bounds the effect of unequal endpoint radii in a rounded Gerber export.

    GerberBounds

    pub struct GerberBounds {
    lower : Point
    upper : Point
    }

    GerberContour

    pub struct GerberContour {
    points : Array[Point]
    error : Double
    bounds : GerberBounds
    }

    GerberDocument

    pub struct GerberDocument {
    features : Array[GerberFeature]
    warnings : Array[String]
    repeated_refs : Map[String, Bool]
    panel_grids : Array[GerberGrid]
    panel_cell : PanelCell?
    }

    Parsed Gerber layer. warnings records constructs that were intentionally approximated or skipped so callers can surface them.

    GerberFeature

    pub struct GerberFeature {
    kind : GerberKind
    dark : Bool
    refdes : String?
    pin : String?
    statement_number : Int
    block_instance : Int?
    }

    A single feature with the X2 component attribution (if present) and the polarity active when it was drawn.

    GerberGrid

    pub struct GerberGrid {
    columns : Int
    rows : Int
    dx : Double
    dy : Double
    footprint : GerberBounds
    }

    GerberKind

    pub enum GerberKind {
    Flash(Shape, Point)
    Draw(Shape, Point, Point)
    Arc(GerberArc)
    Region(GerberRegion)
    }

    One parsed Gerber drawing operation.

    GerberRegion

    pub struct GerberRegion {
    contours : Array[GerberContour]
    bounds : GerberBounds
    }

    Closed outlines filled independently. Retraced cut-ins within an outline cancel under parity; a separate contour never subtracts from another.

    PanelCell

    pub struct PanelCell {
    row : Int
    column : Int
    grid : GerberGrid
    offset_mm : Point
    }

    One-based row (positive Y) and column (positive X) of a Gerber SR grid.

    PlacementTable

    pub struct PlacementTable {
    // private fields
    }

    Point

    pub struct Point {
    x : Double
    y : Double
    }

    A point in millimetres, shared by the audit pipeline and the registration engine.

    Policy

    pub struct Policy {
    // private fields
    }

    Registration

    pub struct Registration {
    model : TransformModel
    transform : Transform2D
    rotation_deg : Double
    scale : Double
    rms_mm : Double
    max_mm : Double
    inlier_mask : Array[Bool]
    residuals_mm : Array[Double]
    }

    Robust registration result in the source-to-target direction.

    inlier_mask[i] is true when correspondence i agreed with the consensus set; the residual arrays keep the same length as the anchor list so callers can report per-anchor evidence without recomputing anything.

    Registration::inlier_count

    fn Registration::inlier_count(self : Registration) -> Int

    Number of correspondences that agreed with the robust consensus.

    Shape

    pub enum Shape {
    Circle(Double)
    Rectangle(Double, Double)
    Obround(Double, Double)
    Polygon(Double, Int)
    Transformed(Shape, Transform2D)
    RoundedOutline(Array[Point], Double)
    RoundHole(Shape, Point, Point, Double)
    Outline(Array[Point])
    Thermal(Double, Double, Double)
    Punched(Shape, Point, Array[(Point, Double)])
    }

    A centered pad aperture. All parameters are in millimetres.

    Gerber C, R, O and P apertures map directly onto these variants; the same shapes are reused by the geometry checks so parsing and verification share one area/containment implementation.

    Shape::area

    fn Shape::area(self : Shape) -> Double

    Shape::contains

    fn Shape::contains(self : Shape, center : Point, point : Point) -> Bool

    Whether point lies inside the shape centered at center.

    Shape::expanded

    fn Shape::expanded(self : Shape, amount : Double) -> Shape

    Grow the shape by amount on every side. Used to test a point against a pad with a tolerance instead of treating a near miss as empty copper.

    Transform2D

    pub struct Transform2D {
    a : Double
    b : Double
    c : Double
    d : Double
    e : Double
    f : Double
    }

    A 2D affine map p' = M * p + t with M = [[a, b], [d, e]].

    The same struct carries rigid, similarity and affine fits, so the audit report can describe every accepted alignment with one type.

    Transform2D::apply

    fn Transform2D::apply(self : Transform2D, p : Point) -> Point

    Transform2D::determinant

    fn Transform2D::determinant(self : Transform2D) -> Double

    Transform2D::identity

    fn Transform2D::identity() -> Transform2D

    Transform2D::quarter_turns

    fn Transform2D::quarter_turns(turns : Int, t : Point) -> Transform2D

    Exact quarter-turn rotation followed by a translation. The coefficients are integers so that existing quarter-turn reports stay bit-for-bit stable.

    Transform2D::rotation

    fn Transform2D::rotation(degrees : Double, t : Point, scale? : Double) -> Transform2D

    Counter-clockwise rotation by degrees with a uniform scale, followed by a translation.

    Transform2D::rotation_deg

    fn Transform2D::rotation_deg(self : Transform2D) -> Double

    Counter-clockwise rotation of the image of the X axis, in degrees.

    Transform2D::scale

    fn Transform2D::scale(self : Transform2D) -> Double

    Uniform scale of the linear part. For a rigid or similarity map this is the exact scale factor; for a general affine map it is the geometric mean of the two singular values.

    Transform2D::translation

    fn Transform2D::translation(self : Transform2D) -> Point

    Transform2D::with_translation

    fn Transform2D::with_translation(self : Transform2D, t : Point) -> Transform2D

    TransformModel

    pub enum TransformModel {
    Rigid
    Similarity
    Affine
    }

    Transform family estimated by the registration engine.

    Verdict

    pub(all) enum Verdict {
    Pass
    Different
    Indeterminate
    }

    REPORT_SCHEMA_VERSION

    let REPORT_SCHEMA_VERSION : Int

    Schema used by audit results and CLI input errors.

    audit

    fn audit(baseline_table : PlacementTable, delivery_table : PlacementTable, policy : Policy, top_gerber? : GerberDocument?, bottom_gerber? : GerberDocument?) -> AuditResult

    Compare two exports of the same board revision. Membership and side are always checked. Geometry requires a unique frame.

    top_gerber and bottom_gerber are optional parsed copper layers used for the pad-level cross-check; when absent the report records an empty pad list and the previous behaviour is unchanged.

    check_pads

    fn check_pads(document : GerberDocument, refdes : Array[String], positions : Array[Point], tolerance_mm : Double) -> Array[
    Json
    ]

    Return attributable pad-centre offsets beyond tolerance. The audit report also exposes the evidence for coordinates whose ownership is unknown.

    copper_at

    fn copper_at(document : GerberDocument, point : Point, tolerance : Double) -> Bool

    Approximate nearby copper from flashes, arc strokes and regions. This cannot establish ownership. A possibly intersecting clear object removes positive evidence.

    copper_centroid

    fn copper_centroid(pads : Array[CopperPad]) -> Point

    Area-weighted centre of a pad group. This is a geometric reference, which may differ from the placement origin of an asymmetric footprint.

    gerber_pads

    fn gerber_pads(document : GerberDocument) -> Array[CopperPad]

    Extract the flashed dark pads from a parsed layer.

    pad_groups

    fn pad_groups(pads : Array[CopperPad]) -> Map[String, Array[CopperPad]]

    Group pads by their X2 component reference.

    parse_gerber

    fn parse_gerber(text : String, source~ : String) -> GerberDocument raise GerberError

    Parse an RS-274X Gerber file.

    Reads standard apertures, selected macros, flashes, strokes, regions, block apertures, step repeats, polarity and X2 component/pin attributes.

    polygon_area

    fn polygon_area(points : Array[Point]) -> Double

    Signed area of a closed polygon (shoelace formula). Positive for a counter-clockwise ring.

    polygon_centroid

    fn polygon_centroid(points : Array[Point]) -> Point

    polygon_contains

    fn polygon_contains(points : Array[Point], point : Point) -> Bool

    Ray-casting containment test for an arbitrary simple polygon.

    read_placements

    fn read_placements(input : String, source~ : String) -> PlacementTable raise InputError

    Read KiCad or JLC-style placement CSV. Coordinates and angles are as exported.

    read_policy

    fn read_policy(input : String) -> Policy raise InputError

    Parse the coordinate conventions and tolerances for a comparison.

    register

    fn register(source : Array[Point], target : Array[Point], model : TransformModel, threshold_mm : Double) -> Registration?

    Robustly estimate a source -> target transform for model.

    Every minimal sample is tried, then the best consensus set is refit twice. Enumerating instead of drawing random samples keeps the report deterministic for a fixed input, which the CI and the tolerance regression rely on.

    render_html

    fn render_html(report :
    Json
    , baseline : PlacementTable) -> String

    Render a self-contained HTML report. The board map uses the trusted baseline positions and draws a red arrow for every reported position offset.

    select_panel_cell

    fn select_panel_cell(document : GerberDocument, row~ : Int, column~ : Int, source~ : String, reference? : GerberDocument) -> GerberDocument raise GerberError

    Select one unambiguous SR cell and move it to the first cell's coordinate frame. File-wide objects inside the same cell keep their original order. Pass the selected top layer as reference when selecting the bottom layer.