fieldsmith 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. fieldsmith/__init__.py +10 -0
  2. fieldsmith/cad/__init__.py +0 -0
  3. fieldsmith/cad/lids.py +156 -0
  4. fieldsmith/cad/plates.py +111 -0
  5. fieldsmith/cad/rails.py +263 -0
  6. fieldsmith/cad/slabs.py +273 -0
  7. fieldsmith/callbacks.py +140 -0
  8. fieldsmith/configurations/__init__.py +8 -0
  9. fieldsmith/configurations/dome_config.py +107 -0
  10. fieldsmith/configurations/halbach_system_config.py +86 -0
  11. fieldsmith/configurations/magnet_configuration.py +145 -0
  12. fieldsmith/configurations/setup_npy.py +94 -0
  13. fieldsmith/evaluation/__init__.py +17 -0
  14. fieldsmith/evaluation/core.py +223 -0
  15. fieldsmith/evaluation/monte_carlo.py +269 -0
  16. fieldsmith/field_simulations/__init__.py +11 -0
  17. fieldsmith/field_simulations/cuboid.py +152 -0
  18. fieldsmith/field_simulations/demagnetization.py +145 -0
  19. fieldsmith/field_simulations/dipole.py +131 -0
  20. fieldsmith/field_simulations/rectangular_prism.py +275 -0
  21. fieldsmith/geometry/__init__.py +18 -0
  22. fieldsmith/geometry/cap_lattice.py +123 -0
  23. fieldsmith/geometry/collision.py +196 -0
  24. fieldsmith/geometry/cube_axes.py +132 -0
  25. fieldsmith/geometry/dome.py +100 -0
  26. fieldsmith/geometry/halbach_ring.py +122 -0
  27. fieldsmith/geometry/halbach_system.py +181 -0
  28. fieldsmith/geometry/lsq_seed.py +208 -0
  29. fieldsmith/geometry/roi.py +109 -0
  30. fieldsmith/geometry/roma.py +148 -0
  31. fieldsmith/logger.py +99 -0
  32. fieldsmith/magnet_geometry_verifier.py +397 -0
  33. fieldsmith/metrics.py +73 -0
  34. fieldsmith/models/__init__.py +17 -0
  35. fieldsmith/models/dome/__init__.py +6 -0
  36. fieldsmith/models/dome/model.py +202 -0
  37. fieldsmith/models/dome/position_model.py +109 -0
  38. fieldsmith/models/halbach_ring/__init__.py +5 -0
  39. fieldsmith/models/halbach_ring/model.py +181 -0
  40. fieldsmith/models/halbach_systems/__init__.py +5 -0
  41. fieldsmith/models/halbach_systems/model.py +143 -0
  42. fieldsmith/models/small_halbach.py +393 -0
  43. fieldsmith/objectives.py +175 -0
  44. fieldsmith/point_sampler.py +131 -0
  45. fieldsmith/train_loop.py +104 -0
  46. fieldsmith/visualizations/__init__.py +17 -0
  47. fieldsmith/visualizations/matplotlib_2d.py +316 -0
  48. fieldsmith/visualizations/plotly_3d.py +568 -0
  49. fieldsmith/visualizations/system_3d.py +250 -0
  50. fieldsmith-0.1.4.dist-info/METADATA +107 -0
  51. fieldsmith-0.1.4.dist-info/RECORD +54 -0
  52. fieldsmith-0.1.4.dist-info/WHEEL +5 -0
  53. fieldsmith-0.1.4.dist-info/licenses/LICENSE +83 -0
  54. fieldsmith-0.1.4.dist-info/top_level.txt +1 -0
fieldsmith/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ # Copyright (c) Fraunhofer MEVIS, Germany. All rights reserved.
2
+ # -----------------------------------------------------------------------------
3
+ # This file initializes the FieldSmith magnet optimization package.
4
+ #
5
+ # __init__.py
6
+ # Kostiantyn Lavronenko
7
+ # 22.06.2026
8
+ # -----------------------------------------------------------------------------
9
+
10
+ """FieldSmith magnet optimization utilities."""
File without changes
fieldsmith/cad/lids.py ADDED
@@ -0,0 +1,156 @@
1
+ # Copyright (c) Fraunhofer MEVIS, Germany. All rights reserved.
2
+ # -----------------------------------------------------------------------------
3
+ # This file builds the lid that closes a plate: a plate-shaped cover carrying
4
+ # one pin per magnet, each cut to sit flat on its own tilted magnet.
5
+ #
6
+ # lids.py
7
+ # Marian Frei
8
+ # 31.07.2026
9
+ # -----------------------------------------------------------------------------
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import shapely
18
+ import torch
19
+ import trimesh
20
+
21
+ from fieldsmith.configurations import MagnetConfiguration
22
+ from fieldsmith.geometry.cube_axes import cube_axes_min_z_extent
23
+ from fieldsmith.cad.plates import assign_planes
24
+
25
+ # Grown outward so the lid overlaps the plate wall rather than balancing on it.
26
+ OUTLINE_GROW_M = 1.0e-3
27
+ # Anything larger than this in the section is the patient bore, not a pocket.
28
+ BORE_MIN_AREA_M2 = 3.0e-3
29
+ # Collapses near-coincident vertices left by sectioning, far below print resolution.
30
+ SIMPLIFY_M = 1.0e-5
31
+ PIN_RADIUS_M = 2.5e-3
32
+ # The pin reaches this far into the magnet face, which preloads the magnet.
33
+ PIN_INTERFERENCE_M = 2.0e-4
34
+ # How far below the magnet face the pin blank starts before it is cut back.
35
+ PIN_BLANK_DROP_M = 4.0e-3
36
+ # Below this the magnet leans too far for a pin to press on its face squarely.
37
+ UPRIGHT_MIN = 0.3
38
+
39
+
40
+ def _outline_at(mesh: trimesh.Trimesh, height: float) -> shapely.Polygon | None:
41
+ """
42
+ Return the plate outline at magnet height with the pockets filled in.
43
+
44
+ Sectioning at magnet level rather than at the lid plane keeps the outermost
45
+ pins over material, since the plates taper upward. Only the bore is left
46
+ open. Returns None if the plate does not reach that height.
47
+ """
48
+ section = mesh.section(plane_normal=[0.0, 0.0, 1.0], plane_origin=[0.0, 0.0, height])
49
+ if section is None:
50
+ return None
51
+ planar, _ = section.to_2D(to_2D=np.eye(4))
52
+ polygons = [polygon for polygon in planar.polygons_full if polygon.area > 0]
53
+ if not polygons:
54
+ return None
55
+ largest = max(polygons, key=lambda polygon: polygon.area)
56
+ outline = shapely.Polygon(largest.exterior).buffer(OUTLINE_GROW_M)
57
+ for interior in largest.interiors:
58
+ hole = shapely.Polygon(interior)
59
+ if hole.area > BORE_MIN_AREA_M2:
60
+ outline = outline.difference(hole)
61
+ if outline.is_empty:
62
+ return None
63
+ # Without this the triangulation yields slivers and every later boolean fails.
64
+ return outline.simplify(SIMPLIFY_M).buffer(0)
65
+
66
+
67
+ def _pin(centre: np.ndarray, axes: np.ndarray, size: float, lid_bottom: float) -> trimesh.Trimesh | None:
68
+ """
69
+ Return the pin that presses one magnet down, cut to its top face.
70
+
71
+ Returns None when the magnet leans too far to be pressed squarely or
72
+ already reaches the lid.
73
+ """
74
+ normals = np.concatenate([axes, -axes])
75
+ normal = normals[int(np.argmax(normals[:, 2]))]
76
+ if normal[2] < UPRIGHT_MIN:
77
+ return None
78
+ face_centre = centre + normal * (size / 2)
79
+ # Height at which a vertical line through the magnet leaves its top face.
80
+ exit_height = centre[2] + (size / 2) / normal[2]
81
+ if exit_height - PIN_INTERFERENCE_M >= lid_bottom - 1.0e-4:
82
+ return None # the magnet is already there
83
+ blank = trimesh.creation.cylinder(
84
+ radius=PIN_RADIUS_M, height=lid_bottom - (exit_height - PIN_BLANK_DROP_M), sections=24)
85
+ blank.apply_translation((centre[0], centre[1],
86
+ (exit_height - PIN_BLANK_DROP_M + lid_bottom) / 2))
87
+ cut = trimesh.intersections.slice_mesh_plane(
88
+ blank, plane_normal=normal,
89
+ plane_origin=face_centre - normal * PIN_INTERFERENCE_M, cap=True)
90
+ return cut if len(cut.faces) else None
91
+
92
+
93
+ def export_lids(configuration: MagnetConfiguration, slab_dir: Path, variant: str = "default") -> dict:
94
+ """
95
+ Write one lid per plate, built against the untrimmed plates in slab_dir.
96
+
97
+ Each lid drops into its plate's recess, finishes flush and presses every
98
+ magnet down through a pin. Writes the lid STLs and their manifest.
99
+ """
100
+ manifest = json.loads((slab_dir / "manifest.json").read_text())
101
+ size = float(configuration.metadata.get("magnet_size_m") or 0.012)
102
+ positions = configuration.positions.double()
103
+ orientations = configuration.orientations.double()
104
+ labels, _ = assign_planes(positions)
105
+ axes = cube_axes_min_z_extent(orientations).numpy()
106
+ centres = positions.numpy()
107
+
108
+ lid_dir = slab_dir / "lids"
109
+ lid_dir.mkdir(parents=True, exist_ok=True)
110
+ entries = []
111
+ for plate in manifest["slabs"]:
112
+ index = plate["layer"]
113
+ raw = trimesh.load(slab_dir / plate["raw_file"])
114
+ raw.apply_scale(1e-3) # back to meters to work in
115
+ lid_bottom = plate["lid_bot_mm"] * 1e-3
116
+ outline = _outline_at(raw, plate["z_center_mm"] * 1e-3)
117
+ if outline is None:
118
+ continue
119
+ body = trimesh.creation.extrude_polygon(outline, height=plate["z_max_mm"] * 1e-3 - lid_bottom)
120
+ body.apply_translation((0.0, 0.0, lid_bottom))
121
+
122
+ here = torch.nonzero(labels == index, as_tuple=True)[0].numpy()
123
+ pins = [pin for pin in (_pin(centres[i], axes[i], size, lid_bottom) for i in here)
124
+ if pin is not None]
125
+ if pins:
126
+ merged = None
127
+ try:
128
+ merged = trimesh.boolean.union([body, *pins])
129
+ except Exception:
130
+ merged = None
131
+ # A failed union may return the bare cover without raising. The pins
132
+ # reach below the lid, so a body that does not was missing them.
133
+ if merged is None or merged.bounds[0][2] > lid_bottom - 1.0e-4:
134
+ merged = body
135
+ for pin in pins:
136
+ try:
137
+ merged = trimesh.boolean.union([merged, pin])
138
+ except Exception:
139
+ continue
140
+ body = merged
141
+
142
+ body.apply_scale(1e3)
143
+ name = f"lid_layer_{index}.stl"
144
+ body.export(lid_dir / name)
145
+ written = trimesh.load(lid_dir / name)
146
+ entries.append({
147
+ "file": name, "layer": index, "n_pins": len(pins), "n_magnets": plate["n_magnets"],
148
+ "z_center_mm": plate["z_center_mm"], "lid_bot_mm": plate["lid_bot_mm"],
149
+ "volume_cm3": float(written.volume) / 1e3,
150
+ "watertight": bool(written.is_watertight),
151
+ "broken_faces": int(len(trimesh.repair.broken_faces(written))),
152
+ })
153
+
154
+ lid_manifest = {"variant": variant, "lid_gap_mm": manifest["lid_gap_mm"], "lids": entries}
155
+ (lid_dir / "manifest.json").write_text(json.dumps(lid_manifest, indent=2))
156
+ return lid_manifest
@@ -0,0 +1,111 @@
1
+ # Copyright (c) Fraunhofer MEVIS, Germany. All rights reserved.
2
+ # -----------------------------------------------------------------------------
3
+ # This file contains the discrete-shell plate geometry: which magnets share a
4
+ # level, how tall each one stands, and whether a stack leaves room to build.
5
+ #
6
+ # plates.py
7
+ # Marian Frei
8
+ # 31.07.2026
9
+ # -----------------------------------------------------------------------------
10
+
11
+ from __future__ import annotations
12
+
13
+ import torch
14
+
15
+ SQRT3 = 3.0 ** 0.5
16
+
17
+
18
+ def assign_planes(positions: torch.Tensor, tolerance: float = 1e-3) -> tuple[torch.Tensor, torch.Tensor]:
19
+ """
20
+ Group magnets into the z levels a design actually occupies.
21
+
22
+ Args:
23
+ positions: Magnet centres in meters, shape (M, 3).
24
+ tolerance: Centres closer than this in z belong to the same level.
25
+
26
+ Returns:
27
+ Level index per magnet, shape (M,), and the level heights, shape (L,).
28
+ """
29
+ z = positions[:, 2]
30
+ order = torch.argsort(z)
31
+ levels = [z[order[0]]]
32
+ for index in order[1:]:
33
+ if float(z[index] - levels[-1]) > tolerance:
34
+ levels.append(z[index])
35
+ heights = torch.stack(levels)
36
+ return torch.argmin((z[:, None] - heights[None, :]).abs(), dim=1), heights
37
+
38
+
39
+ def z_extent(orientations: torch.Tensor, magnet_size: float) -> torch.Tensor:
40
+ """
41
+ Return how tall each cube stands in world z, in meters.
42
+
43
+ In the pocket frame the height is size * (|cos t| + |sin t|) for a tilt t
44
+ from vertical, which peaks at size * sqrt(2) at 45 degrees.
45
+
46
+ Args:
47
+ orientations: Magnetization directions, shape (M, 3); need not be normalized.
48
+ magnet_size: Cube edge length in meters.
49
+
50
+ Returns:
51
+ World-z height per magnet in meters, shape (M,).
52
+ """
53
+ cosine = (orientations[:, 2] / orientations.norm(dim=1).clamp_min(1e-12)).abs()
54
+ return magnet_size * (cosine + (1.0 - cosine * cosine).clamp_min(0.0).sqrt())
55
+
56
+
57
+ def plate_bounds(
58
+ positions: torch.Tensor,
59
+ orientations: torch.Tensor,
60
+ magnet_size: float,
61
+ roof: float,
62
+ floor: float,
63
+ slab_gap: float = 0.0,
64
+ max_floor: float = 6.0e-3,
65
+ ) -> list[dict[str, float]]:
66
+ """
67
+ Return the plate each level would be printed as, after clamping.
68
+
69
+ A plate reaches a roof above its tallest magnet and a floor below its
70
+ lowest. The roof is served first. Where levels are tight the floor is
71
+ clamped against the plate below and comes out thinner than asked.
72
+
73
+ Args:
74
+ positions: Magnet centres in meters, shape (M, 3).
75
+ orientations: Magnetization directions, shape (M, 3).
76
+ magnet_size: Cube edge length in meters.
77
+ roof: Desired material above a pocket, in meters.
78
+ floor: Desired material below a pocket, in meters.
79
+ slab_gap: Air left between neighbouring plates, in meters.
80
+
81
+ Returns:
82
+ One dict per level with its height, z bounds, radii, magnet count, the
83
+ roof and floor actually achieved, and any spacer still needed beneath
84
+ it, all in meters.
85
+ """
86
+ labels, heights = assign_planes(positions)
87
+ extent = z_extent(orientations, magnet_size)
88
+ z = positions[:, 2]
89
+ tops = torch.stack([(z + extent / 2)[labels == i].max() for i in range(len(heights))])
90
+ bottoms = torch.stack([(z - extent / 2)[labels == i].min() for i in range(len(heights))])
91
+ radius = positions[:, :2].norm(dim=1)
92
+ plates: list[dict[str, float]] = []
93
+ for level in range(len(heights)):
94
+ top = float(tops[level]) + roof
95
+ bottom = float(bottoms[level]) - floor
96
+ spacer = 0.0
97
+ if level > 0:
98
+ # Reach down to the plate below so the stack touches, up to
99
+ # max_floor. Any remaining gap is reported as a spacer.
100
+ reachable = plates[-1]["z_max"] + slab_gap
101
+ bottom = max(reachable, float(bottoms[level]) - max_floor)
102
+ spacer = bottom - reachable
103
+ here = labels == level
104
+ plates.append({
105
+ "height": float(heights[level]), "z_min": bottom, "z_max": top,
106
+ "r_min": float(radius[here].min()) - magnet_size * SQRT3 / 2,
107
+ "r_max": float(radius[here].max()) + magnet_size * SQRT3 / 2,
108
+ "count": int(here.sum()), "roof": top - float(tops[level]),
109
+ "floor": float(bottoms[level]) - bottom, "spacer_below": spacer,
110
+ })
111
+ return plates
@@ -0,0 +1,263 @@
1
+ # Copyright (c) Fraunhofer MEVIS, Germany. All rights reserved.
2
+ # -----------------------------------------------------------------------------
3
+ # This file adds inclined fastening rails to an exported shell set.
4
+ #
5
+ # rails.py
6
+ # Marian Frei
7
+ # 26.08.2026
8
+ # -----------------------------------------------------------------------------
9
+ """
10
+ Inclined fastening rails for exported plates.
11
+
12
+ At every interface brass DIN 84 M4 screws pass through the upper plate's
13
+ rail segment into brass nuts captured in side pockets of the segment below.
14
+ Each cut is moved along the rail until it breaches no magnet pocket.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import math
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+ import torch
25
+ import trimesh
26
+
27
+ from fieldsmith.configurations import MagnetConfiguration
28
+ from fieldsmith.cad.plates import assign_planes, plate_bounds
29
+
30
+ MU0 = 4e-7 * math.pi
31
+ SIZE = 0.012
32
+ RAIL_W_MM = 19.0
33
+ PAD_MM = 12.5 # the screw lane must clear the pocket zone
34
+ CBORE_R_MM = 3.9 # DIN 84 M4 head is 7.0 across
35
+ CBORE_DEPTH_MM = 6.0
36
+ SHAFT_R_MM = 2.2
37
+ OFFSET_MM = 4.7
38
+ CEIL_MM = 3.0 # solid material the nut bears up against
39
+ NUT_H_MM = 3.2 # DIN 934 M4
40
+ SLOT_W_MM = 7.4 # across flats 7.0 plus play, blocks rotation
41
+ SLOT_H_MM = 3.6
42
+ NUT_CORNER_MM = 4.05 # half of 8.1 across corners
43
+ RELIEF_R_MM = 2.4
44
+ STANDARD_LENGTHS_MM = (12.0, 16.0, 20.0, 25.0, 30.0, 35.0, 40.0)
45
+ TIP_PAST_NUT_MM = 1.0 # the tip must clear the nut at least this far
46
+ WORKING_LOAD_N = 150.0
47
+ ULTIMATE_LOAD_N = 450.0
48
+ NUT = "DIN 934 brass M4 nut"
49
+
50
+
51
+ def magnet_forces(configuration) -> torch.Tensor:
52
+ """Dipole force on every magnet from all others, Newtons, (M, 3)."""
53
+ br = configuration.remanence_vectors().double()
54
+ volumes = configuration.volumes.double()
55
+ moments = br * volumes[:, None] / MU0
56
+ sources = configuration.positions.double().detach()
57
+ eval_pos = configuration.positions.double().clone().requires_grad_(True)
58
+ diff = eval_pos[:, None, :] - sources[None, :, :]
59
+ dist = diff.norm(dim=-1)
60
+ eye = torch.eye(len(sources), dtype=torch.bool)
61
+ dist = dist.masked_fill(eye, 1.0)
62
+ unit = diff / dist[..., None]
63
+ mdotu = (moments[None, :, :] * unit).sum(-1)
64
+ field = (MU0 / (4 * math.pi)) * (3 * unit * mdotu[..., None]
65
+ - moments[None, :, :]) / dist[..., None] ** 3
66
+ field = field.masked_fill(eye[..., None], 0.0)
67
+ energy = (moments * field.sum(1)).sum()
68
+ (force,) = torch.autograd.grad(energy, eval_pos)
69
+ return force
70
+
71
+
72
+ def _rail_segment(angle, r_in, r_out_lo, r_out_hi, z_lo, z_hi):
73
+ w = RAIL_W_MM / 2
74
+ points = [(r_in, -w, z_lo), (r_in, w, z_lo), (r_in, -w, z_hi), (r_in, w, z_hi),
75
+ (r_out_lo, -w, z_lo), (r_out_lo, w, z_lo),
76
+ (r_out_hi, -w, z_hi), (r_out_hi, w, z_hi)]
77
+ solid = trimesh.convex.convex_hull(np.array(points))
78
+ solid.apply_transform(trimesh.transformations.rotation_matrix(angle, (0, 0, 1)))
79
+ return solid
80
+
81
+
82
+ def _cyl(x, y, z0, z1, r):
83
+ body = trimesh.creation.cylinder(radius=r, height=z1 - z0, sections=24)
84
+ body.apply_translation([x, y, (z0 + z1) / 2])
85
+ return body
86
+
87
+
88
+ def _slot(angle, off, r_inner, r_outer, z0, z1):
89
+ """The nut pocket: a radial slot entered from the rail's outer face."""
90
+ body = trimesh.creation.box((r_outer - r_inner, SLOT_W_MM, z1 - z0))
91
+ body.apply_translation((r_inner + (r_outer - r_inner) / 2, off, (z0 + z1) / 2))
92
+ body.apply_transform(trimesh.transformations.rotation_matrix(angle, (0, 0, 1)))
93
+ return body
94
+
95
+
96
+ def _cyl_points(x, y, z0, z1, r):
97
+ pts = []
98
+ for rho in (0.0, 0.55 * r, 0.92 * r):
99
+ for j in range(1 if rho == 0.0 else 8):
100
+ a = 2 * math.pi * j / 8
101
+ for z in np.linspace(z0 + 0.15, z1 - 0.15, 4):
102
+ pts.append((x + rho * math.cos(a), y + rho * math.sin(a), z))
103
+ return pts
104
+
105
+
106
+ def _slot_points(angle, off, r_inner, r_outer, z0, z1):
107
+ pts = []
108
+ rot = np.array([[math.cos(angle), -math.sin(angle)],
109
+ [math.sin(angle), math.cos(angle)]])
110
+ for r in np.linspace(r_inner + 0.2, r_outer - 0.2, 6):
111
+ for t in np.linspace(-SLOT_W_MM / 2 + 0.2, SLOT_W_MM / 2 - 0.2, 4):
112
+ for z in np.linspace(z0 + 0.15, z1 - 0.15, 3):
113
+ x, y = rot @ (r, t)
114
+ pts.append((x, y, z))
115
+ return pts
116
+
117
+
118
+ def _breaches(points, hull, mesh) -> bool:
119
+ """True when a probe point should be solid plate but is a pocket void."""
120
+ pts = np.asarray(points)
121
+ inside_outline = hull.contains(pts)
122
+ if not inside_outline.any():
123
+ return False
124
+ return bool((~mesh.contains(pts[inside_outline])).any())
125
+
126
+
127
+ def add_rails(design_path: Path, shell_dir: Path, n_rails: int = 6) -> dict:
128
+ """Add fastening rails to the exported set in shell_dir, in place."""
129
+ configuration = MagnetConfiguration.from_file(design_path, dtype=torch.float64)
130
+ configuration.metadata.setdefault("magnet_size_m", SIZE)
131
+ labels, _ = assign_planes(configuration.positions.double())
132
+ plates = plate_bounds(configuration.positions.double(),
133
+ configuration.orientations.double(), SIZE, 1.0e-3, 1.4e-3)
134
+ L = labels.numpy()
135
+ n_plates = len(plates)
136
+ z_lo = [p["z_min"] * 1e3 for p in plates]
137
+ z_hi = [p["z_max"] * 1e3 for p in plates]
138
+
139
+ force = magnet_forces(configuration).numpy()
140
+ lid_load = [float(np.clip(force[L == k, 2], 0, None).sum()) for k in range(n_plates)]
141
+ iface = [0.0] + [float(max(force[L > k, 2].sum(), -force[L <= k, 2].sum(), 0.0))
142
+ for k in range(n_plates - 1)]
143
+
144
+ manifest = json.loads((shell_dir / "manifest.json").read_text())
145
+ by_layer = {slab["layer"]: slab for slab in manifest["slabs"]}
146
+ meshes = {k: trimesh.load(shell_dir / by_layer[k]["file"]) for k in by_layer}
147
+ hulls = {k: meshes[k].convex_hull for k in by_layer}
148
+ wall = {k: float(np.linalg.norm(meshes[k].vertices[:, :2], axis=1).max())
149
+ for k in by_layer}
150
+
151
+ slope = (wall[0] - wall[n_plates - 1]) / max(z_hi[-1] - z_lo[0], 1e-9)
152
+ offset = max(wall[k] + PAD_MM + slope * z_hi[k] for k in by_layer)
153
+ rail_r = lambda z: offset - slope * z
154
+
155
+ # The shortest standard length whose tip clears every interface's nut.
156
+ need = max(z_hi[k] - z_lo[k] - CBORE_DEPTH_MM + CEIL_MM + NUT_H_MM + TIP_PAST_NUT_MM
157
+ for k in range(1, n_plates))
158
+ length = next((l for l in STANDARD_LENGTHS_MM if l >= need), STANDARD_LENGTHS_MM[-1])
159
+ screw = f"DIN 84 brass M4 x {length:.0f}"
160
+
161
+ angles = [2 * math.pi * j / n_rails for j in range(n_rails)]
162
+ adds: dict[int, list] = {k: [] for k in by_layer}
163
+ cuts: dict[int, list] = {k: [] for k in by_layer}
164
+ plan = {"design": design_path.name, "screw": screw, "nut": NUT,
165
+ "rails": n_rails,
166
+ "rail_profile": {"A_mm": round(offset, 1), "slope": round(slope, 4)},
167
+ "screw_length_mm": length,
168
+ "assembly": "slide a nut into each pocket, screw each shell down "
169
+ "empty onto the one below, then insert its magnets, "
170
+ "then its lid",
171
+ "interfaces": [], "warnings": []}
172
+ spots_view = {"design": design_path.name, "screw": screw, "nut": NUT,
173
+ "screw_length_mm": length, "cbore_mm": CBORE_DEPTH_MM,
174
+ "plates": []}
175
+
176
+ for k in by_layer:
177
+ for a in angles:
178
+ adds[k].append(_rail_segment(a, wall[k] - 4.0, rail_r(z_lo[k]),
179
+ rail_r(z_hi[k]), z_lo[k], z_hi[k]))
180
+
181
+ for k in range(1, n_plates):
182
+ r_base = rail_r(z_lo[k]) - 8.5
183
+ sign = 1 if k % 2 else -1
184
+ z_int = z_lo[k]
185
+ tip = length - (z_hi[k] - z_lo[k] - CBORE_DEPTH_MM) # depth below interface
186
+ slot_top = z_int - CEIL_MM
187
+ slot_bot = slot_top - SLOT_H_MM
188
+ relief_bot = z_int - tip - 1.5
189
+ screws = []
190
+ for a in angles:
191
+ taken: list[float] = []
192
+ for off0 in (sign * OFFSET_MM, -sign * OFFSET_MM):
193
+ placed = False
194
+ for d_off in (0.0, 1.5, -1.5, 3.0, -3.0):
195
+ off = off0 + d_off
196
+ if abs(off) > RAIL_W_MM / 2 - SLOT_W_MM / 2 - 1.0:
197
+ continue
198
+ if any(abs(off - t) < SLOT_W_MM + 1.2 for t in taken):
199
+ continue
200
+ for d_r in (0.0, 1.2, -1.2, 2.4, -2.4, 3.6):
201
+ r_s = r_base + d_r
202
+ x = r_s * math.cos(a) - off * math.sin(a)
203
+ y = r_s * math.sin(a) + off * math.cos(a)
204
+ outer = rail_r(slot_bot) + 2.0
205
+ probe_up = (_cyl_points(x, y, z_hi[k] - CBORE_DEPTH_MM,
206
+ z_hi[k], CBORE_R_MM)
207
+ + _cyl_points(x, y, z_lo[k], z_hi[k], SHAFT_R_MM))
208
+ probe_dn = (_cyl_points(x, y, slot_top, z_int, SHAFT_R_MM)
209
+ + _slot_points(a, off, r_s - NUT_CORNER_MM - 0.35,
210
+ outer - 2.5, slot_bot, slot_top)
211
+ + _cyl_points(x, y, relief_bot, slot_bot, RELIEF_R_MM))
212
+ if _breaches(probe_up, hulls[k], meshes[k]):
213
+ continue
214
+ if _breaches(probe_dn, hulls[k - 1], meshes[k - 1]):
215
+ continue
216
+ cuts[k].append(_cyl(x, y, z_hi[k] - CBORE_DEPTH_MM,
217
+ z_hi[k] + 0.4, CBORE_R_MM))
218
+ cuts[k].append(_cyl(x, y, z_lo[k] - 0.4, z_hi[k] + 0.4,
219
+ SHAFT_R_MM))
220
+ cuts[k - 1].append(_cyl(x, y, slot_top - 0.05, z_int + 0.4,
221
+ SHAFT_R_MM))
222
+ cuts[k - 1].append(_slot(a, off, r_s - NUT_CORNER_MM - 0.35,
223
+ outer, slot_bot, slot_top))
224
+ cuts[k - 1].append(_cyl(x, y, relief_bot, slot_bot + 0.1,
225
+ RELIEF_R_MM))
226
+ screws.append({"x_mm": round(x, 1), "y_mm": round(y, 1)})
227
+ taken.append(off)
228
+ placed = True
229
+ break
230
+ if placed:
231
+ break
232
+ if not placed:
233
+ plan["warnings"].append(
234
+ f"interface {k - 1}->{k}: no clean spot on the rail at "
235
+ f"{math.degrees(a):.0f} deg, screw dropped")
236
+ joint = iface[k] + lid_load[k - 1]
237
+ plan["interfaces"].append({
238
+ "interface": f"{k - 1}->{k}", "joint_load_n": round(joint, 1),
239
+ "screws": len(screws), "bolt_radius_mm": round(r_base, 1),
240
+ "nut_ceiling_mm": CEIL_MM,
241
+ "tip_past_nut_mm": round(tip - CEIL_MM - NUT_H_MM, 1),
242
+ "margin_working": round(len(screws) * WORKING_LOAD_N / max(joint, 1e-9), 2),
243
+ "margin_ultimate": round(len(screws) * ULTIMATE_LOAD_N / max(joint, 1e-9), 2)})
244
+ spots_view["plates"].append({
245
+ "plate": k, "z_min_mm": round(z_lo[k], 1), "z_max_mm": round(z_hi[k], 1),
246
+ "joint_load_n": round(joint, 1), "nut_top_mm": round(slot_top, 1),
247
+ "lid_screws": screws, "plate_screws": []})
248
+
249
+ for k in by_layer:
250
+ mesh = trimesh.boolean.union([meshes[k]] + adds[k], engine="manifold")
251
+ if cuts[k]:
252
+ mesh = trimesh.boolean.difference([mesh] + cuts[k], engine="manifold")
253
+ mesh.update_faces(mesh.nondegenerate_faces())
254
+ mesh.merge_vertices()
255
+ mesh.export(shell_dir / by_layer[k]["file"])
256
+
257
+ total = sum(entry["screws"] for entry in plan["interfaces"])
258
+ plan["parts"] = {screw: total, NUT: total}
259
+ if not plan["warnings"]:
260
+ del plan["warnings"]
261
+ (shell_dir / "fastener_plan.json").write_text(json.dumps(plan, indent=1))
262
+ (shell_dir / "screw_spots.json").write_text(json.dumps(spots_view, indent=1))
263
+ return plan