from typing import Any from ee.kicad.read_schematic import read_schematic, read_schematics from ee.kicad.to_bom import to_bom, to_bom_xml from .model import * from .._utils import run_filters __all__ = [ "Component", "ComponentField", "Position", "read_schematic", "read_schematics", "Schematic", "to_bom", "to_bom_xml", "to_pandas", ] def parse_ref(ref): m = parse_ref.r.match(ref) if not m: return g = m.groups() return g[0], None if g[1] == "?" else int(g[1]) parse_ref.r = re.compile("([^0-9]+)([0-9]+|\?)$") def to_pandas(obj: Any, **kwarg): import pandas def to_pandas_schematics(ss: Schematics): dfs = [to_pandas_schematic(schematic) for schematic in ss.schematics] df = pandas.concat(dfs). \ sort_values(["ref_type", "ref_num"]). \ applymap(lambda s: s if isinstance(s, str) else None) return df def to_pandas_schematic(sch: Schematic): # These fields will always be put first. special_fields = ["ref", "ref_type", "ref_num", "value", "footprint"] def make_dict(c: Component): fields = { "ref": c.ref, "ref_type": c.ref_type, "value": c.value, "footprint": c.footprint, } if c.has_ref_num: fields["ref_num"] = c.ref_num fields.update({f.name: f.value for f in c.fields if f.is_custom}) return fields components = sch.components filters = [] include_pwr = kwarg.get("include_pwr", False) if not include_pwr: filters.append(lambda c: not c.is_pwr) include_flg = kwarg.get("include_flg", False) if not include_flg: filters.append(lambda c: c.ref_type != "#FLG") data = [make_dict(c) for c in components if run_filters(filters, c)] columns = set([key for row in data for key in list(row)]) - set(special_fields) columns = special_fields + list(columns) df = pandas.DataFrame(data=data, columns=columns). \ set_index("ref"). \ sort_values(["ref_type", "ref_num"]). \ applymap(lambda s: s if isinstance(s, str) else None) return df if isinstance(obj, Schematic): return to_pandas_schematic(obj) elif isinstance(obj, Schematics): return to_pandas_schematics(obj) else: raise EeException("Unsupported type: {}".format(type(obj)))