Geometry toolbox#

Start with a primitive when it fits. For everything else, Magnelio offers curves, profiles, owned faces and CAD operations. This visual tour builds useful shapes with short recipes. The geometry methods guide explains their full contracts and limits.

All dimensions are in metres. No field simulation runs on this page.

import math
from pathlib import Path
from tempfile import TemporaryDirectory

import matplotlib.pyplot as plt
import numpy as np

from magnelio import GeometryModel, geo, monitors, plots, ports
from magnelio.io import export_step, import_step

Draw a profile and give it depth#

A Profile is a bounded sheet. Inner wires are real holes, so a sweep or extrusion carries the bore without a Boolean cut.

ring = geo.Profile.from_wires(
    geo.Curve.circle((0, 0, 0), 2e-3),
    holes=[geo.Curve.circle((0, 0, 0), 1e-3)],
    material="pec",
)
tube = ring.extruded((0, 0, 6e-3))
spine = geo.Curve.arc((8e-3, 0, 0), (0, 8e-3, 0), (-8e-3, 0, 0))
elbow = ring.swept(spine)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section([tube], "z", 3e-3, ax=axes[0], title="Extruded bore")
plots.plot_cross_section([elbow], "z", 0, ax=axes[1], title="Swept bore")
for axis, color in zip(axes, ("#3289a8", "#cf7554")):
    for shape in axis.patches:
        shape.set_facecolor(color)
fig.tight_layout()
Extruded bore, Swept bore

Sketch a custom outline or a routed track#

Path connects lines and arcs into a closed outline; ellipse is an exact curve. For a conductor centreline, traced adds width and thickness.

outline = (
    geo.Path((0, 0, 0))
    .line_to((4e-3, 0, 0))
    .arc_to((4e-3, 4e-3, 0), via=(6e-3, 2e-3, 0))
    .line_to((0, 4e-3, 0))
    .closed()
)
pad = geo.Profile.from_wires(outline).thickened(35e-6, material="pec")
ellipse = geo.Curve.ellipse((10e-3, 2e-3, 0), (2e-3, 1e-3), major_axis="x")
elliptical_pad = geo.Profile.from_wires(ellipse).thickened(35e-6, material="pec")
centreline = geo.Path((0, 0, 0)).line_to((5e-3, 0, 0)).spline_to((8e-3, 2e-3, 0)).curve()
track = centreline.traced(width=0.5e-3, thickness=35e-6, caps="flat", normal="z", material="pec")
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section(
    [pad, elliptical_pad], "z", 20e-6, ax=axes[0], title="Custom and exact ellipse pads"
)
plots.plot_cross_section([track], "z", 20e-6, ax=axes[1], title="Routed, flat-ended track")
fig.tight_layout()
Custom and exact ellipse pads, Routed, flat-ended track

Place curves, profiles and solids together#

Named transforms and reusable affine values act on every category. The rightmost transform acts first; Groups retain members and materials.

placement = geo.Translation((6e-3, 0, 0)) @ geo.Rotation("z", 30)
placed_ring, placed_tube = placement @ ring, placement @ tube
component = geo.Group(tube, spine, name="tube and route")
copies = [geo.Translation((18e-3 * i, 0, 0)) @ component for i in range(2)]
fig, ax = plots.plot_cross_section(
    [placed_tube, *(next(copy.members()) for copy in copies)],
    "z",
    3e-3,
    title="One component, several placements",
)
One component, several placements

Name a face before moving its owner#

A FaceRef belongs to its solid. Name the annular end, rotate the solid, then retrieve the same physical face in its new position.

shield = geo.Cylinder(axis="x", radius=2e-3, inner_radius=1e-3, height=6e-3, material="pec")
shield = shield.tagged_face("port", near=(6e-3, 1.5e-3, 0), normal="x")
shield = shield.rotated("z", 22.5)
end = shield.face("port")
assert len(end.edges) == 2
route = (
    geo.Path.from_face(end, up="z")
    .turn_right(radius=8e-3, angle_deg=22.5)
    .straight_to_plane(normal="x", position=20e-3)
)
extension = end.swept(route.curve())
# Volume measures the curved, hollow CAD solid in cubic metres. Its
# internal measurement scale is automatic; compare with area times length.
assert math.isclose(extension.volume(), end.area * route.curve().length, rel_tol=1e-9)
fig, ax = plots.plot_cross_section(
    [shield, extension], "z", 0, title="Named face swept to a domain plane"
)
ax.axvline(20, color="0.5", linestyle="--")

# A deliberate face set can keep both successors of a split.
cap = geo.Brick(size=(4e-3, 4e-3, 2e-3), material="pec").tagged_faces("cap", normal="z")
slot = geo.Brick(origin=(1.8e-3, -1e-3, -1e-3), size=(0.4e-3, 6e-3, 4e-3))
assert len((cap - slot).faces("cap")) == 2
Named face swept to a domain plane

Copy a component with its named contact#

Each placed copy owns its own face. A reusable placement can move an entire mixed component without replacing the face name.

shell = geo.Brick(size=(2e-3, 1e-3, 1e-3), material="pec").tagged_face("contact", normal="z")
datum = geo.Curve.line((0, 0, 0), (2e-3, 0, 0))
named_component = geo.Group(shell, datum)
placed_copies = [geo.Translation((5e-3 * i, 0, 0)) @ named_component for i in range(3)]
contacts = [next(copy.members()).face("contact") for copy in placed_copies]
assert len({id(contact.owner) for contact in contacts}) == 3
fig, ax = plots.plot_cross_section(
    [next(copy.members()) for copy in placed_copies],
    "z",
    0.5e-3,
    title="Three copies, three owned contacts",
)
Three copies, three owned contacts

Shape solids from existing faces#

Owned faces select shell openings and loft ends. Annular faces give a transition its bore automatically.

block = geo.Brick(size=(10e-3, 8e-3, 6e-3), material="pec")
housing = block.shelled(0.5e-3, openings=block.face(normal="z"))
inlet = geo.Cylinder(radius=2e-3, inner_radius=1e-3, height=2e-3, material="pec")
outlet = geo.Cylinder(
    origin=(0, 0, 8e-3), radius=3e-3, inner_radius=1.5e-3, height=2e-3, material="pec"
)
taper = inlet.face(normal="z").lofted(outlet.face(normal=(0, 0, -1)), blend="ruled")
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section([housing], "z", 3e-3, ax=axes[0], title="Open housing")
plots.plot_cross_section([inlet, taper, outlet], "y", 0, ax=axes[1], title="Hollow face loft")
fig.tight_layout()
Open housing, Hollow face loft

Revolve a profile or round selected edges#

Revolution suits a rotational part with a changing outline. Fillets and chamfers can take edges from a selected face on an existing solid.

pin_outline = geo.Profile.from_wires(
    geo.Path((0, 0, 0))
    .line_to((3e-3, 0, 0))
    .line_to((3e-3, 0, 8e-3))
    .arc_to((0, 0, 11e-3), via=(2.1e-3, 0, 10.1e-3))
    .closed()
)
pin = pin_outline.revolved(axis="z", material="pec")
top = block.face(normal="z")
rounded = block.filleted(edges=top.edges, radius=0.2e-3)
bevelled = block.chamfered(faces=top, distance=0.2e-3)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section([pin], "y", 0, ax=axes[0], title="Revolved pin")
plots.plot_cross_section(
    [rounded, bevelled.translated((12e-3, 0, 0))], "y", 4e-3, ax=axes[1], title="Round or bevel"
)
fig.tight_layout()
Revolved pin, Round or bevel

Choose how a section follows a bend#

The default keeps a swept section perpendicular to the route. A fixed frame keeps its apertures parallel in world space instead.

radius, angle = 8e-3, math.pi / 4
aperture = geo.Profile.rectangle(
    (radius, 0, 0), (1e-3, 0.3e-3), normal="y", x_direction="x", material="air"
)
bend_path = geo.Curve.arc(
    (radius, 0, 0),
    (radius * math.cos(angle / 2), radius * math.sin(angle / 2), 0),
    (radius * math.cos(angle), radius * math.sin(angle), 0),
)
perpendicular = aperture.swept(bend_path)
parallel = aperture.swept(bend_path, frame="fixed")
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section([perpendicular], "z", 0, ax=axes[0], title="Perpendicular")
plots.plot_cross_section([parallel], "z", 0, ax=axes[1], title="Parallel apertures")
fig.tight_layout()
Perpendicular, Parallel apertures

Twist or draft a sweep#

Twist is total roll. Positive draft grows the outside of a profile and shrinks its holes by a normal offset.

straight = geo.Curve.line((0, 0, 0), (0, 0, 4e-3))
rectangle = geo.Profile.rectangle((0, 0, 0), (2e-3, 1e-3), material="air")
twisted = rectangle.swept(straight, twist_deg=90)
drafted = ring.swept(straight, draft_deg=1)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section([twisted], "z", 2e-3, ax=axes[0], title="Halfway through a twist")
plots.plot_cross_section([drafted], "y", 0, ax=axes[1], title="Drafted annular walls")
fig.tight_layout()
Halfway through a twist, Drafted annular walls

Partition a body and keep its filled section#

Partition returns independent solids. Section returns curves; filled=True returns a Profile, including its hole.

section_body = geo.Cylinder(radius=2e-3, inner_radius=1e-3, height=6e-3, material="pec")
halves = section_body.partition(normal="z", position=3e-3)
loops = section_body.section(normal="z", position=3e-3)
(cut_profile,) = section_body.section(normal="z", position=3e-3, filled=True)
assert len(halves) == 2 and len(loops) == 2 and len(cut_profile.boundary()) == 2
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section(halves, "y", 0, ax=axes[0], title="Two independent halves")
plots.plot_cross_section([section_body], "z", 3e-3, ax=axes[1], title="Filled section with a hole")
fig.tight_layout()
Two independent halves, Filled section with a hole

Imprint a contact and insert a material#

Imprint splits a receiver face without removing volume. Insert assigns overlap to the body with the higher explicit priority.

host = geo.Brick(size=(2e-3,) * 3, material="pec")
tool = geo.Brick(origin=(1.8e-3, 0.5e-3, 0.5e-3), size=(0.4e-3, 1e-3, 1e-3))
marked = host.imprinted(tool).tagged_face("contact", near=(2e-3, 1e-3, 1e-3), normal="x")
dielectric = geo.Brick(origin=(0.5e-3,) * 3, size=(1e-3,) * 3, material="air")
assembly = geo.insert(marked, dielectric, priorities=(0, 1))
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
plots.plot_cross_section(
    [marked.face("contact").detached()], "x", 2e-3, ax=axes[0], title="Imprinted contact"
)
plots.plot_cross_section(
    list(assembly.members()), "z", 1e-3, ax=axes[1], title="Inserted dielectric"
)
fig.tight_layout()
Imprinted contact, Inserted dielectric

Project a trace onto a curved wall#

Directional rays meet the actual bounded face. The resulting curve is independent and can be used in a thin-wire declaration.

round_host = geo.Cylinder(radius=5e-3, height=10e-3, material="pec")
wall = round_host.face(near=(5e-3, 0, 5e-3))
sketch = geo.Curve.line((8e-3, -2e-3, 5e-3), (8e-3, 2e-3, 5e-3))
(trace,) = sketch.projected_onto(wall, direction=(-1, 0, 0))
wire = geo.ThinWire(trace, radius=20e-6)
assert wire.curve is trace
y = np.linspace(-2e-3, 2e-3, 200)
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(np.full_like(y, 8), y * 1e3, "--", label="sketch")
ax.plot(np.sqrt((5e-3) ** 2 - y**2) * 1e3, y * 1e3, label="projected trace")
ax.set(xlabel="x (mm)", ylabel="y (mm)", title="Trace on a cylindrical wall")
ax.set_aspect("equal")
ax.legend()
Trace on a cylindrical wall
<matplotlib.legend.Legend object at 0x7fcdb02bc4d0>

Add clearance or move a curved sheet#

Profile offset expands the material region, including into the hole. Detach an owned face before using the independent Sheet offset.

(clearance,) = ring.offset(0.1e-3)
(outer_wall,) = wall.detached().offset(0.2e-3)
feed = geo.Curve.line((0, 0, 0), (3e-3, 0, 0))
(feed_clearance,) = feed.offset(0.1e-3, normal="z")
assert clearance.area > ring.area
assert math.isclose(feed_clearance.length, feed.length)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
theta = np.linspace(0, 2 * math.pi, 256)
for axis, radii, title in (
    (axes[0], (1, 0.9, 2, 2.1), "Profile clearance"),
    (axes[1], (5, 5.2), "Sheet offset"),
):
    for radius_mm in radii:
        axis.plot(
            radius_mm * np.cos(theta),
            radius_mm * np.sin(theta),
            color="#cf7554" if radius_mm in (0.9, 2.1, 5.2) else "#3289a8",
        )
    axis.set(xlabel="x (mm)", ylabel="y (mm)", title=title)
    axis.set_aspect("equal")
fig.tight_layout()
Profile clearance, Sheet offset

Bend an existing layered component#

One neutral surface bends both layers, including their straight ends.

bend_radius = 10e-3
bend_length = bend_radius * math.pi / 2
neutral = geo.Surface.parametric(
    lambda u, v: (
        bend_radius * np.sin(u / bend_radius),
        v,
        bend_radius * (1 - np.cos(u / bend_radius)),
    ),
    u=(0, bend_length),
    v=(-1e-3, 1e-3),
    samples=(65, 9),
)
bend = geo.Bend(
    neutral,
    origin=(0, 0, 0),
    along="x",
    across="y",
    u=(0, bend_length),
    v=(-1e-3, 1e-3),
    max_strain=0.01,
)
layers = geo.Group(
    geo.Brick(
        origin=(-3e-3, -1e-3, -0.2e-3), size=(bend_length + 6e-3, 2e-3, 0.2e-3), material="pec"
    ),
    geo.Brick(origin=(-3e-3, -1e-3, 0), size=(bend_length + 6e-3, 2e-3, 0.2e-3), material="air"),
)
curved_layers = bend @ layers
phi = np.linspace(0, math.pi / 2, 200)
fig, ax = plt.subplots(figsize=(6, 4))
for depth, label in ((-0.2e-3, "outer layer"), (0, "neutral surface"), (0.2e-3, "inner layer")):
    r = bend_radius - depth
    ax.plot(r * np.sin(phi) * 1e3, (bend_radius - r * np.cos(phi)) * 1e3, label=label)
ax.set(xlabel="x (mm)", ylabel="z (mm)", title="Two layers, one neutral surface")
ax.set_aspect("equal")
ax.legend()
Two layers, one neutral surface
<matplotlib.legend.Legend object at 0x7fcdaec47950>

Wrap layers onto a curved patch#

Wrap uses one chart for substrate and conductor; max_strain bounds distortion on a surface that need not be developable.

def patch(u, v):
    return (u, v, 0.25e-3 * np.sin(np.pi * u / 20e-3) * np.cos(np.pi * v / 10e-3))


target = geo.Surface.parametric(patch, u=(0, 20e-3), v=(-5e-3, 5e-3), samples=(41, 21))
wrap = geo.Wrap(
    target,
    origin=(0, 0, 0),
    along="x",
    across="y",
    u=(0, 20e-3),
    v=(-5e-3, 5e-3),
    max_strain=0.05,
    tolerance=2e-6,
)
board = geo.Brick(origin=(1e-3, -4e-3, -0.3e-3), size=(18e-3, 8e-3, 0.3e-3), material="air")
conductor = geo.Brick(origin=(2e-3, -0.5e-3, 0), size=(16e-3, 1e-3, 0.035e-3), material="pec")
wrapped = wrap @ geo.Group(board, conductor)
u, v = np.meshgrid(np.linspace(0, 20e-3, 40), np.linspace(-5e-3, 5e-3, 20))
fig = plt.figure(figsize=(7, 4))
ax = fig.add_subplot(projection="3d")
ax.plot_surface(u * 1e3, v * 1e3, patch(u, v)[2] * 1e3, alpha=0.5)
ax.set(xlabel="x (mm)", ylabel="y (mm)", zlabel="z (mm)")
plot 14 profile geometry
[Text(-0.04405491569116248, -0.09538169037532089, 'x (mm)'), Text(0.07423207296593679, -0.07710300837914658, 'y (mm)'), Text(0.11344351648940883, 0.015198549314941825, 'z (mm)')]

Make a tangent transition between solids#

A face-to-face loft with blend=”tangent” meets the adjacent walls without a sharp corner at either end.

small = geo.Brick(origin=(-2e-3, -1e-3, 0), size=(4e-3, 2e-3, 1e-3), material="pec")
large = geo.Brick(origin=(-3e-3, -1.5e-3, 5e-3), size=(6e-3, 3e-3, 1e-3), material="pec")
smooth = small.face(normal="z").lofted(large.face(normal=(0, 0, -1)), blend="tangent")
fig, ax = plots.plot_cross_section([small, smooth, large], "y", 0, title="Tangent transition")
Tangent transition

Use a named face for a port and a recording plane#

Eligible rectangular faces specify EM consumers directly. Port and field monitor now share the selected plane and window.

source = geo.Brick(size=(2e-3, 3e-3, 4e-3), material="air").tagged_face("output", normal="z")
placed = geo.Translation((5e-3, 0, 0)) @ source
model = GeometryModel(background="pec").add(placed)
face = placed.face("output")
port = ports.PortWaveguide.from_face(face, model=model, name="output")
recording = monitors.MonitorFieldFrequency.from_face(
    face, frequencies=[10e9], fields=["Ex", "Ey"], name="output_fields"
)
assert port.corners == recording.corners
fig, ax = plt.subplots(figsize=(5, 4))
ax.fill([5, 7, 7, 5], [0, 0, 4, 4], color="#b9dce9")
ax.plot([5, 7], [4, 4], color="#cf7554", linewidth=4)
ax.text(6, 2, "air region", ha="center")
ax.annotate(
    "port + monitor",
    xy=(6, 4),
    xytext=(6, 4.5),
    ha="center",
    arrowprops={"arrowstyle": "->", "color": "#cf7554"},
)
ax.set(xlabel="x (mm)", ylabel="z (mm)", title="Two consumers, one selected face")
ax.set_aspect("equal")
ax.set_ylim(-0.2, 5)
Two consumers, one selected face
(-0.2, 5.0)

Exchange solids and sheets with CAD#

STEP keeps units and body names. Imported sheets need physical thickness before they become meshable material volumes.

cad_housing = geo.Brick(size=(20e-3, 10e-3, 3e-3), material="pec", name="housing")
cad_trace = geo.Profile.rectangle((10e-3, 5e-3, 3e-3), (8e-3, 1e-3), material="pec", name="trace")
with TemporaryDirectory() as directory:
    path = Path(directory) / "assembly.step"
    export_step(path, geo.Group(cad_housing, cad_trace), unit="mm")
    imported = import_step(path, {"housing": "pec", "trace": "pec"})
    by_name = {body.name: body for body in imported.members()}
    copper = by_name["trace"].thickened(35e-6)
    assert isinstance(by_name["trace"], geo.ImportedSheet)
    export_step(
        Path(directory) / "selected.step", (by_name["housing"], by_name["trace"]), unit="mm"
    )
    fig, ax = plots.plot_cross_section(
        [by_name["housing"], copper],
        "z",
        3e-3,
        title="Imported sheet given physical thickness",
    )
    for shape, color in zip(ax.patches, ("#b9dce9", "#cf7554")):
        shape.set_facecolor(color)
Imported sheet given physical thickness

Total running time of the script: (0 minutes 1.856 seconds)

Gallery generated by Sphinx-Gallery