0hmX/TMDS62LEVM

This code defines the physical layout and component placement for a TI AM62L evaluation module, including mechanical and population components, without routing.

Version
1.0.2
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone 0hmX/TMDS62LEVM  # download the package files into ./TMDS62LEVM
tsci add 0hmX/TMDS62LEVM    # add it to your project as @tsci/0hmX.TMDS62LEVM

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

scripts/extract_ti_design_data.py

#!/usr/bin/env python3
"""Normalize the TMDS62LEVM Altium release BOM, XY, and IDF data.

Requires xlrd 2.x to read the legacy .xls BOM.  This script deliberately keeps
the source placement origin and also derives the geometric center of each IDF
component outline, which is important for offset connector footprints.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import math
import re
import shlex
from collections import Counter
from pathlib import Path

import xlrd


MIL_TO_MM = 0.0254


def round_mm(value: float) -> float:
    return round(value, 6)


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as source:
        for chunk in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def parse_number(value: str) -> float:
    match = re.search(r"[-+]?\d+(?:\.\d+)?", value)
    if not match:
        raise ValueError(f"No number in {value!r}")
    return float(match.group(0))


def parse_outline_and_drills(emn_path: Path) -> tuple[dict, list[dict]]:
    lines = emn_path.read_text(encoding="utf-8", errors="replace").splitlines()

    board_outline_header = next(
        index for index, line in enumerate(lines) if line.startswith(".BOARD_OUTLINE")
    )
    start = board_outline_header + 2
    end = lines.index(".END_BOARD_OUTLINE")
    outline_mil: list[tuple[float, float]] = []
    for line in lines[start:end]:
        fields = line.split()
        if len(fields) >= 3:
            outline_mil.append((float(fields[1]), float(fields[2])))

    min_x = min(point[0] for point in outline_mil)
    max_x = max(point[0] for point in outline_mil)
    min_y = min(point[1] for point in outline_mil)
    max_y = max(point[1] for point in outline_mil)
    center_x = (min_x + max_x) / 2
    center_y = (min_y + max_y) / 2

    outline = {
        "source_units": "mil",
        "nominal_width_mm": 136.0,
        "nominal_height_mm": 142.85,
        "source_bounds_mil": {
            "min_x": min_x,
            "max_x": max_x,
            "min_y": min_y,
            "max_y": max_y,
        },
        "source_center_mil": {"x": center_x, "y": center_y},
        "width_mm": round_mm((max_x - min_x) * MIL_TO_MM),
        "height_mm": round_mm((max_y - min_y) * MIL_TO_MM),
        "vertices_mm_centered": [
            {
                "x": round_mm((x - center_x) * MIL_TO_MM),
                "y": round_mm((y - center_y) * MIL_TO_MM),
            }
            for x, y in outline_mil
        ],
    }

    start = lines.index(".DRILLED_HOLES") + 1
    end = lines.index(".END_DRILLED_HOLES")
    unique_holes: dict[tuple[float, float, float], dict] = {}
    for line in lines[start:end]:
        fields = line.split()
        if len(fields) < 4:
            continue
        diameter, x, y = map(float, fields[:3])
        # The IDF file also contains panel copies outside the individual board.
        if not (min_x <= x <= max_x and min_y <= y <= max_y):
            continue
        key = (diameter, x, y)
        unique_holes[key] = {
            "diameter_mm": round_mm(diameter * MIL_TO_MM),
            "x_mm_centered": round_mm((x - center_x) * MIL_TO_MM),
            "y_mm_centered": round_mm((y - center_y) * MIL_TO_MM),
            "source_diameter_mil": diameter,
            "source_x_mil": x,
            "source_y_mil": y,
            "plating": fields[3],
            "owner": " ".join(fields[4:]),
        }

    drills = sorted(
        unique_holes.values(),
        key=lambda hole: (
            hole["y_mm_centered"],
            hole["x_mm_centered"],
            hole["diameter_mm"],
        ),
    )
    return outline, drills


def parse_idf_library(emp_path: Path) -> dict[tuple[str, str], dict]:
    lines = emp_path.read_text(encoding="utf-8", errors="replace").splitlines()
    outlines: dict[tuple[str, str], dict] = {}
    index = 0
    while index < len(lines):
        if lines[index].strip() != ".ELECTRICAL":
            index += 1
            continue
        header = shlex.split(lines[index + 1])
        points: list[tuple[float, float]] = []
        index += 2
        while index < len(lines) and lines[index].strip() != ".END_ELECTRICAL":
            fields = lines[index].split()
            if len(fields) >= 4:
                try:
                    points.append((float(fields[1]), float(fields[2])))
                except ValueError:
                    pass
            index += 1
        if len(header) >= 4 and points:
            min_x = min(point[0] for point in points)
            max_x = max(point[0] for point in points)
            min_y = min(point[1] for point in points)
            max_y = max(point[1] for point in points)
            outlines[(header[0], header[1])] = {
                "local_bounds_mil": {
                    "min_x": min_x,
                    "max_x": max_x,
                    "min_y": min_y,
                    "max_y": max_y,
                },
                "local_center_mil": {
                    "x": (min_x + max_x) / 2,
                    "y": (min_y + max_y) / 2,
                },
                "width_mm_unrotated": round_mm((max_x - min_x) * MIL_TO_MM),
                "height_mm_unrotated": round_mm((max_y - min_y) * MIL_TO_MM),
                "height_mm": round_mm(float(header[3]) * MIL_TO_MM),
            }
    return outlines


def parse_idf_placements(emn_path: Path) -> dict[str, dict]:
    lines = emn_path.read_text(encoding="utf-8", errors="replace").splitlines()
    start = lines.index(".PLACEMENT") + 1
    end = lines.index(".END_PLACEMENT")
    placements: dict[str, dict] = {}
    index = start
    while index < end:
        identity = shlex.split(lines[index])
        position = lines[index + 1].split()
        if len(identity) >= 3 and len(position) >= 6:
            placements[identity[-1]] = {
                "footprint": identity[0],
                "value": identity[1],
                "source_x_mil": float(position[0]),
                "source_y_mil": float(position[1]),
                "source_z_mil": float(position[2]),
                "rotation_deg": float(position[3]),
                "layer": position[4].lower(),
                "status": position[5].lower(),
            }
        index += 2
    return placements


def parse_xy(
    xy_path: Path,
    board: dict,
    outlines: dict[tuple[str, str], dict],
    idf_placements: dict[str, dict],
) -> list[dict]:
    lines = xy_path.read_text(encoding="utf-8-sig", errors="replace").splitlines()
    header_index = next(
        index for index, line in enumerate(lines) if line.startswith("Designator\t")
    )
    rows = csv.DictReader(lines[header_index:], delimiter="\t")
    center_x = board["source_center_mil"]["x"]
    center_y = board["source_center_mil"]["y"]
    placements: list[dict] = []
    for row in rows:
        if not row.get("Designator"):
            continue
        footprint = row["Footprint"].strip()
        value = row["Comment"].strip()
        x_mil = parse_number(row["Center-X(mil)"])
        y_mil = parse_number(row["Center-Y(mil)"])
        rotation = float(row["Rotation"])
        outline = outlines[(footprint, value)]
        idf_placement = idf_placements[row["Designator"].strip()]
        local_center = outline["local_center_mil"]

        # IDF electrical outlines are planar. This conventional rotation gives
        # the useful geometric center for offset footprints such as J4.
        idf_rotation = idf_placement["rotation_deg"]
        idf_angle = math.radians(idf_rotation)
        offset_x = (
            local_center["x"] * math.cos(idf_angle)
            - local_center["y"] * math.sin(idf_angle)
        )
        offset_y = (
            local_center["x"] * math.sin(idf_angle)
            + local_center["y"] * math.cos(idf_angle)
        )
        unrotated_width = outline["width_mm_unrotated"]
        unrotated_height = outline["height_mm_unrotated"]
        abs_cos = abs(math.cos(idf_angle))
        abs_sin = abs(math.sin(idf_angle))
        axis_aligned_width = unrotated_width * abs_cos + unrotated_height * abs_sin
        axis_aligned_height = unrotated_width * abs_sin + unrotated_height * abs_cos

        placements.append(
            {
                "refdes": row["Designator"].strip(),
                "value": value,
                "footprint": footprint,
                "layer": "top" if row["Layer"].strip() == "TopLayer" else "bottom",
                "rotation_deg": rotation,
                "x_mm_centered": round_mm((x_mil - center_x) * MIL_TO_MM),
                "y_mm_centered": round_mm((y_mil - center_y) * MIL_TO_MM),
                "source_x_mil": x_mil,
                "source_y_mil": y_mil,
                "description": row["Description"].strip(),
                "idf_placement": {
                    **idf_placement,
                    "x_mm_centered": round_mm(
                        (idf_placement["source_x_mil"] - center_x) * MIL_TO_MM
                    ),
                    "y_mm_centered": round_mm(
                        (idf_placement["source_y_mil"] - center_y) * MIL_TO_MM
                    ),
                },
                "idf_outline": {
                    **outline,
                    "geometric_center_x_mm": round_mm(
                        (
                            idf_placement["source_x_mil"]
                            + offset_x
                            - center_x
                        )
                        * MIL_TO_MM
                    ),
                    "geometric_center_y_mm": round_mm(
                        (
                            idf_placement["source_y_mil"]
                            + offset_y
                            - center_y
                        )
                        * MIL_TO_MM
                    ),
                    "axis_aligned_width_mm": round_mm(axis_aligned_width),
                    "axis_aligned_height_mm": round_mm(axis_aligned_height),
                },
            }
        )
    return placements


def parse_bom(bom_path: Path) -> tuple[list[dict], dict[str, dict], dict[str, dict]]:
    sheet = xlrd.open_workbook(str(bom_path)).sheet_by_name("BOM")
    headers = [str(sheet.cell_value(11, column)).strip() for column in range(15)]
    all_by_ref: dict[str, dict] = {}
    populated_by_ref: dict[str, dict] = {}
    item_rows: list[dict] = []
    for row_index in range(12, sheet.nrows):
        values = [sheet.cell_value(row_index, column) for column in range(15)]
        if not values[1]:
            continue
        references = [
            ref.strip()
            for ref in re.split(r"[,\s]+", str(values[1]))
            if ref.strip()
        ]
        quantity = int(float(values[13] or 0))
        item = {
            "bom_item": int(float(values[0])),
            "source_row": row_index + 1,
            "references": references,
            "description": str(values[2]).strip(),
            "value": str(values[3]).strip(),
            "tolerance": str(values[4]).strip(),
            "rating": str(values[5]).strip(),
            "footprint": str(values[6]).strip(),
            "package_type": str(values[7]).strip(),
            "temperature_rating": str(values[8]).strip(),
            "manufacturer": str(values[9]).strip(),
            "mpn": str(values[10]).strip(),
            "alternate_manufacturer": str(values[11]).strip(),
            "internal_part_number": str(values[12]).strip(),
            "quantity_per_board": quantity,
            "unit_of_measure": str(values[14]).strip(),
        }
        item_rows.append(item)
        for refdes in references:
            expanded = {key: value for key, value in item.items() if key != "references"}
            expanded["refdes"] = refdes
            all_by_ref[refdes] = expanded
            if quantity > 0:
                populated_by_ref[refdes] = expanded

    return item_rows, all_by_ref, populated_by_ref


def natural_refdes_key(refdes: str) -> tuple[str, int, str]:
    match = re.match(r"([A-Za-z]+)(\d+)(.*)", refdes)
    if not match:
        return (refdes, -1, "")
    return (match.group(1), int(match.group(2)), match.group(3))


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--bom", type=Path, required=True)
    parser.add_argument("--xy", type=Path, required=True)
    parser.add_argument("--emn", type=Path, required=True)
    parser.add_argument("--emp", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    args = parser.parse_args()

    args.output_dir.mkdir(parents=True, exist_ok=True)
    board, drills = parse_outline_and_drills(args.emn)
    outlines = parse_idf_library(args.emp)
    idf_placements = parse_idf_placements(args.emn)
    placements = parse_xy(args.xy, board, outlines, idf_placements)
    item_rows, all_bom_by_ref, populated_by_ref = parse_bom(args.bom)
    placement_by_ref = {placement["refdes"]: placement for placement in placements}

    populated_records: list[dict] = []
    for refdes in sorted(populated_by_ref, key=natural_refdes_key):
        bom = populated_by_ref[refdes]
        placement = placement_by_ref.get(refdes)
        populated_records.append(
            {
                **bom,
                "placement_found": placement is not None,
                "placement": placement,
            }
        )

    all_placements: list[dict] = []
    for placement in sorted(placements, key=lambda row: natural_refdes_key(row["refdes"])):
        refdes = placement["refdes"]
        bom = all_bom_by_ref.get(refdes)
        all_placements.append(
            {
                **placement,
                "populated_in_bom": refdes in populated_by_ref,
                "listed_in_bom": bom is not None,
                "bom": bom,
            }
        )

    unmatched_populated = sorted(
        set(populated_by_ref) - set(placement_by_ref), key=natural_refdes_key
    )
    placement_only = sorted(
        set(placement_by_ref) - set(populated_by_ref), key=natural_refdes_key
    )
    prefix_counts = Counter(
        re.match(r"[A-Za-z]+", refdes).group(0)
        for refdes in populated_by_ref
        if re.match(r"[A-Za-z]+", refdes)
    )

    source_files = {
        "bom": {"name": args.bom.name, "sha256": sha256(args.bom)},
        "xy": {"name": args.xy.name, "sha256": sha256(args.xy)},
        "emn": {"name": args.emn.name, "sha256": sha256(args.emn)},
        "emp": {"name": args.emp.name, "sha256": sha256(args.emp)},
    }
    metadata = {
        "board": "TMDS62LEVM / PROC181E1-1",
        "source_release": "TI SPRCAL9 design package, Altium release dated 2025-07",
        "source_files": source_files,
        "coordinate_system": {
            "origin": "center of the IDF board-outline bounding box",
            "x_positive": "right",
            "y_positive": "up",
            "units": "mm",
            "canonical_position": "placement.x_mm_centered / placement.y_mm_centered",
            "note": "IDF geometric centers are derived from the component outline and are useful for offset connector bodies; placement coordinates remain canonical.",
        },
        "counts": {
            "bom_item_rows_all": len(item_rows),
            "bom_item_rows_populated": sum(
                item["quantity_per_board"] > 0 for item in item_rows
            ),
            "populated_references": len(populated_by_ref),
            "populated_references_with_xy": len(populated_by_ref) - len(unmatched_populated),
            "populated_references_without_xy": len(unmatched_populated),
            "xy_placements_all": len(placements),
            "xy_placements_not_in_populated_bom": len(placement_only),
            "unique_idf_drills_on_board": len(drills),
            "idf_library_outlines": len(outlines),
        },
        "populated_reference_counts_by_prefix": dict(sorted(prefix_counts.items())),
        "unmatched_populated_references": unmatched_populated,
        "assumptions": [
            "A BOM row is populated only when Per Board Qty is greater than zero.",
            "The BOM has no active Altium variants; quantity zero rows are treated as DNP/accessory alternatives.",
            "Eight positive-quantity BOM references have no XY row: ACC4/ACC5 are loose accessories, MH3/MH5 are mounting hardware, and FID1-FID4 reflect a BOM/XY fiducial naming mismatch.",
            "The IDF drill section contains duplicate and panel-copy coordinates; mechanical output keeps one instance of each unique drill located inside the individual board outline.",
            "The fabrication drawing's nominal board size is 136.00 x 142.85 mm; the IDF outline bounding box measures 136.028786 x 142.875762 mm because its vertices include edge/corner tolerance excursions.",
        ],
    }

    main_output = {
        "metadata": metadata,
        "board": board,
        "populated_bom_placement": populated_records,
        "all_xy_placements": all_placements,
    }
    mechanical_output = {
        "metadata": {
            "board": metadata["board"],
            "source_files": {"emn": source_files["emn"]},
            "coordinate_system": metadata["coordinate_system"],
            "note": "Drills include vias, component holes, and mechanical holes; they are not exclusively mounting holes.",
        },
        "board": board,
        "drills": drills,
    }

    (args.output_dir / "tmds62levm_bom_placement.json").write_text(
        json.dumps(main_output, indent=2) + "\n", encoding="utf-8"
    )
    (args.output_dir / "tmds62levm_board_mechanical.json").write_text(
        json.dumps(mechanical_output, indent=2) + "\n", encoding="utf-8"
    )

    csv_fields = [
        "refdes",
        "description",
        "value",
        "manufacturer",
        "mpn",
        "footprint",
        "layer",
        "rotation_deg",
        "x_mm_centered",
        "y_mm_centered",
        "geometric_center_x_mm",
        "geometric_center_y_mm",
        "axis_aligned_width_mm",
        "axis_aligned_height_mm",
        "placement_found",
    ]
    with (args.output_dir / "tmds62levm_populated_bom_placement.csv").open(
        "w", newline="", encoding="utf-8"
    ) as output:
        writer = csv.DictWriter(output, fieldnames=csv_fields, lineterminator="\n")
        writer.writeheader()
        for record in populated_records:
            placement = record["placement"] or {}
            outline = placement.get("idf_outline", {})
            writer.writerow(
                {
                    "refdes": record["refdes"],
                    "description": record["description"],
                    "value": record["value"],
                    "manufacturer": record["manufacturer"],
                    "mpn": record["mpn"],
                    "footprint": record["footprint"],
                    "layer": placement.get("layer", ""),
                    "rotation_deg": placement.get("rotation_deg", ""),
                    "x_mm_centered": placement.get("x_mm_centered", ""),
                    "y_mm_centered": placement.get("y_mm_centered", ""),
                    "geometric_center_x_mm": outline.get("geometric_center_x_mm", ""),
                    "geometric_center_y_mm": outline.get("geometric_center_y_mm", ""),
                    "axis_aligned_width_mm": outline.get("axis_aligned_width_mm", ""),
                    "axis_aligned_height_mm": outline.get("axis_aligned_height_mm", ""),
                    "placement_found": record["placement_found"],
                }
            )


if __name__ == "__main__":
    main()