Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
Move util imports
Browse files Browse the repository at this point in the history
  • Loading branch information
iopapamanoglou committed Aug 27, 2024
1 parent 2acc91a commit c66b86c
Show file tree
Hide file tree
Showing 29 changed files with 132 additions and 113 deletions.
1 change: 1 addition & 0 deletions src/faebryk/core/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@ def __init__(self):
self._is_setup = True

def __preinit__(self): ...

def __postinit__(self): ...

def __post_init__(self, *args, **kwargs):
Expand Down
60 changes: 26 additions & 34 deletions src/faebryk/core/util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# This file is part of the faebryk project
# SPDX-License-Identifier: MIT

from ast import Call
import logging
from enum import Enum
from textwrap import indent
Expand All @@ -13,6 +12,7 @@

from typing_extensions import deprecated

import faebryk.library._F as F
from faebryk.core.graphinterface import (
Graph,
GraphInterface,
Expand All @@ -25,14 +25,6 @@
from faebryk.core.node import Node
from faebryk.core.parameter import Parameter
from faebryk.core.trait import Trait
from faebryk.library.ANY import ANY
from faebryk.library.can_bridge_defined import can_bridge_defined
from faebryk.library.Constant import Constant
from faebryk.library.Electrical import Electrical
from faebryk.library.has_overriden_name_defined import has_overriden_name_defined
from faebryk.library.Range import Range
from faebryk.library.Set import Set
from faebryk.library.TBD import TBD
from faebryk.libs.units import Quantity, UnitsContainer, to_si_str
from faebryk.libs.util import NotNone, cast_assert, zip_dicts_by_key

Expand All @@ -42,18 +34,18 @@


def enum_parameter_representation(param: Parameter, required: bool = False) -> str:
if isinstance(param, Constant):
if isinstance(param, F.Constant):
return param.value.name if isinstance(param.value, Enum) else str(param.value)
elif isinstance(param, Range):
elif isinstance(param, F.Range):
return (
f"{enum_parameter_representation(param.min)} - "
f"{enum_parameter_representation(param.max)}"
)
elif isinstance(param, Set):
elif isinstance(param, F.Set):
return f"Set({', '.join(map(enum_parameter_representation, param.params))})"
elif isinstance(param, TBD):
elif isinstance(param, F.TBD):
return "TBD" if required else ""
elif isinstance(param, ANY):
elif isinstance(param, F.ANY):
return "ANY" if required else ""
else:
return type(param).__name__
Expand All @@ -67,23 +59,23 @@ def as_unit(
) -> str:
if base != 1000:
raise NotImplementedError("Only base 1000 supported")
if isinstance(param, Constant):
if isinstance(param, F.Constant):
return to_si_str(param.value, unit)
elif isinstance(param, Range):
elif isinstance(param, F.Range):
return (
as_unit(param.min, unit, base=base)
+ " - "
+ as_unit(param.max, unit, base=base, required=True)
)
elif isinstance(param, Set):
elif isinstance(param, F.Set):
return (
"Set("
+ ", ".join(map(lambda x: as_unit(x, unit, required=True), param.params))
+ ")"
)
elif isinstance(param, TBD):
elif isinstance(param, F.TBD):
return "TBD" if required else ""
elif isinstance(param, ANY):
elif isinstance(param, F.ANY):
return "ANY" if required else ""

raise ValueError(f"Unsupported {param=}")
Expand All @@ -92,41 +84,41 @@ def as_unit(
def as_unit_with_tolerance(
param: Parameter, unit: str, base: int = 1000, required: bool = False
) -> str:
if isinstance(param, Constant):
if isinstance(param, F.Constant):
return as_unit(param, unit, base=base)
elif isinstance(param, Range):
elif isinstance(param, F.Range):
center, delta = param.as_center_tuple(relative=True)
delta_percent_str = f"±{to_si_str(delta.value, "%", 0)}"
return (
f"{as_unit(center, unit, base=base, required=required)} {delta_percent_str}"
)
elif isinstance(param, Set):
elif isinstance(param, F.Set):
return (
"Set("
+ ", ".join(
map(lambda x: as_unit_with_tolerance(x, unit, base), param.params)
)
+ ")"
)
elif isinstance(param, TBD):
elif isinstance(param, F.TBD):
return "TBD" if required else ""
elif isinstance(param, ANY):
elif isinstance(param, F.ANY):
return "ANY" if required else ""
raise ValueError(f"Unsupported {param=}")


def get_parameter_max(param: Parameter):
if isinstance(param, Constant):
if isinstance(param, F.Constant):
return param.value
if isinstance(param, Range):
if isinstance(param, F.Range):
return param.max
if isinstance(param, Set):
if isinstance(param, F.Set):
return max(map(get_parameter_max, param.params))
raise ValueError(f"Can't get max for {param}")


def with_same_unit(to_convert: float | int, param: Parameter | Quantity | float | int):
if isinstance(param, Constant) and isinstance(param.value, Quantity):
if isinstance(param, F.Constant) and isinstance(param.value, Quantity):
return Quantity(to_convert, param.value.units)
if isinstance(param, Quantity):
return Quantity(to_convert, param.units)
Expand Down Expand Up @@ -257,7 +249,7 @@ def get_direct_connected_nodes[T: Node](
return cast(set[T], out)


def get_net(mif: Electrical):
def get_net(mif: F.Electrical):
from faebryk.library.Net import Net

nets = {
Expand Down Expand Up @@ -446,7 +438,7 @@ def __init__(self) -> None:
if_in = bridge_trait.get_in()
if_out = bridge_trait.get_out()

self.add_trait(can_bridge_defined(if_out, if_in))
self.add_trait(F.can_bridge_defined(if_out, if_in))

return _reversed_bridge()

Expand Down Expand Up @@ -632,7 +624,7 @@ def use_interface_names_as_net_names(node: Node, name: str | None = None):

name_prefix = node.get_full_name()

el_ifs = {n for n in get_all_nodes(node) if isinstance(n, Electrical)}
el_ifs = {n for n in get_all_nodes(node) if isinstance(n, F.Electrical)}

# for el_if in el_ifs:
# print(el_if)
Expand All @@ -642,7 +634,7 @@ def use_interface_names_as_net_names(node: Node, name: str | None = None):
resolved: set[ModuleInterface] = set()

# get representative interfaces that determine the name of the Net
to_use: set[Electrical] = set()
to_use: set[F.Electrical] = set()
for el_if in el_ifs:
# performance
if el_if in resolved:
Expand Down Expand Up @@ -675,7 +667,7 @@ def use_interface_names_as_net_names(node: Node, name: str | None = None):
# performance
resolved.update(group)

nets: dict[str, tuple[Net, Electrical]] = {}
nets: dict[str, tuple[Net, F.Electrical]] = {}
for el_if in to_use:
net_name = f"{name}{el_if.get_full_name().removeprefix(name_prefix)}"

Expand All @@ -694,7 +686,7 @@ def use_interface_names_as_net_names(node: Node, name: str | None = None):
)

net = Net()
net.add_trait(has_overriden_name_defined(net_name))
net.add_trait(F.has_overriden_name_defined(net_name))
net.part_of.connect(el_if)
logger.debug(f"Created {net_name} for {el_if}")
nets[net_name] = net, el_if
Expand Down
48 changes: 21 additions & 27 deletions src/faebryk/exporters/pcb/kicad/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from shapely import Polygon
from typing_extensions import deprecated

import faebryk.library._F as F
from faebryk.core.graphinterface import Graph
from faebryk.core.module import Module
from faebryk.core.moduleinterface import ModuleInterface
Expand All @@ -23,16 +24,6 @@
get_all_nodes_with_traits,
get_children,
)
from faebryk.library.Electrical import Electrical
from faebryk.library.Footprint import (
Footprint as FFootprint,
)
from faebryk.library.has_footprint import has_footprint
from faebryk.library.has_kicad_footprint import has_kicad_footprint
from faebryk.library.has_overriden_name import has_overriden_name
from faebryk.library.has_pcb_position import has_pcb_position
from faebryk.library.Net import Net as FNet
from faebryk.library.Pad import Pad as FPad
from faebryk.libs.geometry.basic import Geometry
from faebryk.libs.kicad.fileformats import (
UUID,
Expand All @@ -56,6 +47,9 @@

logger = logging.getLogger(__name__)

FPad = F.Pad
FNet = F.Net
FFootprint = F.Footprint

PCB = C_kicad_pcb_file.C_kicad_pcb
Footprint = PCB.C_pcb_footprint
Expand Down Expand Up @@ -237,15 +231,15 @@ def attach(self):
(f.propertys["Reference"].value, f.name): f for f in self.pcb.footprints
}

for node, fpt in get_all_nodes_with_trait(self.graph, has_footprint):
if not node.has_trait(has_overriden_name):
for node, fpt in get_all_nodes_with_trait(self.graph, F.has_footprint):
if not node.has_trait(F.has_overriden_name):
continue
g_fp = fpt.get_footprint()
if not g_fp.has_trait(has_kicad_footprint):
if not g_fp.has_trait(F.has_kicad_footprint):
continue

fp_ref = node.get_trait(has_overriden_name).get_name()
fp_name = g_fp.get_trait(has_kicad_footprint).get_kicad_footprint()
fp_ref = node.get_trait(F.has_overriden_name).get_name()
fp_name = g_fp.get_trait(F.has_kicad_footprint).get_kicad_footprint()

assert (
fp_ref,
Expand All @@ -259,7 +253,7 @@ def attach(self):
g_fp.add_trait(self.has_linked_kicad_footprint_defined(fp, self))
node.add_trait(self.has_linked_kicad_footprint_defined(fp, self))

pin_names = g_fp.get_trait(has_kicad_footprint).get_pin_names()
pin_names = g_fp.get_trait(F.has_kicad_footprint).get_pin_names()
for fpad in get_children(g_fp, direct_only=True, types=ModuleInterface):
pads = [
pad
Expand Down Expand Up @@ -317,7 +311,7 @@ def get_fp(cmp) -> Footprint:

def get_net(self, net: FNet) -> Net:
nets = {pcb_net.name: pcb_net for pcb_net in self.pcb.nets}
return nets[net.get_trait(has_overriden_name).get_name()]
return nets[net.get_trait(F.has_overriden_name).get_name()]

def get_edge(self) -> list[Point2D]:
def geo_to_lines(
Expand Down Expand Up @@ -408,8 +402,8 @@ def geo_to_lines(
return list(poly.exterior.coords)

@staticmethod
def _get_pad(ffp: FFootprint, intf: Electrical):
pin_map = ffp.get_trait(has_kicad_footprint).get_pin_names()
def _get_pad(ffp: FFootprint, intf: F.Electrical):
pin_map = ffp.get_trait(F.has_kicad_footprint).get_pin_names()
pin_name = find(
pin_map.items(),
lambda pad_and_name: intf.is_connected_to(pad_and_name[0].net) is not None,
Expand All @@ -421,14 +415,14 @@ def _get_pad(ffp: FFootprint, intf: Electrical):
return fp, pad

@staticmethod
def get_pad(intf: Electrical) -> tuple[Footprint, Pad, Node]:
def get_pad(intf: F.Electrical) -> tuple[Footprint, Pad, Node]:
obj, ffp = FFootprint.get_footprint_of_parent(intf)
fp, pad = PCB_Transformer._get_pad(ffp, intf)

return fp, pad, obj

@staticmethod
def get_pad_pos_any(intf: Electrical) -> list[tuple[FPad, Point]]:
def get_pad_pos_any(intf: F.Electrical) -> list[tuple[FPad, Point]]:
try:
fpads = FPad.find_pad_for_intf_with_parent_that_has_footprint(intf)
except ValueError:
Expand All @@ -438,7 +432,7 @@ def get_pad_pos_any(intf: Electrical) -> list[tuple[FPad, Point]]:
return [PCB_Transformer._get_pad_pos(fpad) for fpad in fpads]

@staticmethod
def get_pad_pos(intf: Electrical) -> tuple[FPad, Point] | None:
def get_pad_pos(intf: F.Electrical) -> tuple[FPad, Point] | None:
try:
fpad = FPad.find_pad_for_intf_with_parent_that_has_footprint_unique(intf)
except ValueError:
Expand Down Expand Up @@ -709,20 +703,20 @@ def insert_zone(self, net: Net, layers: str | list[str], polygon: list[Point2D])
def move_footprints(self):
# position modules with defined positions
pos_mods = get_all_nodes_with_traits(
self.graph, (has_pcb_position, self.has_linked_kicad_footprint)
self.graph, (F.has_pcb_position, self.has_linked_kicad_footprint)
)

logger.info(f"Positioning {len(pos_mods)} footprints")

for module, _ in pos_mods:
fp = module.get_trait(self.has_linked_kicad_footprint).get_fp()
coord = module.get_trait(has_pcb_position).get_position()
coord = module.get_trait(F.has_pcb_position).get_position()
layer_name = {
has_pcb_position.layer_type.TOP_LAYER: "F.Cu",
has_pcb_position.layer_type.BOTTOM_LAYER: "B.Cu",
F.has_pcb_position.layer_type.TOP_LAYER: "F.Cu",
F.has_pcb_position.layer_type.BOTTOM_LAYER: "B.Cu",
}

if coord[3] == has_pcb_position.layer_type.NONE:
if coord[3] == F.has_pcb_position.layer_type.NONE:
raise Exception(f"Component {module}({fp.name}) has no layer defined")

logger.debug(f"Placing {fp.name} at {coord} layer {layer_name[coord[3]]}")
Expand Down
2 changes: 1 addition & 1 deletion src/faebryk/library/CBM9002A_56ILG_Reference_Design.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import faebryk.library._F as F
from faebryk.core.module import Module
from faebryk.core.util import connect_module_mifs_by_name
from faebryk.libs.library import L
from faebryk.libs.units import P

Expand Down Expand Up @@ -49,6 +48,7 @@ class CBM9002A_56ILG_Reference_Design(Module):
# ----------------------------------------
def __preinit__(self):
gnd = self.vcc.lv
from faebryk.core.util import connect_module_mifs_by_name

connect_module_mifs_by_name(self, self.mcu, allow_partial=True)

Expand Down
11 changes: 6 additions & 5 deletions src/faebryk/library/Capacitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@

import faebryk.library._F as F
from faebryk.core.module import Module
from faebryk.core.util import (
as_unit,
as_unit_with_tolerance,
enum_parameter_representation,
)
from faebryk.libs.library import L
from faebryk.libs.units import Quantity

Expand Down Expand Up @@ -43,6 +38,12 @@ def can_bridge(self):

@L.rt_field
def simple_value_representation(self):
from faebryk.core.util import (
as_unit,
as_unit_with_tolerance,
enum_parameter_representation,
)

return F.has_simple_value_representation_based_on_params(
(
self.capacitance,
Expand Down
3 changes: 2 additions & 1 deletion src/faebryk/library/Comparator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import faebryk.library._F as F
from faebryk.core.module import Module
from faebryk.core.util import as_unit
from faebryk.libs.library import L
from faebryk.libs.units import Quantity

Expand All @@ -30,6 +29,8 @@ class OutputType(Enum):

@L.rt_field
def simple_value_representation(self):
from faebryk.core.util import as_unit

return F.has_simple_value_representation_based_on_params(
[
self.common_mode_rejection_ratio,
Expand Down
Loading

0 comments on commit c66b86c

Please sign in to comment.