Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice
TypeScript 3d-modeling3d-printing3d-printing-toolsagentagentic-aiai-cadcadcadqueryclaude-codecodexelectronfemllmmacdmakeropencodeparametric-designpythonsteptext-to-cad
soma auf Englisch: Ausgaben, Fehlermeldungen und Docstrings der API (E73)
Kai-Jungsthoefelf73fca99f88c
diff --git a/python/pyproject.toml b/python/pyproject.tomlindex 1f3263d..7b7263b 100644--- a/python/pyproject.toml+++ b/python/pyproject.toml@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"name = "soma"# Versionsnummer von SOMA (E68), eine fuer App und soma: steht in soma/__init__.py und gleichlautend in app/package.jsondynamic = ["version"]-description = "Hilfsbibliothek und Kommandozeile von SOMA"+description = "Helper library and command line of SOMA"# Lizenz von SOMA (E71), Text in LICENSE im Hauptordner des Reposlicense = "GPL-3.0-or-later"requires-python = ">=3.11"diff --git a/python/soma/__init__.py b/python/soma/__init__.pyindex 3b831d1..db2d773 100644--- a/python/soma/__init__.py+++ b/python/soma/__init__.py@@ -1,6 +1,6 @@-"""soma: Hilfsbibliothek von SOMA. Aus model.py: `from soma import add_part, import_step`.-Normteile (Schrauben, Muttern, Scheiben, Gewindeeinsaetze): `from soma.fasteners import Screw, Nut, Washer, HeatSetInsert`.-Animationen in animations/*.py: `from soma.anim import Animation`."""+"""soma: helper library of SOMA. In model.py: `from soma import add_part, import_step, import_assembly`.+Standard parts (screws, nuts, washers, heat-set inserts): `from soma.fasteners import Screw, Nut, Washer, HeatSetInsert`.+Animations in animations/*.py: `from soma.anim import Animation`."""import time as _time# Vor dem Import von cadquery (dauert Sekunden): `soma build` meldet die ganze Wartezeit, nicht nur das Modelldiff --git a/python/soma/analysis.py b/python/soma/analysis.pyindex f07c4e4..afa4f2a 100644--- a/python/soma/analysis.py+++ b/python/soma/analysis.py@@ -19,12 +19,12 @@ from . import build, gltf, mesherOUT_DIR = Path(".soma") / "results"KINDS = {- "overhang": dict(title="Überhang", quantity="Überhangwinkel", unit="°", bad="high", threshold=45.0,- help="Winkel zur Senkrechten fuer nach unten zeigende Flaechen, kritisch ueber dem Grenzwert"),- "thickness": dict(title="Wandstärke", quantity="Wandstärke", unit="mm", bad="low", threshold=1.2,- help="Abstand zur Gegenseite des Materials, kritisch unter dem Grenzwert"),- "clearance": dict(title="Abstand", quantity="Abstand zu anderen Bauteilen", unit="mm", bad="low", threshold=0.5,- help="kleinster Abstand zu einem anderen Bauteil, negativ bei Ueberschneidung, kritisch unter dem Grenzwert"),+ "overhang": dict(title="Overhang", quantity="Overhang angle", unit="°", bad="high", threshold=45.0,+ help="angle from vertical for downward-facing faces, critical above the limit"),+ "thickness": dict(title="Wall thickness", quantity="Wall thickness", unit="mm", bad="low", threshold=1.2,+ help="distance to the opposite side of the material, critical below the limit"),+ "clearance": dict(title="Clearance", quantity="Clearance to other parts", unit="mm", bad="low", threshold=0.5,+ help="smallest distance to another part, negative where they overlap, critical below the limit"),}@@ -187,13 +187,13 @@ def _pick(parts, spec, default_roles):group = [p for p in parts if _group_path(p) == path or _group_path(p).startswith(path + "/")]part = [p for p in parts if p["name"] == s]if part and group:- notes.append(f"{s!r} ist Bauteil und Gruppe: ausgewertet ist das Bauteil, die Gruppe mit --parts \"{path}/\"")+ notes.append(f"{s!r} is a part and a group: the part was analysed, for the group use --parts \"{path}/\"")hit = part or groupif not hit:names = ", ".join(repr(p["name"]) for p in parts[:30])groups = sorted({_group_path(p) for p in parts if p.get("group")})- raise AnalysisError(f"Bauteil oder Gruppe {s!r} gibt es nicht. Bauteile: {names}"- + (f". Gruppen: {', '.join(repr(g) for g in groups)}" if groups else ""))+ raise AnalysisError(f"There is no part or group {s!r}. Parts: {names}"+ + (f". Groups: {', '.join(repr(g) for g in groups)}" if groups else ""))out += [p for p in hit if p not in out]return out, notes@@ -270,7 +270,7 @@ def run(root, kind, parts_spec=None, threshold=None, up="z", name=None):"""Fuehrt eine Auswertung aus, schreibt .soma/results/<name>.glb und gibt die Metadaten zurueck."""from .progress import Progressif kind not in KINDS:- raise AnalysisError(f"Unbekannte Auswertung {kind!r}. Moeglich: {', '.join(KINDS)}")+ raise AnalysisError(f"Unknown analysis {kind!r}. Available: {', '.join(KINDS)}")spec = KINDS[kind]high = spec["bad"] == "high"thr = spec["threshold"] if threshold is None else float(threshold)@@ -278,12 +278,12 @@ def run(root, kind, parts_spec=None, threshold=None, up="z", name=None):try:parts = build.run_model(root)except build.BuildError as e:- raise AnalysisError(f"Das Modell laesst sich nicht bauen: {e.message}" + (f" ({e.file}:{e.line})" if e.file and e.line else "")) from None+ raise AnalysisError(f"The model does not build: {e.message}" + (f" ({e.file}:{e.line})" if e.file and e.line else "")) from Nonechosen, notes = _pick(parts, parts_spec, ("part",))if not chosen:- raise AnalysisError("Keine Bauteile zum Auswerten (ohne --parts zaehlen nur eigene Teile, keine Referenzen und Zukaufteile).")+ raise AnalysisError("No parts to analyse (without --parts only your own parts count, not reference or purchased parts).")if up not in AXES:- raise AnalysisError(f"--up {up!r} gibt es nicht. Moeglich: {', '.join(AXES)}")+ raise AnalysisError(f"There is no --up {up!r}. Available: {', '.join(AXES)}")upv = np.asarray(AXES[up], dtype=float)tol = build.auto_tolerance([p["shape"] for p in parts])meshes = {p["name"]: mesher.mesh_shape(p["shape"], tol, 0.3) for p in parts}@@ -297,7 +297,7 @@ def run(root, kind, parts_spec=None, threshold=None, up="z", name=None):# mit genau 45 Grad oder genau 0,2 mm Spiel lag durch Rundung sonst knapp darueber.band = 0.5 if kind == "overhang" else round(max(0.005, tol), 4)if kind == "clearance" and len(parts) < 2:- raise AnalysisError("Der Abstand braucht mindestens zwei Bauteile.")+ raise AnalysisError("Clearance needs at least two parts.")g = gltf.Glb()edge_mat = g.material(name="edge", pbrMetallicRoughness=dict(baseColorFactor=[0.05, 0.05, 0.05, 1.0], metallicFactor=0, roughnessFactor=1))face_mat = g.material(name="result", doubleSided=True, pbrMetallicRoughness=dict(baseColorFactor=[1, 1, 1, 1], metallicFactor=0, roughnessFactor=0.7))@@ -310,7 +310,7 @@ def run(root, kind, parts_spec=None, threshold=None, up="z", name=None):continuepos, nrm, idx = m["positions"].astype(float), m["normals"].astype(float), m["indices"].astype(np.int64)work.append((i, p, m, pos, idx, _subdivide(pos, nrm, idx, h, 150000)))- progress = Progress(f"soma analyze {kind}", sum(len(w[5][2]) for w in work), "Messstellen")+ progress = Progress(f"soma analyze {kind}", sum(len(w[5][2]) for w in work), "sample points")for i, p, m, pos, idx, (pos2, nrm2, idx2) in work:tri = pos2[idx2]fn = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])@@ -415,48 +415,48 @@ def _mm2(a):def _region_line(r, unit):size = f"{r['size'][0]:.1f} x {r['size'][1]:.1f} mm"if r.get("count", 1) > 1:- return f"{r['count']} gleichartige Stellen je {_mm2(r['area'])} in {size}, bis {_fmt(r['worst'], unit)}, z. B. bei {_where(r['at'])}"- return f"{_mm2(r['area'])} in {size}, bis {_fmt(r['worst'], unit)} bei {_where(r['at'])}"+ return f"{r['count']} similar spots of {_mm2(r['area'])} each in {size}, up to {_fmt(r['worst'], unit)}, e.g. at {_where(r['at'])}"+ return f"{_mm2(r['area'])} in {size}, up to {_fmt(r['worst'], unit)} at {_where(r['at'])}"def summary_text(meta):unit, thr = meta["unit"], meta["threshold"]- worse = "über" if meta["bad"] == "high" else "unter"- head = f"{meta['title']} (Grenzwert {_fmt(thr, unit)}, kritisch {worse} dem Grenzwert"+ worse = "above" if meta["bad"] == "high" else "below"+ head = f"{meta['title']} (limit {_fmt(thr, unit)}, critical {worse} the limit"if meta.get("tolerance"):- head += f", auf ±{meta['tolerance']:g}{'°' if unit == '°' else ' ' + unit} genau"+ head += f", accurate to ±{meta['tolerance']:g}{'°' if unit == '°' else ' ' + unit}"head += ")"if meta["kind"] == "overhang":- head += f", Druckrichtung +{meta['up'].lstrip('-')}" if not (meta["up"] or "").startswith("-") else f", Druckrichtung {meta['up']}"+ head += f", print direction +{meta['up'].lstrip('-')}" if not (meta["up"] or "").startswith("-") else f", print direction {meta['up']}"lines = [head + ":"]for st in meta["parts"]:if "min" not in st:- lines.append(f" {st['name']}: keine Werte")+ lines.append(f" {st['name']}: no values")continue- rng = f"{_fmt(st['min'], unit)} bis {_fmt(st['max'], unit)}"- crit = f"{st['critical'] / 100:.2f} cm² {worse} {_fmt(thr, unit)}" if st["critical"] > 0 else f"nichts {worse} {_fmt(thr, unit)}"+ rng = f"{_fmt(st['min'], unit)} to {_fmt(st['max'], unit)}"+ crit = f"{st['critical'] / 100:.2f} cm² {worse} {_fmt(thr, unit)}" if st["critical"] > 0 else f"nothing {worse} {_fmt(thr, unit)}"w = st["worst"]extra = ""if st.get("limit"):- extra += f", {st['limit'] / 100:.2f} cm² genau am Grenzwert"+ extra += f", {st['limit'] / 100:.2f} cm² exactly at the limit"if st.get("overlap"):- extra += f", davon {st['overlap'] / 100:.2f} cm² Ueberschneidung"+ extra += f", of which {st['overlap'] / 100:.2f} cm² overlap"if st.get("contact"):- extra += f", {st['contact'] / 100:.2f} cm² Beruehrung (nicht kritisch)"+ extra += f", {st['contact'] / 100:.2f} cm² contact (not critical)"if st.get("open"):- extra += f", {st['open']} Stellen ohne Gegenseite (offene Flaeche?)"+ extra += f", {st['open']} spots without an opposite side (open face?)"if st.get("betterUp"):b = st["betterUp"]- extra += f", mit --up {b['up']} nur {b['critical'] / 100:.2f} cm²"- worst = f", {'groesster' if meta['bad'] == 'high' else 'kleinster'} Wert {_fmt(w['value'], unit)} bei {_where(w['at'])}" if st["critical"] > 0 else ""+ extra += f", with --up {b['up']} only {b['critical'] / 100:.2f} cm²"+ worst = f", {'largest' if meta['bad'] == 'high' else 'smallest'} value {_fmt(w['value'], unit)} at {_where(w['at'])}" if st["critical"] > 0 else ""lines.append(f" {st['name']}: {rng}, {crit}{extra}{worst}")for r in st.get("regions", []):lines.append(f" {_region_line(r, unit)}")if st.get("regionsMore"):mo = st["regionsMore"]- lines.append(f" und {mo['count']} weitere Stelle{'n' if mo['count'] > 1 else ''}, zusammen {_mm2(mo['area'])}")+ lines.append(f" and {mo['count']} more spot{'s' if mo['count'] > 1 else ''}, {_mm2(mo['area'])} in total")for n in meta.get("notes") or []:- lines.append(f"Hinweis: {n}")+ lines.append(f"Note: {n}")return "\n".join(lines)diff --git a/python/soma/anim.py b/python/soma/anim.pyindex 3871a2f..b39d0ef 100644--- a/python/soma/anim.py+++ b/python/soma/anim.py@@ -1,19 +1,19 @@-"""Animationen (E58): Bewegungen, Kamerafahrten und Texte, beschrieben in animations/*.py.+"""Animations: movements, camera moves and texts, described in animations/*.py.-Der Agent beschreibt eine Animation in Python, aehnlich wie in manim (`play`, `wait`, `run_time`) und mit Drehachsen wie-in CadQuery (`rotate(p1, p2, winkel)`). `soma anim build` fuehrt die Datei aus, tastet die Bewegung ab und schreibt eine-glTF-Animation nach .soma/anim/. Viewer, Video und Bilder entstehen daraus, die Animation selbst ist kein Video.+An animation is described in Python, similar to manim (`play`, `wait`, `run_time`) and with rotation axes as in+CadQuery (`rotate(p1, p2, angle)`). `soma anim build` runs the file, samples the movement and writes a glTF animation+to .soma/anim/. The viewer, videos and pictures are made from it, the animation itself is not a video.from soma.anim import Animation- a = Animation("Deckel oeffnen")- lid = a.hinge("Deckel", (0, 20, 25), (1, 20, 25)) # Drehachse durch zwei Punkte, wie cq rotate()+ a = Animation("Open lid")+ lid = a.hinge("Lid", (0, 20, 25), (1, 20, 25)) # rotation axis through two points, like cq rotate()a.camera.set(view="iso")- a.caption("Der Deckel oeffnet bis 110 Grad")+ a.caption("The lid opens to 110 degrees")a.play(lid.to(110), run_time=2)a.play(a.camera.orbit(90), run_time=3)-Laengen in mm, Winkel in Grad, Zeiten in Sekunden. Bauteile heissen wie in add_part(), Gruppen wie in group=.+Lengths in mm, angles in degrees, times in seconds. Parts are named as in add_part(), groups as in group=."""import inspectimport math@@ -51,7 +51,7 @@ def _ease(ease):if callable(ease):return easeif ease not in EASES:- raise ValueError(f"ease={ease!r} gibt es nicht. Moeglich: {', '.join(EASES)} oder eine Funktion f(s) fuer s von 0 bis 1")+ raise ValueError(f"ease={ease!r} does not exist. Possible: {', '.join(EASES)} or a function f(s) for s from 0 to 1")return EASES[ease]@@ -61,9 +61,9 @@ def _vec(v, what):try:a = np.asarray([float(x) for x in v], dtype=float)except (TypeError, ValueError):- raise ValueError(f"{what} muss drei Zahlen haben, z. B. (0, 0, 10), nicht {v!r}") from None+ raise ValueError(f"{what} needs three numbers, e.g. (0, 0, 10), not {v!r}") from Noneif a.shape != (3,) or not np.all(np.isfinite(a)):- raise ValueError(f"{what} muss drei Zahlen haben, z. B. (0, 0, 10), nicht {v!r}")+ raise ValueError(f"{what} needs three numbers, e.g. (0, 0, 10), not {v!r}")return a@@ -71,7 +71,7 @@ def _unit(v, what):v = _vec(v, what)n = np.linalg.norm(v)if n < 1e-12:- raise ValueError(f"{what} darf nicht die Laenge 0 haben")+ raise ValueError(f"{what} must not have length 0")return v / n@@ -156,19 +156,19 @@ def _placement(loc):a = np.asarray(loc, dtype=float) if not isinstance(loc, str) else Noneif a is not None and a.shape == (4, 4):return a.copy()- return _translation(_vec(loc, "Die Lage"))+ return _translation(_vec(loc, "The location"))# ---- Bauteile ---------------------------------------------------------------------------------------------------def _parts():if _PARTS is None:- raise RuntimeError("Animationen laufen ueber `soma anim build` (dort kennt soma die Bauteile des Modells), "- "nicht direkt mit python.")+ raise RuntimeError("Animations run through `soma anim build` (there soma knows the parts of the model), "+ "not directly with python.")return _PARTS-def _resolve(spec, what="Bauteil"):+def _resolve(spec, what="Part"):"""Bauteilname, Gruppe ("Gehaeuse" oder "Gehaeuse/Schrauben") oder eine Liste davon -> Liste von Bauteilnamen."""parts = _parts()if isinstance(spec, (list, tuple, set)):@@ -178,10 +178,10 @@ def _resolve(spec, what="Bauteil"):if n not in out:out.append(n)if not out:- raise ValueError(f"{what}: leere Liste")+ raise ValueError(f"{what}: empty list")return outif not isinstance(spec, str) or not spec.strip():- raise ValueError(f"{what} muss ein Bauteilname oder eine Gruppe sein, nicht {spec!r}")+ raise ValueError(f"{what} must be a part name or a group, not {spec!r}")if any(p["name"] == spec for p in parts):return [spec]path = spec.strip("/")@@ -190,8 +190,8 @@ def _resolve(spec, what="Bauteil"):return hitnames = ", ".join(repr(p["name"]) for p in parts[:30]) + (" ..." if len(parts) > 30 else "")groups = sorted({"/".join(p["group"][:i + 1]) for p in parts for i in range(len(p["group"]))})- extra = f" Gruppen: {', '.join(repr(g) for g in groups)}." if groups else ""- raise ValueError(f"{what} {spec!r} gibt es im Modell nicht. Bauteile: {names}.{extra}")+ extra = f" Groups: {', '.join(repr(g) for g in groups)}." if groups else ""+ raise ValueError(f"{what} {spec!r} does not exist in the model. Parts: {names}.{extra}")def _where():@@ -202,10 +202,10 @@ def _where():def _text(text, what):if not isinstance(text, str):- raise ValueError(f"{what} muss ein Text sein, nicht {type(text).__name__}")+ raise ValueError(f"{what} must be a text, not {type(text).__name__}")t = " ".join(text.split())if len(t) > MAX_TEXT:- raise ValueError(f"{what} ist laenger als {MAX_TEXT} Zeichen")+ raise ValueError(f"{what} is longer than {MAX_TEXT} characters")return t@@ -213,9 +213,9 @@ def _num(v, what, lo=None):try:f = float(v)except (TypeError, ValueError):- raise ValueError(f"{what} muss eine Zahl sein, nicht {v!r}") from None+ raise ValueError(f"{what} must be a number, not {v!r}") from Noneif not math.isfinite(f) or (lo is not None and f < lo):- raise ValueError(f"{what} muss eine Zahl{'' if lo is None else f' ab {lo}'} sein, nicht {v!r}")+ raise ValueError(f"{what} must be a number{'' if lo is None else f' of at least {lo}'}, not {v!r}")return f@@ -229,7 +229,7 @@ class _Action:class Joint:- """Bauteile, die sich gemeinsam bewegen. Entsteht ueber Animation.hinge(), slider() oder part()."""+ """Parts that move together. Created by Animation.hinge(), slider() or part()."""unit = None # Einheit des Gelenkwerts (Grad, mm), None bei frei bewegten Teilen@@ -255,13 +255,13 @@ class Joint:return vdef matrix(self, t):- """Lage aller Bauteile dieses Gelenks zur Zeit t (mit den Gelenken darueber)."""+ """Position of all parts of this joint at time t (including the joints above it), as a 4x4 matrix."""m = self._own(self.value_at(t))return self.parent.matrix(t) @ m if self.parent else mclass _Hinge(Joint):- unit = "Grad"+ unit = "deg"def __init__(self, anim, parts, p1, axis, parent, angle):super().__init__(anim, "hinge", parts, parent, angle)@@ -271,14 +271,14 @@ class _Hinge(Joint):return _axis_rotation(self.p1, self.axis, value)def to(self, angle):- """Auf diesen Winkel drehen (Grad, 0 = Lage im Modell)."""- a1 = _num(angle, "Der Winkel")- return _Action(self, lambda a0: (lambda s: a0 + (a1 - a0) * s, a1), lambda a0: f"{self.label}: {a0:g} -> {a1:g} Grad")+ """Rotate to this angle (degrees, 0 = position in the model)."""+ a1 = _num(angle, "The angle")+ return _Action(self, lambda a0: (lambda s: a0 + (a1 - a0) * s, a1), lambda a0: f"{self.label}: {a0:g} -> {a1:g} deg")def by(self, delta):- """Um diesen Winkel weiterdrehen (Grad)."""- d = _num(delta, "Der Winkel")- return _Action(self, lambda a0: (lambda s: a0 + d * s, a0 + d), lambda a0: f"{self.label}: {a0:g} -> {a0 + d:g} Grad")+ """Rotate further by this angle (degrees)."""+ d = _num(delta, "The angle")+ return _Action(self, lambda a0: (lambda s: a0 + d * s, a0 + d), lambda a0: f"{self.label}: {a0:g} -> {a0 + d:g} deg")class _Slider(Joint):@@ -292,13 +292,13 @@ class _Slider(Joint):return _translation(self.direction * value)def to(self, distance):- """An diese Stelle schieben (mm entlang der Richtung, 0 = Lage im Modell)."""- d1 = _num(distance, "Der Weg")+ """Slide to this position (mm along the direction, 0 = position in the model)."""+ d1 = _num(distance, "The distance")return _Action(self, lambda d0: (lambda s: d0 + (d1 - d0) * s, d1), lambda d0: f"{self.label}: {d0:g} -> {d1:g} mm")def by(self, delta):- """Um diesen Weg weiterschieben (mm)."""- d = _num(delta, "Der Weg")+ """Slide further by this distance (mm)."""+ d = _num(delta, "The distance")return _Action(self, lambda d0: (lambda s: d0 + d * s, d0 + d), lambda d0: f"{self.label}: {d0:g} -> {d0 + d:g} mm")@@ -310,30 +310,30 @@ class _Free(Joint):return valuedef to(self, location):- """In diese Lage bewegen (cq.Location oder (x, y, z), bezogen auf die Lage im Modell). Ohne Drehachse geht der- Ursprung geradlinig: Fuer Drehungen um eine Achse hinge() oder rotate() nehmen."""+ """Move to this location (cq.Location or (x, y, z), relative to the position in the model). Without a rotation+ axis the origin moves in a straight line: for rotations about an axis use hinge() or rotate()."""m1 = _placement(location)- return _Action(self, lambda m0: (lambda s: _blend(m0, m1, s), m1), lambda m0: f"{self.label}: in neue Lage")+ return _Action(self, lambda m0: (lambda s: _blend(m0, m1, s), m1), lambda m0: f"{self.label}: to new location")def translate(self, vector):- """Um diesen Vektor verschieben (mm)."""- v = _vec(vector, "Die Verschiebung")+ """Move by this vector (mm)."""+ v = _vec(vector, "The translation")return _Action(self, lambda m0: (lambda s: _translation(v * s) @ m0, _translation(v) @ m0),- lambda m0: f"{self.label}: verschieben um ({v[0]:g}, {v[1]:g}, {v[2]:g}) mm")+ lambda m0: f"{self.label}: move by ({v[0]:g}, {v[1]:g}, {v[2]:g}) mm")def rotate(self, p1, p2, angle):- """Um die Achse durch p1 und p2 drehen (Grad), wie cq rotate(). Die Achse liegt im Modell, nicht im Teil."""- a, b = _vec(p1, "Der erste Achspunkt"), _vec(p2, "Der zweite Achspunkt")- axis = _unit(b - a, "Die Drehachse (p2 - p1)")- deg = _num(angle, "Der Winkel")+ """Rotate about the axis through p1 and p2 (degrees), like cq rotate(). The axis is in the model, not in the part."""+ a, b = _vec(p1, "The first axis point"), _vec(p2, "The second axis point")+ axis = _unit(b - a, "The rotation axis (p2 - p1)")+ deg = _num(angle, "The angle")return _Action(self, lambda m0: (lambda s: _axis_rotation(a, axis, deg * s) @ m0, _axis_rotation(a, axis, deg) @ m0),- lambda m0: f"{self.label}: drehen um {deg:g} Grad")+ lambda m0: f"{self.label}: rotate by {deg:g} deg")# ---- Kamera -----------------------------------------------------------------------------------------------------class Camera:- """Kamera einer Animation. set() springt, move(), orbit() und zoom() sind Bewegungen fuer play()."""+ """Camera of an animation. set() jumps, move(), orbit() and zoom() are movements for play()."""def __init__(self, anim):self.anim = anim@@ -344,11 +344,11 @@ class Camera:if view is not None:if isinstance(view, str):if view not in VIEWS:- raise ValueError(f"view={view!r} gibt es nicht. Moeglich: {', '.join(VIEWS)} oder eine Richtung (x, y, z)")- spec["dir"] = _unit(VIEWS[view], "Die Blickrichtung")+ raise ValueError(f"view={view!r} does not exist. Possible: {', '.join(VIEWS)} or a direction (x, y, z)")+ spec["dir"] = _unit(VIEWS[view], "The view direction")else:- spec["dir"] = _unit(view, "Die Blickrichtung (von der Mitte zur Kamera)")- spec["view"] = view if isinstance(view, str) else "Richtung"+ spec["dir"] = _unit(view, "The view direction (from the center to the camera)")+ spec["view"] = view if isinstance(view, str) else "direction"if fit is not None:spec["fit"] = None if fit == "all" else _resolve(fit, "fit")if zoom is not None:@@ -360,63 +360,63 @@ class Camera:return specdef set(self, view=None, fit=None, zoom=None, target=None, distance=None):- """Kamera sofort setzen. view: "iso", "front", "back", "left", "right", "top", "bottom" oder eine Richtung von der- Mitte zur Kamera. fit: Bauteile oder Gruppen, die ganz ins Bild sollen (ueber die ganze Bewegung), Standard alle.- zoom: groesser als 1 naeher heran. target und distance setzen Mitte und Abstand (mm) direkt."""+ """Set the camera at once. view: "iso", "front", "back", "left", "right", "top", "bottom" or a direction from the+ center to the camera. fit: parts or groups that should be fully in the picture (over the whole movement), default+ all. zoom: greater than 1 is closer. target and distance set the center and the distance (mm) directly."""spec = self._spec(view, fit, zoom, target, distance)if "fit" not in spec and "target" not in spec and "distance" not in spec:spec["fit"] = None # ohne Angabe: alles einpassent = self.anim.timeself.ops.append(dict(t0=t, t1=t, kind="set", spec=spec, ease=EASES["linear"]))- self.anim._step(t, t, "Kamera: " + _describe_camera(spec))+ self.anim._step(t, t, "Camera: " + _describe_camera(spec))def move(self, view=None, fit=None, zoom=None, target=None, distance=None):- """Kamerafahrt zu einer neuen Ansicht (fuer play). Was nicht angegeben ist, bleibt: Ohne fit, target und distance- bleiben Mitte und Abstand, und die Kamera schwenkt nur."""+ """Camera move to a new view (for play). What is not given stays: without fit, target and distance the center+ and the distance stay, and the camera only swings around."""spec = self._spec(view, fit, zoom, target, distance)- return _Action(self, ("move", spec), lambda _v: "Kamera: Fahrt " + _describe_camera(spec))+ return _Action(self, ("move", spec), lambda _v: "Camera: move " + _describe_camera(spec))def orbit(self, degrees, tilt=0.0):- """Um die Mitte kreisen (Grad um die Hochachse Z, positiv gegen den Uhrzeigersinn von oben). tilt hebt oder- senkt die Kamera (Grad)."""- spec = dict(orbit=_num(degrees, "Der Winkel"), tilt=_num(tilt, "tilt"))- return _Action(self, ("orbit", spec), lambda _v: f"Kamera: Umlauf {spec['orbit']:g} Grad" + (f", Neigung {spec['tilt']:g} Grad" if spec["tilt"] else ""))+ """Circle around the center (degrees about the vertical axis Z, positive is counterclockwise seen from above).+ tilt raises or lowers the camera (degrees)."""+ spec = dict(orbit=_num(degrees, "The angle"), tilt=_num(tilt, "tilt"))+ return _Action(self, ("orbit", spec), lambda _v: f"Camera: orbit {spec['orbit']:g} deg" + (f", tilt {spec['tilt']:g} deg" if spec["tilt"] else ""))def zoom(self, factor):- """Naeher heran (factor groesser als 1) oder weiter weg (kleiner als 1)."""- f = _num(factor, "Der Faktor", 0.01)- return _Action(self, ("zoom", dict(zoom=f)), lambda _v: f"Kamera: Zoom x{f:g}")+ """Closer (factor greater than 1) or farther away (less than 1)."""+ f = _num(factor, "The factor", 0.01)+ return _Action(self, ("zoom", dict(zoom=f)), lambda _v: f"Camera: zoom x{f:g}")def _describe_camera(spec):bits = []if "view" in spec:- bits.append(f"Ansicht {spec['view']}")+ bits.append(f"view {spec['view']}")if "fit" in spec:- bits.append("alles im Bild" if spec["fit"] is None else f"im Bild: {', '.join(spec['fit'][:4])}")+ bits.append("everything in the picture" if spec["fit"] is None else f"in the picture: {', '.join(spec['fit'][:4])}")if "zoom" in spec:- bits.append(f"Zoom x{spec['zoom']:g}")+ bits.append(f"zoom x{spec['zoom']:g}")if "target" in spec:- bits.append("Mitte ({:g}, {:g}, {:g})".format(*spec["target"]))+ bits.append("center ({:g}, {:g}, {:g})".format(*spec["target"]))if "distance" in spec:- bits.append(f"Abstand {spec['distance']:g} mm")- return ", ".join(bits) or "unveraendert"+ bits.append(f"distance {spec['distance']:g} mm")+ return ", ".join(bits) or "unchanged"# ---- Animation --------------------------------------------------------------------------------------------------class Animation:- """Eine Animation mit Namen. Mehrere je Datei sind erlaubt, Namen muessen im Projekt eindeutig sein.+ """An animation with a name. Several per file are allowed, names must be unique in the project.- Zeitleiste wie in manim: play() bewegt (alle uebergebenen Bewegungen gleichzeitig) und rueckt die Zeit um run_time- weiter, wait() wartet, title() zeigt eine Titelkarte und rueckt weiter. caption(), label(), highlight(), hide(),- show() und ghost() gelten ab der aktuellen Zeit und ruecken nicht weiter.+ Timeline as in manim: play() moves (all given movements at the same time) and advances the time by run_time,+ wait() waits, title() shows a title card and advances. caption(), label(), highlight(), hide(), show() and ghost()+ apply from the current time and do not advance it."""def __init__(self, name):- self.name = _text(name, "Der Name der Animation")+ self.name = _text(name, "The name of the animation")if not self.name:- raise ValueError("Die Animation braucht einen Namen, z. B. Animation(\"Deckel oeffnen\")")+ raise ValueError("The animation needs a name, e.g. Animation(\"Open lid\")")self.id = registry.ascii_name(self.name).lower().replace("_", "-")self.file, self.line = _where()self.time = 0.0@@ -431,26 +431,26 @@ class Animation:for j in self.joints:twice = set(j.parts) & set(joint.parts)if twice:- raise ValueError(f"{sorted(twice)[0]!r} haengt schon an einem Gelenk dieser Animation. Ein Bauteil hat "- "ein Gelenk, Bewegungen darueber kommen mit parent=.")+ raise ValueError(f"{sorted(twice)[0]!r} is already on a joint of this animation. A part has one joint, "+ "movements on top of it come with parent=.")if joint.parent is not None and not isinstance(joint.parent, Joint):- raise ValueError("parent muss ein Gelenk dieser Animation sein (Rueckgabe von hinge(), slider() oder part())")+ raise ValueError("parent must be a joint of this animation (returned by hinge(), slider() or part())")self.joints.append(joint)return jointdef hinge(self, parts, p1, p2, parent=None, angle=0.0):- """Drehgelenk: Bauteile (Name, Gruppe oder Liste) drehen um die Achse durch p1 und p2, wie cq rotate(p1, p2, w).- Positive Winkel drehen rechtsherum um die Richtung p2 - p1. angle ist der Winkel am Anfang (Grad, 0 = wie im- Modell). parent: Gelenk, auf dem dieses sitzt (die Achse liegt dann in der Modelllage)."""- a, b = _vec(p1, "Der erste Achspunkt"), _vec(p2, "Der zweite Achspunkt")- return self._joint(_Hinge(self, _resolve(parts), a, _unit(b - a, "Die Drehachse (p2 - p1)"), parent, _num(angle, "angle")))+ """Revolute joint: parts (name, group or list) rotate about the axis through p1 and p2, like cq rotate(p1, p2, a).+ Positive angles turn right-handed about the direction p2 - p1. angle is the angle at the start (degrees, 0 = as in+ the model). parent: joint this one sits on (the axis is then given in the model position)."""+ a, b = _vec(p1, "The first axis point"), _vec(p2, "The second axis point")+ return self._joint(_Hinge(self, _resolve(parts), a, _unit(b - a, "The rotation axis (p2 - p1)"), parent, _num(angle, "angle")))def slider(self, parts, direction, parent=None, position=0.0):- """Schubgelenk: Bauteile verschieben sich entlang direction. position ist der Weg am Anfang (mm)."""- return self._joint(_Slider(self, _resolve(parts), _unit(direction, "Die Richtung"), parent, _num(position, "position")))+ """Prismatic joint: parts slide along direction. position is the distance at the start (mm)."""+ return self._joint(_Slider(self, _resolve(parts), _unit(direction, "The direction"), parent, _num(position, "position")))def part(self, parts, parent=None):- """Frei bewegte Bauteile: to(lage), translate((x, y, z)), rotate(p1, p2, winkel)."""+ """Freely moving parts: to(location), translate((x, y, z)), rotate(p1, p2, angle)."""return self._joint(_Free(self, _resolve(parts), parent))# -- Zeitleiste --@@ -461,19 +461,19 @@ class Animation:self.steps.append(dict(start=round(t0, 4), end=round(t1, 4), text=text, **move))def play(self, *actions, run_time=1.0, ease="smooth"):- """Bewegungen gleichzeitig ablaufen lassen, dann geht die Zeit um run_time (Sekunden) weiter.- ease: "smooth" (Standard, sanft an und aus), "linear", "in", "out" oder eine Funktion f(s)."""+ """Run movements at the same time, then the time advances by run_time (seconds).+ ease: "smooth" (default, gentle start and stop), "linear", "in", "out" or a function f(s)."""rt = _num(run_time, "run_time", 0.0)f = _ease(ease)if not actions:- raise ValueError("play() braucht mindestens eine Bewegung, z. B. play(deckel.to(90)). Zum Warten: wait()")+ raise ValueError("play() needs at least one movement, e.g. play(lid.to(90)). To wait: wait()")seen = set()t0, t1 = self.time, self.time + rtfor act in actions:if not isinstance(act, _Action):- raise ValueError(f"play() erwartet Bewegungen wie gelenk.to(90) oder a.camera.orbit(90), nicht {act!r}")+ raise ValueError(f"play() expects movements like joint.to(90) or a.camera.orbit(90), not {act!r}")if id(act.target) in seen:- raise ValueError("Ein Gelenk (oder die Kamera) kommt zweimal im selben play() vor")+ raise ValueError("A joint (or the camera) appears twice in the same play()")seen.add(id(act.target))if isinstance(act.target, Camera):kind, spec = act.make@@ -483,7 +483,7 @@ class Animation:continuej = act.targetif j.anim is not self:- raise ValueError("Diese Bewegung gehoert zu einer anderen Animation")+ raise ValueError("This movement belongs to another animation")func, end = act.make(j.value)j.segments.append((t0, t1, func, f))move = dict(key=f"joint{self.joints.index(j)}", label=j.label)@@ -494,46 +494,46 @@ class Animation:self.time = t1def wait(self, seconds=1.0):- """Nichts bewegt sich, die Zeit geht weiter."""- s = _num(seconds, "Die Wartezeit", 0.0)+ """Nothing moves, the time advances."""+ s = _num(seconds, "The waiting time", 0.0)self._step(self.time, self.time + s, "Pause")self.time += s# -- Texte und Hervorhebungen --def title(self, text, subtitle=None, duration=2.0):- """Titelkarte in der Bildmitte. Die Zeit geht um duration weiter (wie wait)."""+ """Title card in the middle of the picture. The time advances by duration (like wait)."""d = _num(duration, "duration", 0.0)- t = dict(start=self.time, end=self.time + d, text=_text(text, "Der Titel"))+ t = dict(start=self.time, end=self.time + d, text=_text(text, "The title"))if subtitle:- t["subtitle"] = _text(subtitle, "Der Untertitel")+ t["subtitle"] = _text(subtitle, "The subtitle")self.titles.append(t)- self._step(self.time, self.time + d, f"Titel: {t['text']}")+ self._step(self.time, self.time + d, f"Title: {t['text']}")self.time += ddef caption(self, text, duration=None):- """Untertitel unten im Bild, ab jetzt bis zum naechsten Untertitel (oder duration Sekunden). caption(None) blendet aus."""+ """Caption at the bottom of the picture, from now until the next caption (or duration seconds). caption(None) hides it."""if text is None or text == "":self.captions.append(dict(start=self.time, end=None, text=""))returnd = None if duration is None else _num(duration, "duration", 0.0)- c = dict(start=self.time, end=None if d is None else self.time + d, text=_text(text, "Der Untertitel"))+ c = dict(start=self.time, end=None if d is None else self.time + d, text=_text(text, "The caption"))self.captions.append(c)- self._step(self.time, self.time if d is None else self.time + d, f"Untertitel: {c['text']}")+ self._step(self.time, self.time if d is None else self.time + d, f"Caption: {c['text']}")def label(self, text, part=None, at=None, duration=None):- """Beschriftung an einer Stelle im Modell, ab jetzt (bis zum Ende oder duration Sekunden). part: Das Schild wandert- mit diesem Bauteil. at: Punkt (mm, in der Lage im Modell), ohne at die Mitte des Bauteils."""+ """Label at a spot in the model, from now on (until the end or duration seconds). part: the label moves with this+ part. at: point (mm, in the position in the model), without at the center of the part."""if part is None and at is None:- raise ValueError("label() braucht part= oder at=")+ raise ValueError("label() needs part= or at=")names = _resolve(part, "part") if part is not None else []if len(names) > 1:- raise ValueError(f"label(part=...) braucht ein einzelnes Bauteil, {part!r} sind {len(names)}")+ raise ValueError(f"label(part=...) needs a single part, {part!r} are {len(names)}")d = None if duration is None else _num(duration, "duration", 0.0)- lb = dict(start=self.time, end=None if d is None else self.time + d, text=_text(text, "Die Beschriftung"),+ lb = dict(start=self.time, end=None if d is None else self.time + d, text=_text(text, "The label"),part=names[0] if names else None, at=None if at is None else [float(x) for x in _vec(at, "at")])self.labels.append(lb)- self._step(self.time, self.time, f"Beschriftung: {lb['text']}")+ self._step(self.time, self.time, f"Label: {lb['text']}")def _event(self, kind, parts, what):names = _resolve(parts)@@ -541,25 +541,27 @@ class Animation:self._step(self.time, self.time, f"{what}: {', '.join(names[:4])}{' ...' if len(names) > 4 else ''}")def highlight(self, parts, duration=None):- """Bauteile hervorheben (orange), ab jetzt bis unhighlight() oder duration Sekunden."""- self._event("highlight", parts, "Hervorheben")+ """Highlight parts (orange), from now until unhighlight() or duration seconds."""+ self._event("highlight", parts, "Highlight")if duration is not None:d = _num(duration, "duration", 0.0)self.events.append(dict(t=self.time + d, kind="unhighlight", parts=_resolve(parts)))def unhighlight(self, parts):- self._event("unhighlight", parts, "Hervorhebung aus")+ """End the highlight of parts."""+ self._event("unhighlight", parts, "Highlight off")def hide(self, parts):- """Bauteile ausblenden (bis show())."""- self._event("hide", parts, "Ausblenden")+ """Hide parts (until show())."""+ self._event("hide", parts, "Hide")def show(self, parts):- self._event("show", parts, "Einblenden")+ """Show hidden parts again."""+ self._event("show", parts, "Show")def ghost(self, parts, on=True):- """Bauteile durchsichtig zeigen (on=False: wieder deckend). So sieht man, was dahinter liegt."""- self._event("ghost" if on else "solid", parts, "Durchsichtig" if on else "Wieder deckend")+ """Show parts transparent (on=False: opaque again). So you can see what is behind them."""+ self._event("ghost" if on else "solid", parts, "Transparent" if on else "Opaque again")# -- Auswertung (fuer animrun.py) --diff --git a/python/soma/animrun.py b/python/soma/animrun.pyindex ccab4d8..bb5d918 100644--- a/python/soma/animrun.py+++ b/python/soma/animrun.py@@ -19,6 +19,9 @@ from . import anim, build, gltf, registryANIM_DIR = "animations"OUT_DIR = Path(".soma") / "anim"+# Arten eines Treffers in soma anim check. Vor E73 standen sie deutsch in .check.json, read_check() setzt sie um+COLLISION, TOO_CLOSE = "collision", "too close"+_OLD_KINDS = {"Kollision": COLLISION, "zu nah": TOO_CLOSE}class AnimError(Exception):@@ -91,7 +94,7 @@ def _run_file(root, path):runpy.run_path(str(path), run_name="__main__")except SystemExit as e:if e.code not in (None, 0):- raise build.BuildError(f"{_rel(path, root)} hat sich mit Code {e.code} beendet", file=_rel(path, root), kind="SystemExit")+ raise build.BuildError(f"{_rel(path, root)} exited with code {e.code}", file=_rel(path, root), kind="SystemExit")except BaseException as e:raise build._error_from_exception(e, root)finally:@@ -106,7 +109,7 @@ def _run_file(root, path):sys.path.pop(0)found = list(anim.ANIMATIONS)if not found:- raise build.BuildError(f"{_rel(path, root)} legt keine Animation an. Beginne mit a = Animation(\"Name\") "+ raise build.BuildError(f"{_rel(path, root)} creates no animation. Start with a = Animation(\"Name\") ""(from soma.anim import Animation).", file=_rel(path, root), kind="NoAnimation")return found@@ -282,7 +285,7 @@ def finalize(a):"""Abgetastete Daten einer Animation (fuer die Datei, die Textausgabe und die Pruefung)."""duration = a.durationif duration <= 0:- raise build.BuildError(f"Die Animation {a.name!r} ist leer: Sie braucht play(), wait() oder title(), damit Zeit vergeht.",+ raise build.BuildError(f"The animation {a.name!r} is empty: it needs play(), wait() or title() for time to pass.",file=a.file, line=a.line, kind="EmptyAnimation")times = sample_times(duration)poses = [a.poses(t) for t in times]@@ -361,7 +364,7 @@ def build_all(root, only=None):try:_parts, results = load(root, only)except build.BuildError as e:- raise AnimError(f"Das Modell laesst sich nicht bauen, deshalb auch keine Animation: {e.message}"+ raise AnimError(f"The model does not build, so no animation does either: {e.message}"+ (f" ({e.file}:{e.line})" if e.file and e.line else "")) from Nonedone_files = {_rel(f, root) for f, _ in results}keep = [x for x in old.get("animations", []) if x.get("file") not in done_files and (root / x.get("file", "")).is_file()]@@ -375,7 +378,7 @@ def build_all(root, only=None):for a in res:try:if a.id in taken:- raise build.BuildError(f"Die Animation {a.name!r} gibt es schon (in {taken[a.id]}). Namen muessen eindeutig sein.",+ raise build.BuildError(f"The animation {a.name!r} already exists (in {taken[a.id]}). Names must be unique.",file=_rel(a.file, root), line=a.line, kind="DuplicateName")taken[a.id] = reldata = finalize(a)@@ -430,10 +433,10 @@ def ensure(root, name):e = find(root, name)if e is None: # Eine Datei mit Fehler verliert ihre Eintraege, die Meldung nennt den Fehlernames = [x["name"] for x in res["index"]["animations"]]- msg = f"Keine Animation {name!r}."+ msg = f"No animation {name!r}."if res["errors"]:- msg += " Fehler: " + "; ".join(f"{x['file']}{':' + str(x['line']) if x.get('line') else ''}: {x['message']}" for x in res["errors"])- msg += f" Vorhanden: {', '.join(repr(n) for n in names)}." if names else f" In {ANIM_DIR}/ liegt noch keine fehlerfreie Animation."+ msg += " Errors: " + "; ".join(f"{x['file']}{':' + str(x['line']) if x.get('line') else ''}: {x['message']}" for x in res["errors"])+ msg += f" Available: {', '.join(repr(n) for n in names)}." if names else f" There is no animation without errors in {ANIM_DIR}/ yet."raise AnimError(msg)return e@@ -464,13 +467,13 @@ def _merge(run):v0, v1, lo, hi = first["v0"], run[-1]["v1"], min(vals), max(vals)text = f"{first['label']}: {_g(v0)} -> {_g(v1)} {first['unit']}"if lo < min(v0, v1) - 1e-6 or hi > max(v0, v1) + 1e-6:- text += f", dazwischen {_g(lo)} bis {_g(hi)} {first['unit']}"+ text += f", in between {_g(lo)} to {_g(hi)} {first['unit']}"elif first["key"] == "camera" and all("orbit" in x for x in run):orbit, tilt = sum(x["orbit"] for x in run), sum(x["tilt"] for x in run)- text = f"Kamera: Umlauf {_g(orbit)} Grad" + (f", Neigung {_g(tilt)} Grad" if abs(tilt) > 1e-9 else "")+ text = f"Camera: orbit {_g(orbit)} deg" + (f", tilt {_g(tilt)} deg" if abs(tilt) > 1e-9 else "")else:- text = first["text"].split(":")[0] + ": Bewegung"- s["text"] = f"{text} ({n} Schritte)"+ text = first["text"].split(":")[0] + ": movement"+ s["text"] = f"{text} ({n} steps)"return s@@ -508,24 +511,24 @@ def _compact_steps(steps):def info_text(root, entry):m = read_meta(root, entry)- lines = [f"Animation \"{m['name']}\" ({m['file']} Zeile {m['line']}), Dauer {_t(m['duration'])} s",- f"Bewegte Bauteile: {', '.join(m['parts']) or 'keine'}",- "Kamera: " + ("keine eigene (Standardansicht iso, alles im Bild)" if m["cameraAuto"] else "eigene Einstellungen und Fahrten"),- "", "Ablauf:"]+ lines = [f"Animation \"{m['name']}\" ({m['file']} line {m['line']}), duration {_t(m['duration'])} s",+ f"Moving parts: {', '.join(m['parts']) or 'none'}",+ "Camera: " + ("none of its own (default view iso, everything in the picture)" if m["cameraAuto"] else "own settings and moves"),+ "", "Sequence:"]for s in _compact_steps(m["steps"]):span = f"{_t(s['start'])}-{_t(s['end'])} s" if s["end"] > s["start"] else f"{_t(s['start'])} s"lines.append(f" {span:<16} {s['text']}")if m["captions"]:- lines += ["", "Untertitel:"] + [f" {_t(c['start'])}-{_t(c['end'])} s \"{c['text']}\"" for c in m["captions"]]+ lines += ["", "Captions:"] + [f" {_t(c['start'])}-{_t(c['end'])} s \"{c['text']}\"" for c in m["captions"]]if m["labels"]:- lines += ["", "Beschriftungen:"] + [- f" {_t(lb['start'])}-{_t(lb['end'])} s \"{lb['text']}\"" + (f" an {lb['part']}" if lb["part"] else "")- + " bei ({:.1f}, {:.1f}, {:.1f})".format(*lb["at"]) for lb in m["labels"]]+ lines += ["", "Labels:"] + [+ f" {_t(lb['start'])}-{_t(lb['end'])} s \"{lb['text']}\"" + (f" on {lb['part']}" if lb["part"] else "")+ + " at ({:.1f}, {:.1f}, {:.1f})".format(*lb["at"]) for lb in m["labels"]]chk = read_check(root, entry)if chk:lines += ["", check_text(chk)]else:- lines += ["", "Kollisionen: nicht geprueft (soma anim check \"" + m["name"] + "\")"]+ lines += ["", "Collisions: not checked (soma anim check \"" + m["name"] + "\")"]return "\n".join(lines)@@ -588,7 +591,7 @@ def _check(root, name, step, gap):parts, results = load(root, root / entry["file"])a = next((x for _f, res in results if not isinstance(res, build.BuildError) for x in res if x.id == entry["id"]), None)if a is None:- raise AnimError(f"Die Animation {name!r} liess sich nicht neu laden.")+ raise AnimError(f"The animation {name!r} could not be loaded again.")tol = build.auto_tolerance([p["shape"] for p in parts])pen = round(max(0.01, 2 * tol), 4)raw = {p["name"]: mesher.mesh_shape(p["shape"], tol, 0.3) for p in parts}@@ -687,26 +690,26 @@ def _check(root, name, step, gap):depth, dist = rhit = dict(distance=round(dist, 4), depth=round(depth, 4))if depth > pen:- return "Kollision", hit+ return COLLISION, hitif dist <= pen and not wanted:# Beruehrung oder flaches Eindringen, keine Ecke liegt tief im anderen Teil: die B-Rep-Koerper entscheidenvol, thick = overlap(m, o, ma, mb)if math.isnan(vol) or (vol > VOL_MIN and thick > pen):hit["volume"] = None if math.isnan(vol) else round(vol, 4)hit["depth"] = round(max(depth, 0.0 if math.isnan(thick) else thick), 4)- return "Kollision", hit+ return COLLISION, hit# Wie bei soma analyze: Werte innerhalb der Genauigkeit um den Grenzwert gelten als genau auf dem Grenzwertif gap > 0 and dist < gap - pen and dist < rest - pen:- return "zu nah", hit+ return TOO_CLOSE, hitreturn None, hit# Lage im Modell: Beruehrung und Spiel dort sind so konstruiert, eine Kollision dort meldet die Pruefung als schon vorhandenrest, at_rest = {}, {}for m, o in pairs:kind, hit = judge(m, o, eye, eye, eye, math.inf)- at_rest[(m, o)] = kind if kind == "Kollision" else None- rest[(m, o)] = math.inf if hit is None or kind == "Kollision" else hit["distance"]- progress = Progress("soma anim check", len(times), "Zeitpunkten")+ at_rest[(m, o)] = kind if kind == COLLISION else None+ rest[(m, o)] = math.inf if hit is None or kind == COLLISION else hit["distance"]+ progress = Progress("soma anim check", len(times), "time steps")found = {}for t in times:poses = a.poses(t)@@ -746,33 +749,38 @@ def read_check(root, entry):try:if p.stat().st_mtime < (Path(root) / entry["glb"]).stat().st_mtime:return None # gehoert zu einem aelteren Stand der Animation- return json.loads(p.read_text(encoding="utf-8"))+ res = json.loads(p.read_text(encoding="utf-8"))except (OSError, ValueError):return None+ # Pruefungen von vor E73 nennen die Arten deutsch+ for pair in res.get("pairs", []) if isinstance(res, dict) else []:+ for r in pair.get("ranges", []):+ r["kind"] = _OLD_KINDS.get(r.get("kind"), r.get("kind"))+ return resdef check_text(res):tol = res.get("tolerance")- head = (f"Kollisionen (Schritt {res['step']:g} s, {res['samples']} Zeitpunkte" + (f", Mindestabstand {res['gap']:g} mm" if res["gap"] else "")- + (f", genau auf {tol:g} mm" if tol else "") + "):")- lines = [head + ("" if res["pairs"] else " keine")]+ head = (f"Collisions (step {res['step']:g} s, {res['samples']} time steps" + (f", minimum distance {res['gap']:g} mm" if res["gap"] else "")+ + (f", accurate to {tol:g} mm" if tol else "") + "):")+ lines = [head + ("" if res["pairs"] else " none")]for p in res["pairs"]:- note = " (auch in der Lage im Modell)" if p["atRest"] else ""+ note = " (also in the assembled position)" if p["atRest"] else ""for r in p["ranges"]:span = f"{_t(r['start'])}-{_t(r['end'])} s" if r["end"] > r["start"] else f"{_t(r['start'])} s"- if r["kind"] != "Kollision":- val = f"Abstand bis {r['distance']:.3f} mm"+ if r["kind"] != COLLISION:+ val = f"distance down to {r['distance']:.3f} mm"elif r.get("depth"):- val = f"bis {r['depth']:.2f} mm tief" + (f", Ueberschneidung {r['volume']:.3f} mm3" if r.get("volume") else "")+ val = f"up to {r['depth']:.2f} mm deep" + (f", overlap {r['volume']:.3f} mm3" if r.get("volume") else "")else:- val = f"Ueberschneidung bis {r['volume']:.3f} mm3" if r.get("volume") else "Oberflaechen schneiden sich"+ val = f"overlap up to {r['volume']:.3f} mm3" if r.get("volume") else "surfaces intersect"lines.append(f" {span:<16} {p['a']} / {p['b']}: {r['kind']}, {val}{note}")contacts = res.get("contacts") or []if contacts:- names = ", ".join(f"{m} / {o}" for m, o in contacts[:6]) + (f" und {len(contacts) - 6} weitere" if len(contacts) > 6 else "")- lines.append(f"Beruehren sich schon im Modell (gewollt, gemeldet wird nur tieferes Eindringen): {names}")+ names = ", ".join(f"{m} / {o}" for m, o in contacts[:6]) + (f" and {len(contacts) - 6} more" if len(contacts) > 6 else "")+ lines.append(f"Already touching in the model (intended, only deeper penetration is reported): {names}")near = res.get("clearances") or []if near:- names = ", ".join(f"{m} / {o} {d:.2f} mm" for m, o, d in near[:6]) + (f" und {len(near) - 6} weitere" if len(near) > 6 else "")- lines.append(f"Schon im Modell naeher als {res['gap']:g} mm (gemeldet nur, wenn es enger wird): {names}")+ names = ", ".join(f"{m} / {o} {d:.2f} mm" for m, o, d in near[:6]) + (f" and {len(near) - 6} more" if len(near) > 6 else "")+ lines.append(f"Already closer than {res['gap']:g} mm in the model (reported only if it gets tighter): {names}")return "\n".join(lines)diff --git a/python/soma/build.py b/python/soma/build.pyindex e42010d..c74fc87 100644--- a/python/soma/build.py+++ b/python/soma/build.py@@ -21,6 +21,7 @@ DEFAULT_ENTRY = "model.py"# nur, wenn build.json diese Nummer traegt (app/src/main/build.ts, OUTPUT_FORMAT). Erhoehen, sobald sich daran etwas aendert,# das der Viewer braucht: dann baut die App jedes Projekt beim naechsten Oeffnen einmal neu.OUTPUT_FORMAT = 1+REFERENCE_GROUP = "Reference" # Baugruppe der Referenzteile in output/model.stepclass BuildError(Exception):@@ -86,7 +87,7 @@ def run_model(root, entry=None):script = (root / entry)if not script.is_file():raise BuildError(- f"Einstiegspunkt {entry!r} nicht gefunden. Lege {DEFAULT_ENTRY} an oder setze \"entry\" in .soma/project.json.",+ f"Entry point {entry!r} not found. Create {DEFAULT_ENTRY} or set \"entry\" in .soma/project.json.",kind="EntryMissing")global LAST_RUNregistry.REGISTRY.clear()@@ -100,7 +101,7 @@ def run_model(root, entry=None):raiseexcept SystemExit as e:if e.code not in (None, 0):- raise BuildError(f"model.py hat sich mit Code {e.code} beendet", file=entry, kind="SystemExit")+ raise BuildError(f"{entry} exited with code {e.code}", file=entry, kind="SystemExit")except BaseException as e: # auch KeyboardInterrupt/Fehler im Nutzercode sauber meldenraise _error_from_exception(e, root)finally:@@ -109,7 +110,7 @@ def run_model(root, entry=None):sys.path.pop(0)if not registry.REGISTRY:raise BuildError(- "Kein Bauteil registriert. Rufe add_part(name, objekt) fuer jedes Bauteil auf "+ "No part registered. Call add_part(name, obj) for every part ""(from soma import add_part).", file=entry, kind="NoParts")return list(registry.REGISTRY)@@ -149,14 +150,14 @@ def write_outputs(root, parts, project_name):timings = {}t = time.perf_counter()- # Gruppen werden Unterbaugruppen der STEP-Datei, Referenzen stehen unter "Referenz" (E34)- taken = {p["step_name"] for p in parts} | {"Referenz"}+ # Gruppen werden Unterbaugruppen der STEP-Datei, Referenzen stehen unter "Reference" (E34, vor E73 "Referenz")+ taken = {p["step_name"] for p in parts} | {REFERENCE_GROUP}root_name = registry.ascii_name(project_name)taken.add(root_name)asm = _assembly(root_name, [(p.get("group", ()), p) for p in parts if p["role"] != "reference"], taken)refs = [p for p in parts if p["role"] == "reference"]if refs:- asm.add(_assembly("Referenz", [(p.get("group", ()), p) for p in refs], taken), name="Referenz")+ asm.add(_assembly(REFERENCE_GROUP, [(p.get("group", ()), p) for p in refs], taken), name=REFERENCE_GROUP)(root / "output").mkdir(exist_ok=True)asm.export(str(root / "output" / "model.step"))timings["step"] = time.perf_counter() - t@@ -210,7 +211,7 @@ def run_build(project_dir):from . import envw = env.record_requirements(root)except Exception as e: # noqa: BLE001- w = f"requirements.txt konnte nicht aktualisiert werden: {type(e).__name__}: {e}"+ w = f"requirements.txt could not be updated: {type(e).__name__}: {e}"if w:result["warnings"].append(w)except BuildError as e:@@ -224,5 +225,5 @@ def run_build(project_dir):(root / ".soma").mkdir(exist_ok=True)(root / ".soma" / "build.json").write_text(json.dumps(result, indent=1, ensure_ascii=False), encoding="utf-8")except OSError as e:- result["warnings"].append(f"build.json konnte nicht geschrieben werden: {e}")+ result["warnings"].append(f"build.json could not be written: {e}")return resultdiff --git a/python/soma/cli.py b/python/soma/cli.pyindex 11f76fd..8eeda94 100644--- a/python/soma/cli.py+++ b/python/soma/cli.py@@ -1,4 +1,4 @@-"""Kommandozeile: `soma build`, `soma export`, `soma anim`, `soma analyze` und `soma render`."""+"""Command line: `soma build`, `soma export`, `soma anim`, `soma analyze` and `soma render`."""import argparseimport jsonimport os@@ -21,13 +21,13 @@ def _print_build(res, as_json, seconds):returnif res["status"] == "ok":n = len(res.get("parts", []))- print(f"Build ok: {n} Bauteil(e), {seconds:.1f} s -> output/model.step")+ print(f"Build ok: {n} part(s), {seconds:.1f} s -> output/model.step")for w in res.get("warnings", []):- print("Warnung:", w)+ print("Warning:", w)else:e = res["error"]where = f" ({e['file']}:{e['line']})" if e.get("file") and e.get("line") else (f" ({e['file']})" if e.get("file") else "")- print(f"Build FEHLER{where}: {e['message']}", file=sys.stderr)+ print(f"Build ERROR{where}: {e['message']}", file=sys.stderr)if e.get("traceback"):print(e["traceback"], file=sys.stderr)@@ -61,7 +61,7 @@ def _export_one(shape, fmt, path):w.AddShape(shape.wrapped)w.ComputeModel()if not w.Write(str(path)):- raise RuntimeError("IGES-Schreiben fehlgeschlagen")+ raise RuntimeError("Writing the IGES file failed")elif fmt == "obj":from . import build, mesherm = mesher.mesh_shape(shape, build.auto_tolerance([shape]), 0.3)@@ -70,32 +70,32 @@ def _export_one(shape, fmt, path):lines += [f"f {a}//{a} {b}//{b} {c}//{c}" for a, b, c in m["indices"] + 1]Path(path).write_text("\n".join(lines) + "\n")else:- raise ValueError(f"Format nicht unterstuetzt: {fmt}")+ raise ValueError(f"Format not supported: {fmt}")def cmd_export(args):root = Path(args.project).resolve()fmt = args.format.lower()if fmt not in EXPORT_FORMATS:- print(f"Format {fmt!r} nicht unterstuetzt. Moeglich: {', '.join(EXPORT_FORMATS)}", file=sys.stderr)+ print(f"Format {fmt!r} not supported. Supported: {', '.join(EXPORT_FORMATS)}", file=sys.stderr)return 2from . import buildtry:parts = build.run_model(root)except build.BuildError as e:- print(f"Export nicht moeglich, das Modell laesst sich nicht bauen: {e.message}", file=sys.stderr)+ print(f"Cannot export, the model does not build: {e.message}", file=sys.stderr)return 1if args.all:# Referenzen (E34) und Zukaufteile wie Schrauben (E48) gehoeren nicht zu --all, einzeln gehen siechosen = [p for p in parts if p["role"] not in ("reference", "hardware")]skipped = len(parts) - len(chosen)if skipped:- print(f"nicht exportiert: {skipped} Referenz- und Zukaufteil(e)")+ print(f"not exported: {skipped} reference and purchased part(s)")else:chosen = [p for p in parts if p["name"] == args.part or p["step_name"] == args.part]if not chosen:names = ", ".join(repr(p["name"]) for p in parts)- print(f"Bauteil {args.part!r} nicht gefunden. Registriert: {names}", file=sys.stderr)+ print(f"Part {args.part!r} not found. Registered: {names}", file=sys.stderr)return 1out_dir = root / (args.out or "exports")out_dir.mkdir(parents=True, exist_ok=True)@@ -104,9 +104,9 @@ def cmd_export(args):try:_export_one(p["shape"], fmt, path)# Im Projekt relativ (so liest es der Agent), ein Ziel ausserhalb (Speicherdialog der App) absolut- print(f"exportiert: {path.relative_to(root).as_posix() if path.is_relative_to(root) else path.as_posix()}")+ print(f"exported: {path.relative_to(root).as_posix() if path.is_relative_to(root) else path.as_posix()}")except Exception as e:- print(f"Export von {p['name']!r} als {fmt} fehlgeschlagen: {type(e).__name__}: {e}", file=sys.stderr)+ print(f"Export of {p['name']!r} as {fmt} failed: {type(e).__name__}: {e}", file=sys.stderr)return 1return 0@@ -117,10 +117,10 @@ def cmd_glb(args):try:parts = preview.step_to_glb(args.step, args.out)except Exception as e:- print(f"Umwandlung fehlgeschlagen: {type(e).__name__}: {e}", file=sys.stderr)+ print(f"Conversion failed: {type(e).__name__}: {e}", file=sys.stderr)return 1print(json.dumps(dict(status="ok", parts=[p["name"] for p in parts]), ensure_ascii=False) if args.json- else f"{len(parts)} Bauteil(e) nach {args.out}")+ else f"{len(parts)} part(s) to {args.out}")return 0@@ -137,10 +137,10 @@ def cmd_warm(args):argv = [str(a) for a in job["argv"]]cwd = str(job["cwd"])if not argv or argv[0] == "warm":- raise ValueError("kein Befehl")+ raise ValueError("no command")os.chdir(cwd)except (ValueError, KeyError, TypeError, OSError) as e:- return _fail(f"Ungueltiger Auftrag fuer den vorgewaermten Prozess: {type(e).__name__}: {e}")+ return _fail(f"Invalid job for the prewarmed process: {type(e).__name__}: {e}")# Wie bei `python -m soma` im Ordner des Auftrags: dieser Ordner vorn im Suchpfad (gestartet wurde in einem leeren Ordner)if sys.path and sys.path[0] in ("", START_DIR):sys.path[0] = os.getcwd()@@ -155,7 +155,7 @@ def cmd_env(args):"""Projektumgebung anlegen oder auf den Stand der Basis bringen (E67). Nur fuer die App: Sie ruft das beim Oeffnen."""from . import envres = env.ensure(args.project)- print(json.dumps(res, ensure_ascii=False) if args.json else (res.get("note") or res.get("error") or f"Projektumgebung: {res['env']}"))+ print(json.dumps(res, ensure_ascii=False) if args.json else (res.get("note") or res.get("error") or f"Project environment: {res['env']}"))return 0 if res["ok"] else 1@@ -182,22 +182,22 @@ def cmd_anim(args):if args.name and args.name.endswith(".py"):target = root / args.nameif not target.is_file():- return _fail(f"{args.name} gibt es nicht")+ return _fail(f"{args.name} does not exist")res = animrun.build_all(root, target)if args.json:print(json.dumps(dict(built=res["built"], errors=res["errors"]), ensure_ascii=False))else:for b in res["built"]:- print(f"Animation ok: \"{b['name']}\" ({b['duration']:.2f} s, {b['parts']} bewegte(s) Bauteil(e)) aus {b['file']}")+ print(f"Animation ok: \"{b['name']}\" ({b['duration']:.2f} s, {b['parts']} moving part(s)) from {b['file']}")for e in res["errors"]:where = f"{e['file']}{':' + str(e['line']) if e.get('line') else ''}"- print(f"Animation FEHLER ({where}): {e['message']}", file=sys.stderr)+ print(f"Animation ERROR ({where}): {e['message']}", file=sys.stderr)if e.get("traceback"):print(e["traceback"], file=sys.stderr)if not res["built"] and not res["errors"]:- print(f"Keine Animationen: Lege eine Datei in {animrun.ANIM_DIR}/ an (from soma.anim import Animation).")+ print(f"No animations: create a file in {animrun.ANIM_DIR}/ (from soma.anim import Animation).")if args.name and not args.name.endswith(".py") and not animrun.find(root, args.name):- return _fail(f"Keine Animation {args.name!r} gefunden")+ return _fail(f"No animation {args.name!r} found")return 1 if res["errors"] else 0if args.action == "list":idx = animrun.read_index(root)@@ -206,14 +206,14 @@ def cmd_anim(args):print(json.dumps(dict(animations=rows, errors=idx.get("errors", [])), ensure_ascii=False))return 0for x in rows:- print(f"\"{x['name']}\" {x['duration']:.2f} s {x['file']}{' (veraltet, soma anim build)' if x['stale'] else ''}")+ print(f"\"{x['name']}\" {x['duration']:.2f} s {x['file']}{' (outdated, soma anim build)' if x['stale'] else ''}")for e in idx.get("errors", []):- print(f"FEHLER {e['file']}{':' + str(e['line']) if e.get('line') else ''}: {e['message']}")+ print(f"ERROR {e['file']}{':' + str(e['line']) if e.get('line') else ''}: {e['message']}")if not rows and not idx.get("errors"):- print("Noch keine Animation gebaut (soma anim build).")+ print("No animation built yet (soma anim build).")return 0if not args.name:- return _fail(f"soma anim {args.action} braucht den Namen der Animation")+ return _fail(f"soma anim {args.action} needs the name of the animation")entry = animrun.ensure(root, args.name)if args.action == "info":if args.json:@@ -223,7 +223,7 @@ def cmd_anim(args):return 0res = animrun.check(root, args.name, step=args.step, gap=args.gap)print(json.dumps(res, ensure_ascii=False) if args.json else animrun.check_text(res))- return 1 if any(r["kind"] == "Kollision" and not p["atRest"] for p in res["pairs"] for r in p["ranges"]) else 0+ return 1 if any(r["kind"] == animrun.COLLISION and not p["atRest"] for p in res["pairs"] for r in p["ranges"]) else 0except animrun.AnimError as e:return _fail(str(e))@@ -240,17 +240,17 @@ def cmd_analyze(args):for m in res:print(f"{m['id']}: {m['title']} ({m['file']})")if not res:- print("Noch keine Ergebnisse (soma analyze overhang | thickness | clearance | fem <studie.py>).")+ print("No results yet (soma analyze overhang | thickness | clearance | fem <study.py>).")return 0try:if args.kind == "fem":from . import femif not args.study:- return _fail("soma analyze fem braucht die Datei mit dem Lastfall, z. B. soma analyze fem analyses/halter.py (Skill FEM)")+ return _fail("soma analyze fem needs the file with the load case, e.g. soma analyze fem analyses/bracket.py (skill \"Strength with FEM\")")meta = fem.run(root, args.study, args.name, args.threshold)else:if args.study:- return _fail(f"Unerwartete Angabe {args.study!r}: nur soma analyze fem nimmt eine Datei")+ return _fail(f"Unexpected argument {args.study!r}: only soma analyze fem takes a file")meta = analysis.run(root, args.kind, args.parts, args.threshold, args.up, args.name)except analysis.AnalysisError as e:return _fail(str(e))@@ -258,7 +258,7 @@ def cmd_analyze(args):print(json.dumps(meta, ensure_ascii=False))else:print(meta["summary"])- print(f"Ergebnis: {meta['file']}. Als Bild mit Farben: soma render --result {meta['id']}")+ print(f"Result: {meta['file']}. As a picture with colors: soma render --result {meta['id']}")return 0@@ -270,81 +270,81 @@ def cmd_render(args):job = render.prepare(root, args)res = render.send(job)except render.RenderError as e:- return _fail(f"Render FEHLER: {e}")+ return _fail(f"Render ERROR: {e}")if args.json:print(json.dumps(res, ensure_ascii=False))return 0for w in res.get("warnings", []):- print("Hinweis:", w)+ print("Note:", w)for f in res.get("files", []):- print(f"geschrieben: {f}")+ print(f"written: {f}")if job["kind"] == "video":- print("Das Video selbst kannst du nicht ansehen, die Uebersicht (PNG) zeigt Standbilder mit Zeitstempel.")+ print("You cannot watch the video itself, the contact sheet (PNG) shows stills with timestamps.")else:- print("Oeffne das Bild, um es anzusehen.")+ print("Open the picture to look at it.")return 0def main(argv=None):- ap = argparse.ArgumentParser(prog="soma", description="Hilfsprogramm von SOMA")+ ap = argparse.ArgumentParser(prog="soma", description="Helper tool of SOMA")ap.add_argument("--version", action="version", version=f"soma {__version__}")sub = ap.add_subparsers(dest="cmd", required=True)- b = sub.add_parser("build", help="model.py ausfuehren und STEP, GLB und Mapping schreiben")- b.add_argument("--project", default=".", help="Projektordner (Standard: aktueller Ordner)")- b.add_argument("--json", action="store_true", help="Ergebnis als JSON ausgeben")+ b = sub.add_parser("build", help="run model.py and write STEP, GLB and mapping")+ b.add_argument("--project", default=".", help="project folder (default: current folder)")+ b.add_argument("--json", action="store_true", help="print the result as JSON")b.set_defaults(func=cmd_build)- e = sub.add_parser("export", help="Einzelne Bauteile exportieren")+ e = sub.add_parser("export", help="export single parts")g = e.add_mutually_exclusive_group(required=True)- g.add_argument("part", nargs="?", help="Name des Bauteils")- g.add_argument("--all", action="store_true", help="alle Bauteile (ohne Referenz- und Zukaufteile)")+ g.add_argument("part", nargs="?", help="name of the part")+ g.add_argument("--all", action="store_true", help="all parts (without reference and purchased parts)")e.add_argument("--format", required=True, help=", ".join(EXPORT_FORMATS))- e.add_argument("--out", help="Zielordner, relativ zum Projekt oder absolut (Standard: exports)")+ e.add_argument("--out", help="target folder, relative to the project or absolute (default: exports)")e.add_argument("--project", default=".")e.set_defaults(func=cmd_export)- g = sub.add_parser("glb", help="STEP-Datei in GLB fuer den Viewer umwandeln (Basismodus)")- g.add_argument("step", help="STEP-Datei")- g.add_argument("--out", required=True, help="Zielordner (model.glb und model.map.json)")+ g = sub.add_parser("glb", help="convert a STEP file to GLB for the viewer (basic mode)")+ g.add_argument("step", help="STEP file")+ g.add_argument("--out", required=True, help="target folder (model.glb and model.map.json)")g.add_argument("--json", action="store_true")g.set_defaults(func=cmd_glb)- a = sub.add_parser("anim", help="Animationen aus animations/*.py bauen, auflisten, beschreiben, pruefen")+ a = sub.add_parser("anim", help="build, list, describe and check animations from animations/*.py")a.add_argument("action", choices=["build", "list", "info", "check"])- a.add_argument("name", nargs="?", help="Name der Animation (bei build auch eine Datei animations/x.py)")- a.add_argument("--step", type=float, default=0.1, help="check: Abstand der Zeitpunkte in Sekunden (Standard 0.1)")- a.add_argument("--gap", type=float, default=0.0, help="check: Mindestabstand in mm, darunter gilt es als zu nah")+ a.add_argument("name", nargs="?", help="name of the animation (for build also a file animations/x.py)")+ a.add_argument("--step", type=float, default=0.1, help="check: time between samples in seconds (default 0.1)")+ a.add_argument("--gap", type=float, default=0.0, help="check: minimum distance in mm, closer counts as too close")a.add_argument("--project", default=".")a.add_argument("--json", action="store_true")a.set_defaults(func=cmd_anim)- z = sub.add_parser("analyze", help="Auswertung: overhang (3D-Druck), thickness (Wandstaerke), clearance (Spalt zu anderen Teilen), fem (Festigkeit)")+ z = sub.add_parser("analyze", help="analysis: overhang (3D printing), thickness (wall thickness), clearance (gap to other parts), fem (strength)")z.add_argument("kind", choices=["overhang", "thickness", "clearance", "fem", "list"])- z.add_argument("study", nargs="?", help="fem: Datei mit dem Lastfall, z. B. analyses/halter.py")- z.add_argument("--parts", help="Bauteile oder Gruppen, mit Komma getrennt, \"Gruppe/\" immer die Gruppe (Standard: alle eigenen Teile)")- z.add_argument("--threshold", type=float, help="Grenzwert (Standard: overhang 45 Grad, thickness 1.2 mm, clearance 0.5 mm, fem der Sicherheitsfaktor der Studie)")- z.add_argument("--up", default="z", help="overhang: Druckrichtung (z, -z, x, -x, y, -y)")- z.add_argument("--name", help="Name des Ergebnisses (Standard: wie die Auswertung)")+ z.add_argument("study", nargs="?", help="fem: file with the load case, e.g. analyses/bracket.py")+ z.add_argument("--parts", help="parts or groups, separated by commas, \"Group/\" always means the group (default: all own parts)")+ z.add_argument("--threshold", type=float, help="limit (default: overhang 45 degrees, thickness 1.2 mm, clearance 0.5 mm, fem the safety factor of the study)")+ z.add_argument("--up", default="z", help="overhang: print direction (z, -z, x, -x, y, -y)")+ z.add_argument("--name", help="name of the result (default: like the analysis)")z.add_argument("--project", default=".")z.add_argument("--json", action="store_true")z.set_defaults(func=cmd_analyze)- r = sub.add_parser("render", help="Bild oder Video des Modells (ueber die App), nach renders/")- r.add_argument("--view", help="iso, front, back, left, right, top, bottom (Standard iso, bei Animationen ihre Kamera)")- r.add_argument("--size", help="Breite x Hoehe in Pixeln, z. B. 1280x800")- r.add_argument("--anim", help="Name einer Animation")- r.add_argument("--at", type=float, help="Zeitpunkt in der Animation (Sekunden)")- r.add_argument("--sheet", nargs="?", const=True, help="Uebersicht: Standbilder der Animation mit Zeit, z. B. 3x3")- r.add_argument("--video", action="store_true", help="Video (MP4) der Animation")- r.add_argument("--fps", type=int, default=30, help="Bilder je Sekunde im Video")- r.add_argument("--result", help="Ergebnis einer Auswertung (soma analyze) farbig zeigen")- r.add_argument("--out", help="Zieldatei im Projekt (Standard: renders/...)")+ r = sub.add_parser("render", help="picture or video of the model (through the app), to renders/")+ r.add_argument("--view", help="iso, front, back, left, right, top, bottom (default iso, for animations their camera)")+ r.add_argument("--size", help="width x height in pixels, e.g. 1280x800")+ r.add_argument("--anim", help="name of an animation")+ r.add_argument("--at", type=float, help="moment in the animation (seconds)")+ r.add_argument("--sheet", nargs="?", const=True, help="contact sheet: stills of the animation with time, e.g. 3x3")+ r.add_argument("--video", action="store_true", help="video (MP4) of the animation")+ r.add_argument("--fps", type=int, default=30, help="frames per second in the video")+ r.add_argument("--result", help="show the result of an analysis (soma analyze) in color")+ r.add_argument("--out", help="target file in the project (default: renders/...)")r.add_argument("--project", default=".")r.add_argument("--json", action="store_true")r.set_defaults(func=cmd_render)- s = sub.add_parser("serve", help="Messdienst fuer die App (JSON-Zeilen auf stdin/stdout)")+ s = sub.add_parser("serve", help="measuring service for the app (JSON lines on stdin/stdout)")s.set_defaults(func=cmd_serve)w = sub.add_parser("warm", help=argparse.SUPPRESS) # nur fuer die App: vorgewaermt auf einen Auftrag wartendiff --git a/python/soma/env.py b/python/soma/env.pyindex 6b805cf..64be0c6 100644--- a/python/soma/env.py+++ b/python/soma/env.py@@ -73,7 +73,7 @@ def ensure(project):App): Die alten Pakete laufen dort nicht, die Umgebung wird geleert und die App installiert requirements.txt neu."""env = env_dir(project)if _inside(sys.prefix, env):- return dict(ok=False, error="soma env muss mit dem Python der Basisumgebung laufen, nicht aus der Projektumgebung.")+ return dict(ok=False, error="soma env must run with the Python of the base environment, not from the project environment.")version = f"{sys.version_info[0]}.{sys.version_info[1]}"old = {}try:@@ -87,7 +87,7 @@ def ensure(project):try:venv.EnvBuilder(with_pip=False, clear=cleared, upgrade=exists and not cleared, symlinks=os.name != "nt").create(str(env))except Exception as e: # noqa: BLE001 (Rechte, volle Platte, fehlende venv-Dateien: melden)- return dict(ok=False, error=f"Die Projektumgebung liess sich nicht anlegen: {type(e).__name__}: {e}")+ return dict(ok=False, error=f"The project environment could not be created: {type(e).__name__}: {e}")sp = env_site(env)bases = _base_sites()@@ -110,10 +110,10 @@ def ensure(project):base_mtimes=[_mtime_ms(p) for p in bases], site=os.path.relpath(sp, env))(env / INFO).write_text(json.dumps(info, indent=1), encoding="utf-8", newline="\n")except OSError as e:- return dict(ok=False, error=f"Die Projektumgebung liess sich nicht einrichten: {e}")+ return dict(ok=False, error=f"The project environment could not be set up: {e}")res = dict(ok=True, env=str(env), site=str(sp), created=not exists, cleared=cleared)if cleared:- res["note"] = f"Die Projektumgebung war fuer Python {old.get('version')} und wurde fuer Python {version} neu angelegt."+ res["note"] = f"The project environment was for Python {old.get('version')} and was created again for Python {version}."return res@@ -183,7 +183,7 @@ def record_requirements(project):try:old = req.read_text(encoding="utf-8") if req.is_file() else Noneexcept (OSError, UnicodeDecodeError) as e:- return f"{REQUIREMENTS} ist nicht lesbar ({e}) und wurde nicht aktualisiert."+ return f"{REQUIREMENTS} is not readable ({e}) and was not updated."lines = {n: installed[n] for n in used}for name, line in _parse_requirements(old or ""):if name is None or name not in installed:@@ -195,5 +195,5 @@ def record_requirements(project):try:req.write_text(text, encoding="utf-8", newline="\n")except OSError as e:- return f"{REQUIREMENTS} konnte nicht geschrieben werden: {e}"+ return f"{REQUIREMENTS} could not be written: {e}"return Nonediff --git a/python/soma/fasteners.py b/python/soma/fasteners.pyindex 6d8f4f1..2a152b3 100644--- a/python/soma/fasteners.py+++ b/python/soma/fasteners.py@@ -1,22 +1,22 @@-"""Normteile: Schrauben, Muttern, Scheiben und Gewindeeinsaetze, vereinfacht ohne Gewinde, mit passenden Bohrungen.+"""Standard parts: screws, nuts, washers and heat-set inserts, simplified without threads, with matching holes.from soma import add_partfrom soma.fasteners import Screw- s = Screw("ISO 4762", "M3x10", at=(20, 15, 8)) # Kopf liegt bei z = 8 auf, der Schaft zeigt nach unten- lid = lid.cut(s.clearance_hole()) # Durchgangsloch, bei versenktem Kopf mit Senkung- add_part("Schraube 1", s) # Rolle "hardware" (Zukaufteil), nicht in export --all+ s = Screw("ISO 4762", "M3x10", at=(20, 15, 8)) # the head rests at z = 8, the shank points down+ lid = lid.cut(s.clearance_hole()) # clearance hole, with a counterbore for a sunk head+ add_part("Screw 1", s) # role "hardware" (purchased part), not in export --all-Lage, fuer alle Teile gleich: `at` ist der Punkt auf der Achse, an dem das Teil aufliegt. `direction` zeigt von dort-ins Material (Standard "-Z": von oben nach unten). Eine Schraube liegt mit der Kopfunterseite auf, eine Mutter oder-Scheibe mit einer Stirnseite. Senkschraube, Gewindestift und Gewindeeinsatz schliessen mit ihrer Oberseite an `at` ab.-`sunk=True` versenkt Kopf, Mutter oder Scheibe buendig (die Aussenseite liegt dann an `at`), `sunk=0.5` 0,5 mm tiefer.-`on=teil` sucht die Auflage selbst: Die Gerade durch `at` in Richtung `direction` trifft das Teil, der erste Treffer-gilt (bei "-Z" zaehlen dann nur x und y von `at`). `rotate()`, `translate()` und `moved()` wie bei CadQuery-Formen-liefern eine bewegte Kopie, etwa damit eine Schraube mit ihrem Teil in eine andere Stellung wandert.+Placement, the same for all parts: `at` is the point on the axis where the part rests. `direction` points from there+into the material (default "-Z": from top to bottom). A screw rests with the underside of its head, a nut or washer+with one of its faces. Countersunk screws, set screws and heat-set inserts end flush with their top at `at`.+`sunk=True` sinks the head, nut or washer flush (its outer side is then at `at`), `sunk=0.5` 0.5 mm deeper.+`on=part` finds the seat itself: the line through `at` in direction `direction` hits the part, the first hit counts+(with "-Z" only x and y of `at` matter). `rotate()`, `translate()` and `moved()` work as on CadQuery shapes and+return a moved copy, for example so that a screw moves with its part into another position.-Die Masse stammen aus den Tabellen von bd_warehouse (Apache 2.0, siehe data/fasteners/QUELLE.md), teils Nenn-, teils-Groesstmasse. Gewinde werden nicht modelliert: Schaft und Bohrung der Mutter haben den Nenndurchmesser.+Dimensions come from the tables of bd_warehouse (Apache 2.0, see data/fasteners/QUELLE.md), partly nominal, partly+maximum values. Threads are not modelled: the shank and the bore of the nut have the nominal diameter."""import copyimport csv@@ -52,40 +52,40 @@ COARSE_PITCH = {# Kopf: socket (Zylinderkopf), button (Linsenkopf), countersunk (Senkkopf), hex (Sechskant), set (Gewindestift)SCREWS = {- "iso4762": dict(name="ISO 4762", title="Zylinderschraube mit Innensechskant", table="socket_head_cap_parameters.csv",+ "iso4762": dict(name="ISO 4762", title="Socket head cap screw", table="socket_head_cap_parameters.csv",col="iso4762", head="socket", cols=("dk", "k", "s", "t")),- "iso7380": dict(name="ISO 7380", title="Linsenkopfschraube mit Innensechskant", table="button_head_parameters.csv",+ "iso7380": dict(name="ISO 7380", title="Button head socket screw", table="button_head_parameters.csv",col="iso7380_1", head="button", cols=("dk", "dl", "k", "rf", "s", "t")),- "iso10642": dict(name="ISO 10642", title="Senkschraube mit Innensechskant", table="countersunk_head_parameters.csv",+ "iso10642": dict(name="ISO 10642", title="Countersunk socket screw", table="countersunk_head_parameters.csv",col="iso10642", head="countersunk", cols=("a", "dk", "k", "s", "t")),- "iso4017": dict(name="ISO 4017", title="Sechskantschraube mit Gewinde bis Kopf", table="hex_head_parameters.csv",+ "iso4017": dict(name="ISO 4017", title="Hex head screw, fully threaded", table="hex_head_parameters.csv",col="iso4017", head="hex", cols=("k", "s")),- "iso4014": dict(name="ISO 4014", title="Sechskantschraube mit Schaft", table="hex_head_parameters.csv",+ "iso4014": dict(name="ISO 4014", title="Hex head bolt with shank", table="hex_head_parameters.csv",col="iso4014", head="hex", cols=("k", "s")),- "din931": dict(name="DIN 931", title="Sechskantschraube mit Schaft", table="hex_head_parameters.csv",+ "din931": dict(name="DIN 931", title="Hex head bolt with shank", table="hex_head_parameters.csv",col="din931", head="hex", cols=("k", "s")),- "iso4026": dict(name="ISO 4026", title="Gewindestift mit Innensechskant und Kegelstumpf", table="setscrew_parameters.csv",+ "iso4026": dict(name="ISO 4026", title="Socket set screw with flat point", table="setscrew_parameters.csv",col="iso4026", head="set", cols=("s", "t")),}NUTS = {- "iso4032": dict(name="ISO 4032", title="Sechskantmutter", table="hex_nut_parameters.csv", col="iso4032", shape="hex"),- "iso4033": dict(name="ISO 4033", title="Sechskantmutter, hoch", table="hex_nut_parameters.csv", col="iso4033", shape="hex"),- "iso4035": dict(name="ISO 4035", title="Sechskantmutter, flach", table="hex_nut_parameters.csv", col="iso4035", shape="hex"),- "din557": dict(name="DIN 557", title="Vierkantmutter", table="square_nut_parameters.csv", col="din557", shape="square"),+ "iso4032": dict(name="ISO 4032", title="Hex nut", table="hex_nut_parameters.csv", col="iso4032", shape="hex"),+ "iso4033": dict(name="ISO 4033", title="Hex nut, high", table="hex_nut_parameters.csv", col="iso4033", shape="hex"),+ "iso4035": dict(name="ISO 4035", title="Hex nut, thin", table="hex_nut_parameters.csv", col="iso4035", shape="hex"),+ "din557": dict(name="DIN 557", title="Square nut", table="square_nut_parameters.csv", col="din557", shape="square"),}WASHERS = {- "iso7089": dict(name="ISO 7089", title="Scheibe", table="plain_washer_parameters.csv", col="iso7089"),- "iso7091": dict(name="ISO 7091", title="Scheibe, grob", table="plain_washer_parameters.csv", col="iso7091"),- "iso7093": dict(name="ISO 7093", title="Scheibe, gross", table="plain_washer_parameters.csv", col="iso7093"),+ "iso7089": dict(name="ISO 7089", title="Washer", table="plain_washer_parameters.csv", col="iso7089"),+ "iso7091": dict(name="ISO 7091", title="Washer, coarse", table="plain_washer_parameters.csv", col="iso7091"),+ "iso7093": dict(name="ISO 7093", title="Washer, large", table="plain_washer_parameters.csv", col="iso7093"),}INSERT_BRANDS = {"ruthex": "ruthex", "cnckitchen": "CNCKitchen", "mcmaster": "McMaster-Carr", "mcmastercarr": "McMaster-Carr","hilitchi": "Hilitchi", "aesamzhihui": "AE-SamZhihui"}ALIASES = {"iso73801": "iso7380"}# Alte DIN-Bezeichnungen: melden statt still umdeuten, weil manche Masse abweichenHINTS = {- "din912": "ISO 4762", "din7380": "ISO 7380", "din7991": "ISO 10642 (Kopfhoehe weicht etwas ab)",- "din933": "ISO 4017 (bei M10, M12, M14 und M22 andere Schluesselweite als DIN 933)", "din913": "ISO 4026 (Ende anders)",- "din916": "ISO 4026 (Ende anders)", "din934": "ISO 4032 (bei M10, M12, M14 und M22 andere Schluesselweite als DIN 934)",+ "din912": "ISO 4762", "din7380": "ISO 7380", "din7991": "ISO 10642 (head height differs slightly)",+ "din933": "ISO 4017 (M10, M12, M14 and M22 have a different width across flats than DIN 933)", "din913": "ISO 4026 (different point)",+ "din916": "ISO 4026 (different point)", "din934": "ISO 4032 (M10, M12, M14 and M22 have a different width across flats than DIN 934)","din439": "ISO 4035", "din125": "ISO 7089", "din9021": "ISO 7093",}@@ -137,7 +137,7 @@ def _lookup(table, col, cols, d, what):rows = [r for r in _rows(table, col, cols) if abs(r[0] - d) < 1e-9]if not rows:sizes = sorted({r[0] for r in _rows(table, col, cols)})- raise ValueError(f"{what}: Groesse M{_fmt(d)} gibt es in der Tabelle nicht. Vorhanden: "+ raise ValueError(f"{what}: size M{_fmt(d)} is not in the table. Available: "+ ", ".join(f"M{_fmt(x)}" for x in sizes))coarse = [r for r in rows if r[1] is None or abs(r[1] - COARSE_PITCH.get(d, -1)) < 1e-9]return (coarse or rows)[0][3]@@ -150,15 +150,15 @@ def _fmt(x):def _norm_standard(standard, table, kind):if not isinstance(standard, str) or not standard.strip():- raise ValueError(f"{kind}: Norm als Text angeben, z. B. {next(iter(table.values()))['name']!r}")+ raise ValueError(f"{kind}: give the standard as text, e.g. {next(iter(table.values()))['name']!r}")key = re.sub(r"[\s_.-]", "", standard.lower())key = ALIASES.get(key, key)if key in table:return keyknown = ", ".join(v["name"] for v in table.values())if key in HINTS:- raise ValueError(f"{kind}: {standard!r} heisst heute {HINTS[key]}. Moeglich: {known}")- raise ValueError(f"{kind}: Norm {standard!r} gibt es hier nicht. Moeglich: {known}")+ raise ValueError(f"{kind}: {standard!r} is now called {HINTS[key]}. Available: {known}")+ raise ValueError(f"{kind}: there is no standard {standard!r} here. Available: {known}")_SIZE = re.compile(r"^\s*M\s*(\d+(?:[.,]\d+)?)\s*(?:[xX×*]\s*(\d+(?:[.,]\d+)?)\s*(?:mm)?)?\s*$", re.IGNORECASE)@@ -167,15 +167,15 @@ _SIZE = re.compile(r"^\s*M\s*(\d+(?:[.,]\d+)?)\s*(?:[xX×*]\s*(\d+(?:[.,]\d+)?)\def _parse_size(size, length, kind):""""M3" oder "M3x10" (auch "M3 x 10", "M3×10") -> (3.0, Laenge oder None)."""if not isinstance(size, str):- raise ValueError(f"{kind}: Groesse als Text angeben, z. B. \"M3\" oder \"M3x10\", nicht {size!r}")+ raise ValueError(f"{kind}: give the size as text, e.g. \"M3\" or \"M3x10\", not {size!r}")m = _SIZE.match(size)if not m:- raise ValueError(f"{kind}: Groesse {size!r} nicht lesbar. Erwartet z. B. \"M3\" oder \"M3x10\"")+ raise ValueError(f"{kind}: cannot read the size {size!r}. Expected e.g. \"M3\" or \"M3x10\"")d = _num(m.group(1))if m.group(2):from_size = _num(m.group(2))if length is not None and abs(float(length) - from_size) > 1e-9:- raise ValueError(f"{kind}: Laenge doppelt und verschieden angegeben ({size!r} und length={length})")+ raise ValueError(f"{kind}: length given twice with different values ({size!r} and length={length})")length = from_sizereturn d, (float(length) if length is not None else None)@@ -206,8 +206,8 @@ def _length_range(spec, d):def lengths(standard, size):- """Normlaengen einer Schraube in mm, z. B. lengths("ISO 4762", "M3") -> [5, 6, 8, 10, 12, 16, 20, 25, 30]."""- key = _norm_standard(standard, SCREWS, "Schraube")+ """Standard lengths of a screw in mm, e.g. lengths("ISO 4762", "M3") -> [5, 6, 8, 10, 12, 16, 20, 25, 30]."""+ key = _norm_standard(standard, SCREWS, "Screw")spec = SCREWS[key]d, _ = _parse_size(size, None, spec["name"])short, long_ = _length_range(spec, d)@@ -216,37 +216,38 @@ def lengths(standard, size):def pick_length(standard, size, min_length, max_length=None):- """Kuerzeste Normlaenge, die mindestens `min_length` lang ist (und hoechstens `max_length`, wenn angegeben)."""+ """Shortest standard length that is at least `min_length` (and at most `max_length`, if given)."""options = lengths(standard, size)fitting = [x for x in options if x >= min_length - 1e-9 and (max_length is None or x <= max_length + 1e-9)]if not fitting:- span = f"{_fmt(min_length)} bis {_fmt(max_length)}" if max_length is not None else f"mindestens {_fmt(min_length)}"- raise ValueError(f"{standard} {size}: keine Normlaenge {span} mm. Normlaengen: "+ span = f"{_fmt(min_length)} to {_fmt(max_length)}" if max_length is not None else f"of at least {_fmt(min_length)}"+ raise ValueError(f"{standard} {size}: no standard length {span} mm. Standard lengths: "+ ", ".join(_fmt(x) for x in options))return fitting[0]def standards():- """Was es gibt: {"Schrauben": {"ISO 4762": "Zylinderschraube ..."}, ...}."""+ """What is available: {"screws": {"ISO 4762": "Socket head cap screw", ...}, "nuts": ..., "washers": ...,+ "heat_set_inserts": [brands]}."""return {- "Schrauben": {v["name"]: v["title"] for v in SCREWS.values()},- "Muttern": {v["name"]: v["title"] for v in NUTS.values()},- "Scheiben": {v["name"]: v["title"] for v in WASHERS.values()},- "Gewindeeinsaetze": sorted(set(INSERT_BRANDS.values())),+ "screws": {v["name"]: v["title"] for v in SCREWS.values()},+ "nuts": {v["name"]: v["title"] for v in NUTS.values()},+ "washers": {v["name"]: v["title"] for v in WASHERS.values()},+ "heat_set_inserts": sorted(set(INSERT_BRANDS.values())),}def _clearance(d, fit):if fit not in FITS:- raise ValueError(f"fit muss einer von {tuple(FITS)} sein (ISO 273 fein, mittel, grob), nicht {fit!r}")+ raise ValueError(f"fit must be one of {tuple(FITS)} (ISO 273 fine, medium, coarse), not {fit!r}")rows = [r for r in _rows("clearance_hole_sizes.csv", None, (FITS[fit],)) if abs(r[0] - d) < 1e-9]if not rows:- raise ValueError(f"Fuer M{_fmt(d)} gibt es kein Durchgangsloch in der Tabelle")+ raise ValueError(f"The table has no clearance hole for M{_fmt(d)}")return rows[0][3][FITS[fit]]def _tap_drill(d):- return _lookup("tap_hole_sizes.csv", None, ("Soft",), d, "Kernloch")["Soft"]+ return _lookup("tap_hole_sizes.csv", None, ("Soft",), d, "Tap drill hole")["Soft"]@functools.cache@@ -270,26 +271,26 @@ def _vec(v, what):return cq.Vector(*v.toTuple())if isinstance(v, (tuple, list)) and len(v) == 3 and all(isinstance(x, numbers.Real) for x in v):return cq.Vector(*map(float, v))- raise ValueError(f"{what}: erwartet (x, y, z), nicht {v!r}")+ raise ValueError(f"{what}: expected (x, y, z), not {v!r}")def _direction(spec):if isinstance(spec, str):m = re.match(r"^\s*([+-]?)\s*([xyz])\s*$", spec, re.IGNORECASE)if not m:- raise ValueError(f"direction: erwartet \"-Z\", \"+X\" usw. oder (x, y, z), nicht {spec!r}")+ raise ValueError(f"direction: expected \"-Z\", \"+X\" etc. or (x, y, z), not {spec!r}")v = cq.Vector(*[(-1.0 if m.group(1) == "-" else 1.0) if a == m.group(2).lower() else 0.0 for a in "xyz"])else:v = _vec(spec, "direction")if v.Length < 1e-9:- raise ValueError("direction darf nicht (0, 0, 0) sein")+ raise ValueError("direction must not be (0, 0, 0)")return v.normalized()def _at(at, on):"""Punkt und (falls ableitbar) Richtung aus `at`: Tupel, Vector, Vertex, Location oder Workplane."""if at is None:- raise ValueError("at fehlt: der Punkt, an dem das Teil aufliegt, z. B. at=(10, 5, 8)")+ raise ValueError("at is missing: the point where the part rests, e.g. at=(10, 5, 8)")if isinstance(at, cq.Location):pos = cq.Vector(*at.toTuple()[0])z = gp_Dir(0, 0, 1).Transformed(at.wrapped.Transformation())@@ -300,10 +301,10 @@ def _at(at, on):return at.plane.origin, -at.plane.zDirif len(objs) == 1:return _at(objs[0], on)[0], -at.plane.zDir- raise ValueError(f"at: die Workplane traegt {len(objs)} Punkte. Je Teil einen Punkt uebergeben (Schleife ueber .vals())")+ raise ValueError(f"at: the Workplane holds {len(objs)} points. Pass one point per part (loop over .vals())")if isinstance(at, (tuple, list)) and len(at) == 2:if on is None:- raise ValueError("at braucht x, y und z. Nur (x, y) geht mit on=teil, dann wird die Auflage gesucht")+ raise ValueError("at needs x, y and z. Only (x, y) works with on=part, then the seat is searched for")return cq.Vector(float(at[0]), float(at[1]), 0.0), Nonereturn _vec(at, "at"), None@@ -314,13 +315,13 @@ def _shape_of(obj, what="on"):if isinstance(obj, cq.Workplane):vals = [v for v in obj.vals() if isinstance(v, cq.Shape)]if not vals:- raise ValueError(f"{what}: die Workplane enthaelt keine Geometrie")+ raise ValueError(f"{what}: the Workplane contains no geometry")return vals[0] if len(vals) == 1 else cq.Compound.makeCompound(vals)if isinstance(obj, cq.Assembly):return obj.toCompound()if isinstance(obj, cq.Shape):return obj- raise ValueError(f"{what}: erwartet ein Teil (cq.Workplane oder cq.Shape), nicht {type(obj).__name__}")+ raise ValueError(f"{what}: expected a part (cq.Workplane or cq.Shape), not {type(obj).__name__}")def _surface_hit(on, point, d):@@ -335,8 +336,8 @@ def _surface_hit(on, point, d):best = (inter.W(), cq.Vector(p.X(), p.Y(), p.Z()))inter.Next()if best is None:- raise ValueError(f"on: die Gerade durch {_pt(point)} in Richtung {_pt(d)} trifft das Teil nicht. "- "Pruefe at und direction")+ raise ValueError(f"on: the line through {_pt(point)} in direction {_pt(d)} does not hit the part. "+ "Check at and direction")return best[1]@@ -352,7 +353,7 @@ def _sink(sunk, kind):return 0.0if isinstance(sunk, numbers.Real) and sunk >= 0:return float(sunk)- raise ValueError(f"{kind}: sunk ist True, False oder eine Tiefe in mm (>= 0), nicht {sunk!r}")+ raise ValueError(f"{kind}: sunk is True, False or a depth in mm (>= 0), not {sunk!r}")class _Part:@@ -367,7 +368,7 @@ class _Part:if on is not None:point = _surface_hit(on, point, d)if not isinstance(angle, numbers.Real):- raise ValueError(f"angle: Drehung um die Achse in Grad, nicht {angle!r}")+ raise ValueError(f"angle: rotation about the axis in degrees, not {angle!r}")ref = cq.Vector(1, 0, 0) if abs(d.x) < 0.99 else cq.Vector(0, 1, 0)x = (ref - d * ref.dot(d)).normalized()n = -d # lokale Z-Achse@@ -386,26 +387,26 @@ class _Part:@propertydef direction(self):- """Einheitsvektor von der Auflage ins Material."""+ """Unit vector from the seat into the material."""return self._dir.toTuple()@propertydef seat(self):- """Punkt auf der Achse an der Auflage (Kopfunterseite, Stirnseite der Mutter)."""+ """Point on the axis at the seat (underside of the head, face of the nut)."""return self._local_point(0.0)@propertydef surface(self):- """Punkt auf der Achse an der Oberflaeche, auf der das Teil sitzt (`at`, mit on= der gefundene Punkt)."""+ """Point on the axis on the surface the part sits on (`at`, with on= the point found)."""return self._surface.toTuple()def point(self, distance):- """Punkt auf der Achse, `distance` mm von der Auflage ins Material (z. B. fuer die Mutter am anderen Ende)."""+ """Point on the axis, `distance` mm from the seat into the material (e.g. for the nut at the other end)."""return self._local_point(-float(distance))@propertydef shape(self):- """Das Teil als cq.Solid an seiner Lage."""+ """The part as a cq.Solid in its position."""return self._world(self._local())def __soma_shape__(self):@@ -415,9 +416,9 @@ class _Part:# Schraube mit ihrem Teil (etwa in eine andere Stellung), ohne sie dort neu anzulegen.def moved(self, loc):- """Kopie, um loc (cq.Location) bewegt, wie cq.Shape.moved()."""+ """Copy moved by loc (cq.Location), like cq.Shape.moved()."""if not isinstance(loc, cq.Location):- raise ValueError(f"moved() erwartet eine cq.Location, nicht {loc!r}")+ raise ValueError(f"moved() expects a cq.Location, not {loc!r}")t = loc.wrapped.Transformation()def pnt(v):@@ -435,22 +436,22 @@ class _Part:return newdef translate(self, vector):- """Kopie, um vector (x, y, z) verschoben, wie cq.Shape.translate()."""+ """Copy shifted by vector (x, y, z), like cq.Shape.translate()."""return self.moved(cq.Location(_vec(vector, "translate")))def rotate(self, startVector, endVector, angleDegrees):- """Kopie, um die Achse von startVector nach endVector gedreht (Grad), wie cq.Shape.rotate()."""+ """Copy rotated about the axis from startVector to endVector (degrees), like cq.Shape.rotate()."""p1, p2 = _vec(startVector, "rotate: startVector"), _vec(endVector, "rotate: endVector")if (p2 - p1).Length < 1e-9:- raise ValueError("rotate: startVector und endVector muessen verschieden sein (sie legen die Achse fest)")+ raise ValueError("rotate: startVector and endVector must differ (they define the axis)")if not isinstance(angleDegrees, numbers.Real):- raise ValueError(f"rotate: Winkel in Grad, nicht {angleDegrees!r}")+ raise ValueError(f"rotate: angle in degrees, not {angleDegrees!r}")t = gp_Trsf()t.SetRotation(gp_Ax1(gp_Pnt(*p1.toTuple()), gp_Dir(*(p2 - p1).toTuple())), math.radians(angleDegrees))return self.moved(cq.Location(t))def __repr__(self):- return f"<{self.designation} an {_pt(cq.Vector(*self.seat))}, Richtung {_pt(self._dir)}>"+ return f"<{self.designation} at {_pt(cq.Vector(*self.seat))}, direction {_pt(self._dir)}>"def _cyl(d, z0, z1):@@ -524,35 +525,35 @@ def _screw_local(head, d, length, pitch, dims):elif head == "hex":cap = _chamfered_hex(p["s"], p["k"], both=False)else:- raise ValueError(f"Kopfform {head!r} unbekannt")+ raise ValueError(f"Unknown head shape {head!r}")return _one(cap.fuse(shank))class Screw(_Part):- """Schraube ohne Gewinde. Screw("ISO 4762", "M3x10", at=(x, y, z)) oder Screw("ISO 4762", "M3", 10, at=...).-- standard "ISO 4762" (Zylinderkopf), "ISO 7380" (Linsenkopf), "ISO 10642" (Senkkopf), "ISO 4017", "ISO 4014",- "DIN 931" (Sechskant), "ISO 4026" (Gewindestift)- at Auflage der Kopfunterseite (Senkschraube, Gewindestift: Oberseite), (x, y, z) oder cq.Location- direction von der Auflage ins Material, Standard "-Z"- on Teil, auf dem die Schraube sitzt: Die Auflage wird entlang `direction` gesucht- sunk True: Kopf buendig in einer Senkung, 0.5: 0,5 mm tiefer. Senkschrauben sitzen immer buendig- angle Drehung um die Achse in Grad (Lage des Sechskants)- check_length False erlaubt Laengen, die keine Normlaenge sind+ """Screw without thread. Screw("ISO 4762", "M3x10", at=(x, y, z)) or Screw("ISO 4762", "M3", 10, at=...).++ standard "ISO 4762" (socket head), "ISO 7380" (button head), "ISO 10642" (countersunk), "ISO 4017", "ISO 4014",+ "DIN 931" (hex head), "ISO 4026" (set screw)+ at seat of the underside of the head (countersunk screw, set screw: the top), (x, y, z) or cq.Location+ direction from the seat into the material, default "-Z"+ on part the screw sits on: the seat is searched for along `direction`+ sunk True: head flush in a counterbore, 0.5: 0.5 mm deeper. Countersunk screws always sit flush+ angle rotation about the axis in degrees (orientation of the hex)+ check_length False allows lengths that are not standard lengths"""def __init__(self, standard, size=None, length=None, *, at=None, direction=None, on=None, sunk=False, angle=0.0,check_length=True):standard, size = _split_designation(standard, size)- self.standard_key = _norm_standard(standard, SCREWS, "Schraube")+ self.standard_key = _norm_standard(standard, SCREWS, "Screw")spec = SCREWS[self.standard_key]self.standard = spec["name"]self.d, length = _parse_size(size, length, spec["name"])if length is None:- raise ValueError(f"{spec['name']} M{_fmt(self.d)}: Laenge fehlt, z. B. \"M{_fmt(self.d)}x10\". "- f"Normlaengen: {', '.join(_fmt(x) for x in lengths(standard, size))}")+ raise ValueError(f"{spec['name']} M{_fmt(self.d)}: the length is missing, e.g. \"M{_fmt(self.d)}x10\". "+ f"Standard lengths: {', '.join(_fmt(x) for x in lengths(standard, size))}")if length <= 0:- raise ValueError(f"{spec['name']}: Laenge muss groesser als 0 sein")+ raise ValueError(f"{spec['name']}: the length must be greater than 0")self.dims = _lookup(spec["table"], spec["col"], spec["cols"], self.d, spec["name"])self.length = lengthself.head = spec["head"]@@ -560,10 +561,10 @@ class Screw(_Part):if check_length:options = lengths(standard, f"M{_fmt(self.d)}")if options and not any(abs(length - x) < 1e-9 for x in options):- raise ValueError(f"{self.designation}: {_fmt(length)} mm ist keine Normlaenge. Normlaengen: "- f"{', '.join(_fmt(x) for x in options)}. Sonderlaenge: check_length=False")+ raise ValueError(f"{self.designation}: {_fmt(length)} mm is not a standard length. Standard lengths: "+ f"{', '.join(_fmt(x) for x in options)}. Non-standard length: check_length=False")if self.head == "set" and length < self.dims["t"]:- raise ValueError(f"{self.designation}: kuerzer als der Innensechskant tief ist ({_fmt(self.dims['t'])} mm)")+ raise ValueError(f"{self.designation}: shorter than the depth of the hex socket ({_fmt(self.dims['t'])} mm)")sink = _sink(sunk, spec["name"])self.sunk = sink is not Noneif self.head in ("countersunk", "set"): # sitzen ohnehin im Material, `sunk` legt sie nur tiefer@@ -578,7 +579,7 @@ class Screw(_Part):@propertydef head_diameter(self):- """Kopfdurchmesser, beim Sechskant das Eckmass."""+ """Head diameter, for a hex head the width across corners."""if self.head == "hex":return self.dims["s"] / COS30return self.dims["dk"] if "dk" in self.dims else self.d@@ -591,17 +592,17 @@ class Screw(_Part):@propertydef key(self):- """Schluesselweite: Innensechskant oder Sechskant aussen."""+ """Width across flats: of the hex socket, or of the hex head."""return self.dims["s"]@propertydef tip(self):- """Punkt auf der Achse am Ende des Schafts."""+ """Point on the axis at the end of the shank."""return self.point(self.length)@propertydef outer(self):- """Punkt auf der Achse an der Kopfoberseite."""+ """Point on the axis at the top of the head."""return self._local_point(0.0 if self.head in ("countersunk", "set") else self.head_height)@property@@ -609,24 +610,24 @@ class Screw(_Part):return lengths(self.standard, f"M{_fmt(self.d)}")def clearance(self, fit="medium"):- """Durchmesser des Durchgangslochs nach ISO 273: fit "fine", "medium" oder "coarse"."""+ """Diameter of the clearance hole to ISO 273: fit "fine", "medium" or "coarse"."""return _clearance(self.d, fit)@propertydef tap_drill(self):- """Kernlochdurchmesser fuer das Regelgewinde."""+ """Tap drill diameter for the coarse thread."""return _tap_drill(self.d)def _local(self):return _screw_local(self.head, self.d, self.length, self.pitch, tuple(sorted(self.dims.items())))def clearance_hole(self, fit="medium", depth=None, oversize=0.0, recess=None):- """Werkzeug fuer cut(): Durchgangsloch, bei versenktem Kopf mit Senkung, bei Senkschrauben mit 90-Grad-Kegel.+ """Tool for cut(): clearance hole, with a counterbore for a sunk head, with a 90 degree cone for countersunk screws.- fit ISO 273: "fine", "medium" (Standard) oder "coarse"- depth Tiefe ab der Oberflaeche (`at`), Standard: bis 1 mm hinter das Schaftende- oversize zusaetzlich auf alle Durchmesser (3D-Druck: Loecher kommen kleiner heraus)- recess Durchmesser der Senkung statt Kopf + Spiel (z. B. Platz fuer einen Steckschluessel)+ fit ISO 273: "fine", "medium" (default) or "coarse"+ depth depth from the surface (`at`), default: to 1 mm beyond the end of the shank+ oversize added to all diameters (3D printing: holes come out smaller)+ recess diameter of the counterbore instead of head + clearance (e.g. room for a socket wrench)"""c0 = self.clearance(fit)c = c0 + oversize@@ -644,8 +645,8 @@ class Screw(_Part):return self._world(_one(tool))def tap_hole(self, depth=None, diameter=None, oversize=0.0):- """Werkzeug fuer cut(): Kernloch fuer ein Gewinde (oder zum Eindrehen in Kunststoff mit eigenem `diameter`).- depth: Tiefe ab der Oberflaeche, Standard bis 3 Steigungen hinter das Schaftende."""+ """Tool for cut(): tap drill hole for a thread (or for screwing into plastic with your own `diameter`).+ depth: depth from the surface, default to 3 pitches beyond the end of the shank."""dia = (diameter or self.tap_drill) + oversizebottom = self._zs - depth if depth is not None else -(self.length + 3 * self.pitch)return self._world(_cyl(dia, bottom, self._zs + MARGIN))@@ -663,22 +664,22 @@ def _nut_local(shape, d, m, s):class Nut(_Part):- """Mutter. Nut("ISO 4032", "M3", at=(x, y, z), direction="+Z"): liegt mit einer Stirnseite an `at`, `direction`- zeigt von dort ins Material (bei einer Mutter unter einer Platte also nach oben).+ """Nut. Nut("ISO 4032", "M3", at=(x, y, z), direction="+Z"): rests with one face at `at`, `direction` points+ from there into the material (so upwards for a nut under a plate).- standard "ISO 4032" (Sechskant), "ISO 4033" (hoch), "ISO 4035" (flach), "DIN 557" (Vierkant)- sunk True: buendig versenkt (aussen an `at`), 0.5: 0,5 mm tiefer. Die Tasche dafuer liefert trap()- angle Drehung um die Achse in Grad. Bei 0 liegen zwei Flaechen parallel zur X-Achse (bei Achse X: zur Y-Achse)+ standard "ISO 4032" (hex), "ISO 4033" (high), "ISO 4035" (thin), "DIN 557" (square)+ sunk True: sunk flush (outer side at `at`), 0.5: 0.5 mm deeper. trap() gives the pocket for it+ angle rotation about the axis in degrees. At 0 two flats are parallel to the X axis (for axis X: to the Y axis)"""def __init__(self, standard, size=None, *, at=None, direction=None, on=None, sunk=False, angle=0.0):standard, size = _split_designation(standard, size)- self.standard_key = _norm_standard(standard, NUTS, "Mutter")+ self.standard_key = _norm_standard(standard, NUTS, "Nut")spec = NUTS[self.standard_key]self.standard, self.shape_kind = spec["name"], spec["shape"]self.d, length = _parse_size(size, None, spec["name"])if length is not None:- raise ValueError(f"{spec['name']}: Muttern haben keine Laenge, nur \"M{_fmt(self.d)}\" angeben")+ raise ValueError(f"{spec['name']}: nuts have no length, give only \"M{_fmt(self.d)}\"")vals = _lookup(spec["table"], spec["col"], ("m", "s"), self.d, spec["name"])self.height, self.key = vals["m"], vals["s"]sink = _sink(sunk, spec["name"])@@ -697,10 +698,10 @@ class Nut(_Part):return _nut_local(self.shape_kind, self.d, self.height, self.key)def trap(self, clearance=0.2, slot=None, slot_length=None):- """Werkzeug fuer cut(): Tasche fuer die Mutter, `clearance` Spiel je Seite und in der Hoehe.+ """Tool for cut(): pocket for the nut, `clearance` per side and in height.- Versenkte Mutter: offen bis zur Oberflaeche. slot="+X" mit slot_length: Schlitz zum seitlichen Einschieben,- so breit wie die Mutter quer zum Schlitz (bei angle=0 und Achse Z ist das fuer "+X" die Schluesselweite).+ Sunk nut: open up to the surface. slot="+X" with slot_length: slot to insert the nut from the side, as wide as+ the nut across the slot (with angle=0 and axis Z that is the width across flats for "+X")."""sc = self.key + 2 * clearancetop = self._zs + MARGIN if self.sunk else self.height + clearance@@ -708,10 +709,10 @@ class Nut(_Part):cq.Solid.makeBox(sc, sc, top, cq.Vector(-sc / 2, -sc / 2, 0))if slot is not None:if not slot_length or slot_length <= 0:- raise ValueError("trap: slot braucht slot_length, die Laenge des Schlitzes ab der Achse in mm")+ raise ValueError("trap: slot needs slot_length, the length of the slot from the axis in mm")u = _direction(slot)if abs(u.dot(self._dir)) > 1e-6:- raise ValueError("trap: slot muss quer zur Achse der Mutter liegen")+ raise ValueError("trap: slot must be perpendicular to the axis of the nut")ux, uy = u.dot(self._plane.xDir), u.dot(self._plane.yDir)if self.shape_kind == "hex":corners = [(sc / COS30 / 2 * math.cos(math.radians(60 * i)), sc / COS30 / 2 * math.sin(math.radians(60 * i)))@@ -732,20 +733,20 @@ def _ring_local(d1, d2, h):class Washer(_Part):- """Scheibe. Washer("ISO 7089", "M3", at=(x, y, z)): liegt mit einer Seite an `at`, `outer` ist die andere Seite,- auf der dann Kopf oder Mutter sitzt.+ """Washer. Washer("ISO 7089", "M3", at=(x, y, z)): rests with one side at `at`, `outer` is the other side, where+ the head or nut then sits.- standard "ISO 7089" (normal), "ISO 7091" (grob), "ISO 7093" (gross)+ standard "ISO 7089" (normal), "ISO 7091" (coarse), "ISO 7093" (large)"""def __init__(self, standard, size=None, *, at=None, direction=None, on=None, sunk=False, angle=0.0):standard, size = _split_designation(standard, size)- self.standard_key = _norm_standard(standard, WASHERS, "Scheibe")+ self.standard_key = _norm_standard(standard, WASHERS, "Washer")spec = WASHERS[self.standard_key]self.standard = spec["name"]self.d, length = _parse_size(size, None, spec["name"])if length is not None:- raise ValueError(f"{spec['name']}: Scheiben haben keine Laenge, nur \"M{_fmt(self.d)}\" angeben")+ raise ValueError(f"{spec['name']}: washers have no length, give only \"M{_fmt(self.d)}\"")vals = _lookup(spec["table"], spec["col"], ("d1", "d2", "h"), self.d, spec["name"])self.inner, self.outer_diameter, self.thickness = vals["d1"], vals["d2"], vals["h"]sink = _sink(sunk, spec["name"])@@ -774,13 +775,13 @@ def _insert_local(d, s, m):class HeatSetInsert(_Part):- """Gewindeeinsatz zum Einschmelzen (3D-Druck). HeatSetInsert("M3x5.7", at=(x, y, z)): die Oberseite schliesst an- `at` ab, der Einsatz reicht in Richtung `direction` ins Material. hole() liefert die Bohrung dafuer.+ """Heat-set insert (3D printing). HeatSetInsert("M3x5.7", at=(x, y, z)): the top ends flush at `at`, the insert+ reaches into the material in direction `direction`. hole() gives the hole for it.- size "M3x5.7" (Gewinde x Laenge). Ohne Laenge nur, wenn es beim Hersteller nur eine gibt- brand "ruthex" (Standard), "CNCKitchen", "McMaster-Carr", "Hilitchi", "AE-SamZhihui"- variant bei gleicher Laenge, z. B. "Voron" (ruthex M3x4 mit 5 mm Aussendurchmesser)- sunk 0.5: Oberseite 0,5 mm unter `at`+ size "M3x5.7" (thread x length). Without a length only if the manufacturer has just one+ brand "ruthex" (default), "CNCKitchen", "McMaster-Carr", "Hilitchi", "AE-SamZhihui"+ variant for the same length, e.g. "Voron" (ruthex M3x4 with 5 mm outer diameter)+ sunk 0.5: top 0.5 mm below `at`"""color = BRASS@@ -789,14 +790,14 @@ class HeatSetInsert(_Part):angle=0.0):key = re.sub(r"[\s_.-]", "", str(brand).lower())if key not in INSERT_BRANDS:- raise ValueError(f"Gewindeeinsatz: Hersteller {brand!r} unbekannt. Moeglich: "+ raise ValueError(f"Heat-set insert: unknown brand {brand!r}. Available: "+ ", ".join(sorted(set(INSERT_BRANDS.values()))))self.brand = INSERT_BRANDS[key]- self.d, length = _parse_size(size, length, "Gewindeeinsatz")+ self.d, length = _parse_size(size, length, "Heat-set insert")rows = [r for r in _inserts(self.brand) if abs(r[0] - self.d) < 1e-9]if not rows:sizes = sorted({r[0] for r in _inserts(self.brand)})- raise ValueError(f"Gewindeeinsatz {self.brand}: M{_fmt(self.d)} gibt es nicht. Vorhanden: "+ raise ValueError(f"Heat-set insert {self.brand}: there is no M{_fmt(self.d)}. Available: "+ ", ".join(f"M{_fmt(x)}" for x in sizes))def label(r): # "5.7", "4 Voron": wie man die Auswahl nennt@@ -813,23 +814,23 @@ class HeatSetInsert(_Part):found = plain if len(plain) == 1 else foundif len(found) != 1:options = ", ".join(sorted({label(r) for r in rows}))- what = "passt keiner" if not found else "ist nicht eindeutig"- raise ValueError(f"Gewindeeinsatz {self.brand} M{_fmt(self.d)}: {what}. Laengen: {options} "- f"(z. B. \"M{_fmt(self.d)}x{label(rows[0]).split()[0]}\", Zusatz mit variant=)")+ what = "no length matches" if not found else "the length is ambiguous"+ raise ValueError(f"Heat-set insert {self.brand} M{_fmt(self.d)}: {what}. Lengths: {options} "+ f"(e.g. \"M{_fmt(self.d)}x{label(rows[0]).split()[0]}\", the extra with variant=)")row = found[0][3]self.variant = re.sub(r"^\d+(?:\.\d+)?", "", found[0][2]).strip(" -") or Noneself.diameter, self.length, self.part_number = row["s"], row["m"], row["part"]self.hole_diameter = _drill_mm(row["drill"])if self.hole_diameter is None or not self.d < self.hole_diameter < self.diameter:- raise ValueError(f"{self.designation}: die Tabelle nennt keine brauchbare Bohrung (Bohrer {row['drill']!r}). "- "Bohrung beim Hersteller nachsehen, den Einsatz selbst modellieren")- sink = _sink(sunk, "Gewindeeinsatz")+ raise ValueError(f"{self.designation}: the table gives no usable hole (drill {row['drill']!r}). "+ "Look up the hole at the manufacturer and model the insert yourself")+ sink = _sink(sunk, "Heat-set insert")self.sunk = sink is not Noneself._place(at, direction, on, angle, sink or 0.0)@propertydef designation(self):- return f"Gewindeeinsatz {self.brand} M{_fmt(self.d)}x{_fmt(self.length)}" + (f" {self.variant}" if self.variant else "")+ return f"Heat-set insert {self.brand} M{_fmt(self.d)}x{_fmt(self.length)}" + (f" {self.variant}" if self.variant else "")@propertydef outer(self):@@ -839,6 +840,6 @@ class HeatSetInsert(_Part):return _insert_local(self.d, self.diameter, self.length)def hole(self, extra_depth=1.0, oversize=0.0):- """Werkzeug fuer cut(): Bohrung fuer den Einsatz nach Herstellerangabe, `extra_depth` mm tiefer als der Einsatz- lang ist (Platz fuer verdraengten Kunststoff), `oversize` zusaetzlich auf den Durchmesser."""+ """Tool for cut(): hole for the insert as the manufacturer specifies, `extra_depth` mm deeper than the insert is+ long (room for displaced plastic), `oversize` added to the diameter."""return self._world(_cyl(self.hole_diameter + oversize, -(self.length + extra_depth), self._zs + MARGIN))diff --git a/python/soma/fem.py b/python/soma/fem.pyindex f00356a..fdca5c1 100644--- a/python/soma/fem.py+++ b/python/soma/fem.py@@ -1,18 +1,18 @@-"""`soma analyze fem <studie.py>`: Festigkeit mit der Finite-Elemente-Methode (E58, E65).+"""`soma analyze fem <study.py>`: strength with the finite element method (E58, E65).-Der Agent beschreibt den Lastfall in einer Python-Datei (analyses/<name>.py) mit `Study`: welche Bauteile, aus welchem-Werkstoff, wo sie gehalten werden und welche Lasten wo angreifen. Flaechen waehlt er mit CadQuery-Selektoren (">X") oder-einem Punkt in der Naehe. Gerechnet wird linear-elastisch:+The agent describes the load case in a Python file (analyses/<name>.py) with `Study`: which parts, of which material,+where they are held and which loads act where. Faces are chosen with CadQuery selectors (">X") or a point nearby.+The calculation is linear elastic:-- Netz: gmsh aus den BREP-Formen des Builds, quadratische Tetraeder (10 Knoten) auf der echten Geometrie. Mehrere Teile- werden zu einem durchgehenden Netz verschmolzen (fest verbunden, wo sie sich berühren).-- Steifigkeit selbst in numpy (vier Gausspunkte je Element), geloest mit pyamg (CG mit algebraischem Mehrgitter) oder- bei kleinen Netzen direkt.-- Ergebnis wie bei den anderen Auswertungen: .soma/results/<name>.glb mit dem Sicherheitsfaktor als _VALUE, dazu die- Vergleichsspannung (_STRESS) und die Verschiebung (_DISP) je Ecke und der Lastfall als Markierungen.+- Mesh: gmsh from the BREP shapes of the build, quadratic tetrahedra (10 nodes) on the real geometry. Several parts+ are fused into one continuous mesh (rigidly joined where they touch).+- Stiffness in numpy (four Gauss points per element), solved with pyamg (CG with algebraic multigrid) or directly for+ small meshes.+- Result as with the other analyses: .soma/results/<name>.glb with the safety factor as _VALUE, plus the von Mises+ stress (_STRESS) and the displacement (_DISP) per vertex, and the load case as markers.-Melden statt glauben: Die Rechnung prueft, ob jedes Teil gehalten ist, nennt die Lagerkräfte, rechnet ein zweites Mal mit-gröberem Netz und sagt, wenn die Höchstspannung davon abhaengt (scharfe Innenkante, Rand einer Einspannung).+Report instead of trust: the calculation checks that every part is held, gives the reaction forces, calculates a second+time with a coarser mesh and says when the peak stress depends on it (sharp inner edge, edge of a fixed support)."""import mathimport runpy@@ -42,8 +42,8 @@ MATERIALS = {"ASA": dict(E=2000, nu=0.35, strength=30, across=15, density=1.07),"PA": dict(E=1500, nu=0.39, strength=50, density=1.14),"POM": dict(E=3000, nu=0.35, strength=60, density=1.41),- "PMMA": dict(E=3200, nu=0.37, strength=60, density=1.19, note="spröde"),- "Plywood": dict(E=8000, nu=0.3, strength=40, density=0.70, note="Holz ist richtungsabhängig, gerechnet wie ein gleichmäßiger Werkstoff"),+ "PMMA": dict(E=3200, nu=0.37, strength=60, density=1.19, note="brittle"),+ "Plywood": dict(E=8000, nu=0.3, strength=40, density=0.70, note="wood depends on the grain direction, calculated as a uniform material"),"Aluminium 6082": dict(E=70000, nu=0.33, strength=250, density=2.70),"Steel S235": dict(E=210000, nu=0.3, strength=235, density=7.85),"Stainless 1.4301": dict(E=200000, nu=0.3, strength=210, density=7.90),@@ -54,27 +54,27 @@ ALIASES = {"nylon": "PA", "acrylic": "PMMA", "acryl": "PMMA", "sperrholz": "Plywdef material(spec, across_layers=True):- """Werkstoff aus Name oder dict(E=, nu=, strength=, density=). Liefert ein dict mit name, E, nu, strength, density, note."""+ """Material from a name or dict(E=, nu=, strength=, density=). Returns a dict with name, E, nu, strength, density, note."""if isinstance(spec, dict):missing = [k for k in ("E", "strength") if k not in spec]if missing:- raise FemError(f"Eigener Werkstoff braucht {', '.join(missing)} (MPa), z. B. dict(E=2500, nu=0.35, strength=40, density=1.2)")- m = dict(name=str(spec.get("name", "eigener Werkstoff")), E=float(spec["E"]), nu=float(spec.get("nu", 0.33)),+ raise FemError(f"A custom material needs {', '.join(missing)} (MPa), e.g. dict(E=2500, nu=0.35, strength=40, density=1.2)")+ m = dict(name=str(spec.get("name", "custom material")), E=float(spec["E"]), nu=float(spec.get("nu", 0.33)),strength=float(spec["strength"]), density=float(spec.get("density", 1.0)), note=spec.get("note"))else:key = str(spec).strip()found = next((k for k in MATERIALS if k.lower() == key.lower()), None) or ALIASES.get(key.lower())if not found:- raise FemError(f"Werkstoff {spec!r} kenne ich nicht. Bekannt: {', '.join(MATERIALS)}. "- "Oder eigener: material=dict(E=..., nu=..., strength=..., density=...) in MPa und g/cm³")+ raise FemError(f"Unknown material {spec!r}. Known: {', '.join(MATERIALS)}. "+ "Or a custom one: material=dict(E=..., nu=..., strength=..., density=...) in MPa and g/cm³")d = MATERIALS[found]strength, note = d["strength"], d.get("note")if "across" in d and across_layers:strength = d["across"]- note = f"gedruckt: Festigkeit quer zu den Schichten ({d['across']} statt {d['strength']} MPa)"+ note = f"printed: strength across the layers ({d['across']} instead of {d['strength']} MPa)"m = dict(name=found, E=float(d["E"]), nu=float(d["nu"]), strength=float(strength), density=float(d["density"]), note=note)if not (m["E"] > 0 and m["strength"] > 0 and 0 <= m["nu"] < 0.5):- raise FemError(f"Werkstoff {m['name']}: E und Festigkeit müssen positiv sein, nu zwischen 0 und 0.5")+ raise FemError(f"Material {m['name']}: E and strength must be positive, nu between 0 and 0.5")return m@@ -85,11 +85,11 @@ AXIS_NAMES = {"x": 0, "y": 1, "z": 2}class Study:- """Ein Lastfall. Einheiten: mm, N, MPa. Beispiel:+ """A load case. Units: mm, N, MPa. Example:- study = Study("Halter unter Last", material="PETG", safety=2)- study.fix("Halter", faces="<X")- study.force("Halter", faces=">X", N=(0, 0, -50))+ study = Study("Bracket under load", material="PETG", safety=2)+ study.fix("Bracket", faces="<X")+ study.force("Bracket", faces=">X", N=(0, 0, -50))"""def __init__(self, title, material="PLA", safety=2.0, mesh=None, across_layers=True, parts=None, check_mesh=True):@@ -107,36 +107,36 @@ class Study:_STUDIES.append(self)def set_material(self, part, material):- """Anderer Werkstoff fuer ein Bauteil (Standard: der der Studie)."""+ """Another material for one part (default: the material of the study)."""self.materials[str(part)] = materialreturn selfdef fix(self, part, faces=None, near=None, axes="xyz"):- """Flächen festhalten. axes="z": nur in Z gehalten, quer frei (Auflage, Gleitlager)."""+ """Hold faces fixed. axes="z": held only in Z, free across (a support, a sliding bearing)."""axes = str(axes).lower()if not axes or any(a not in AXIS_NAMES for a in axes):- raise FemError(f"fix(axes={axes!r}): nur x, y, z, z. B. axes=\"xyz\" oder axes=\"z\"")+ raise FemError(f"fix(axes={axes!r}): only x, y, z, e.g. axes=\"xyz\" or axes=\"z\"")self.bcs.append(dict(kind="fix", part=str(part), faces=faces, near=near, axes=axes, where=_caller()))return selfdef force(self, part, N, faces=None, near=None):- """Gesamtkraft in N als (Fx, Fy, Fz), gleichmaessig auf die gewaehlten Flaechen verteilt."""+ """Total force in N as (Fx, Fy, Fz), spread evenly over the chosen faces."""v = _vec(N, "force(N=...)")self.bcs.append(dict(kind="force", part=str(part), faces=faces, near=near, vector=v, where=_caller()))return selfdef pressure(self, part, MPa, faces=None, near=None):- """Druck in MPa (= N/mm²) senkrecht auf die Flaechen, positiv drueckt ins Material."""+ """Pressure in MPa (= N/mm²) normal to the faces, positive presses into the material."""self.bcs.append(dict(kind="pressure", part=str(part), faces=faces, near=near, value=float(MPa), where=_caller()))return selfdef gravity(self, g=9.81, direction="-z"):- """Eigengewicht aus der Dichte, g in m/s²."""+ """Self-weight from the density, g in m/s²."""d = str(direction).lower()sign = -1.0 if d.startswith("-") else 1.0ax = d.lstrip("+-")if ax not in AXIS_NAMES:- raise FemError(f"gravity(direction={direction!r}): x, y, z mit Vorzeichen, z. B. \"-z\"")+ raise FemError(f"gravity(direction={direction!r}): x, y, z with a sign, e.g. \"-z\"")v = [0.0, 0.0, 0.0]v[AXIS_NAMES[ax]] = sign * float(g)self.gravity_vec = v@@ -147,9 +147,9 @@ def _vec(v, what):try:out = [float(x) for x in v]except TypeError:- raise FemError(f"{what}: drei Zahlen (x, y, z) erwartet, nicht {v!r}") from None+ raise FemError(f"{what}: expected three numbers (x, y, z), not {v!r}") from Noneif len(out) != 3 or not all(math.isfinite(x) for x in out):- raise FemError(f"{what}: drei Zahlen (x, y, z) erwartet, nicht {v!r}")+ raise FemError(f"{what}: expected three numbers (x, y, z), not {v!r}")return out@@ -164,7 +164,7 @@ def load_study(root, rel):"""Fuehrt die Studiendatei aus und liefert die (letzte) Study darin."""path = (Path(root) / rel).resolve()if not path.is_file():- raise FemError(f"Studie {rel!r} nicht gefunden. Lege sie an, z. B. analyses/halter.py (siehe Skill FEM).")+ raise FemError(f"Study {rel!r} not found. Create it, e.g. analyses/bracket.py (see the skill \"Strength with FEM\").")_STUDIES.clear()old = Path.cwd()sys.path.insert(0, str(root))@@ -176,19 +176,19 @@ def load_study(root, rel):raise FemError(f"{rel}: {e}") from Noneexcept Exception as e: # Fehler im Code des Agenten: Zeile nennentb = [f for f in traceback.extract_tb(e.__traceback__) if Path(f.filename).resolve() == path]- at = f" (Zeile {tb[-1].lineno})" if tb else ""+ at = f" (line {tb[-1].lineno})" if tb else ""raise FemError(f"{rel}{at}: {type(e).__name__}: {e}") from Nonefinally:os.chdir(old)if sys.path and sys.path[0] == str(root):sys.path.pop(0)if not _STUDIES:- raise FemError(f"{rel} legt keine Studie an. Erwartet: from soma.fem import Study; study = Study(\"Titel\", material=\"PLA\")")+ raise FemError(f"{rel} creates no study. Expected: from soma.fem import Study; study = Study(\"Title\", material=\"PLA\")")st = _STUDIES[-1]if not any(b["kind"] == "fix" for b in st.bcs):- raise FemError(f"{rel}: Die Studie hält nichts fest. Mindestens ein study.fix(...) ist nötig.")+ raise FemError(f"{rel}: The study holds nothing fixed. At least one study.fix(...) is needed.")if not any(b["kind"] != "fix" for b in st.bcs) and st.gravity_vec is None:- raise FemError(f"{rel}: Die Studie hat keine Last. study.force(...), study.pressure(...) oder study.gravity().")+ raise FemError(f"{rel}: The study has no load. study.force(...), study.pressure(...) or study.gravity().")return st@@ -199,8 +199,8 @@ def _describe(bc):if bc.get("faces") is not None:sel.append(", ".join(bc["faces"]) if isinstance(bc["faces"], (list, tuple)) else str(bc["faces"]))if bc.get("near") is not None:- sel.append("nahe ({:g}, {:g}, {:g})".format(*bc["near"]))- return f"{bc['part']} {' '.join(sel) if sel else 'alle Flächen'}"+ sel.append("near ({:g}, {:g}, {:g})".format(*bc["near"]))+ return f"{bc['part']} {' '.join(sel) if sel else 'all faces'}"def _select(shape, bc):@@ -217,9 +217,9 @@ def _select(shape, bc):# Bei Tippfehlern liefert pyparsing die ganze Grammatik: nur die Stelle nennenmsg = str(e).splitlines()[0]if "Expected" in msg and "found" in msg:- msg = "kein gültiger CadQuery-Selektor" + (f" ({msg[msg.rfind('found'):]})" if len(msg) > 200 else f" ({msg})")- raise FemError(f"Selektor {s!r} für {bc['part']!r} geht nicht: {msg[:300]}. Beispiele: \">Z\", \"<X\", "- "\"%CYLINDER\", \">Z[-2]\", oder near=(x, y, z)") from None+ msg = "not a valid CadQuery selector" + (f" ({msg[msg.rfind('found'):]})" if len(msg) > 200 else f" ({msg})")+ raise FemError(f"Selector {s!r} for {bc['part']!r} does not work: {msg[:300]}. Examples: \">Z\", \"<X\", "+ "\"%CYLINDER\", \">Z[-2]\", or near=(x, y, z)") from Nonechosen += [f for f in got if not any(f.isSame(c) for c in chosen)]faces = chosennear = bc.get("near")@@ -231,11 +231,11 @@ def _select(shape, bc):best = min(dist)bb = shape.BoundingBox()if best > 0.05 * max(bb.DiagonalLength, 1.0):- raise FemError(f"Keine Fläche von {bc['part']!r} nahe {tuple(near)}: die nächste ist {best:.1f} mm entfernt")+ raise FemError(f"No face of {bc['part']!r} near {tuple(near)}: the nearest is {best:.1f} mm away")faces = [f for f, d in zip(faces, dist) if d <= best + 1e-6]if not faces:- raise FemError(f"{_describe(bc)}: keine Fläche gefunden. Der Selektor wählt am Teil {bc['part']!r}, "- f"in dessen Lage im Modell (z. B. \">Z\" oberste Fläche, \"<X\" in -X).")+ raise FemError(f"{_describe(bc)}: no face found. The selector picks on the part {bc['part']!r}, "+ f"in its position in the model (e.g. \">Z\" the top face, \"<X\" in -X).")return faces@@ -262,7 +262,7 @@ def _mesh(parts, bcs, h, progress=None):p["shape"].exportBrep(str(f))dt = [d for d in gmsh.model.occ.importShapes(str(f)) if d[0] == 3]if not dt:- raise FemError(f"{p['name']!r} ist kein Volumenkörper (nur Flächen oder Linien), so lässt es sich nicht rechnen.")+ raise FemError(f"{p['name']!r} is not a solid (only faces or lines), so it cannot be calculated.")vols.append(dt)owner = {}if len(parts) > 1:@@ -299,7 +299,7 @@ def _mesh(parts, bcs, h, progress=None):tets.append(t)epart.append(np.full(len(t), owner.get(vt, 0)))if not tets:- raise FemError("gmsh hat kein Volumennetz erzeugt (Form defekt oder zu klein?)")+ raise FemError("gmsh created no volume mesh (broken or too small shape?)")tets, epart = np.concatenate(tets), np.concatenate(epart)# Je Randbedingung die gmsh-Flaechen, die auf den gewaehlten CadQuery-Flaechen liegenimport cadquery as cq@@ -361,7 +361,7 @@ def _check_edges(nodes, tets):size = np.linalg.norm(x[:, a] - x[:, b], axis=1)ok = np.linalg.norm(x[:, 4 + k] - mid, axis=1) < 0.25 * size + 1e-9if ok.mean() < 0.9:- raise FemError("Unerwartete Knotenreihenfolge im Netz von gmsh (Kante %d). Bitte melden." % k)+ raise FemError("Unexpected node order in the gmsh mesh (edge %d). Please report this." % k)# ---- Elemente -----------------------------------------------------------------------------------------------------@@ -530,7 +530,7 @@ def _faces_area(nodes, tri6):# ---- Loesen --------------------------------------------------------------------------------------------------------MODE_NAMES = ["Verschiebung in X", "Verschiebung in Y", "Verschiebung in Z", "Drehung um X", "Drehung um Y", "Drehung um Z"]+MODE_NAMES = ["moving in X", "moving in Y", "moving in Z", "turning about X", "turning about Y", "turning about Z"]def _rigid_modes(x):@@ -565,7 +565,7 @@ def _check_held(nodes, tets, fixed, part_names, epart):dofs = (3 * nd[:, None] + np.arange(3)).reshape(-1)mask = fixed[dofs]if not mask.any():- problems.append(f"{', '.join(names)}: nicht gehalten (kein fix() an diesem Körper; berühren sich die Teile wirklich?)")+ problems.append(f"{', '.join(names)}: not held (no fix() on this body; do the parts really touch?)")continue_u, sv, vt = np.linalg.svd(R[mask], full_matrices=True)rank = int((sv > sv[0] * 1e-6).sum())@@ -573,10 +573,10 @@ def _check_held(nodes, tets, fixed, part_names, epart):free = []for v in vt[rank:]:free.append(MODE_NAMES[int(np.argmax(np.abs(v)))])- problems.append(f"{', '.join(names)}: noch frei beweglich ({', '.join(dict.fromkeys(free))})")+ problems.append(f"{', '.join(names)}: still free ({', '.join(dict.fromkeys(free))})")if problems:- raise FemError("Lagerung reicht nicht, die Teile können sich als Ganzes bewegen: " + "; ".join(problems)- + ". Mehr Flächen festhalten oder axes=\"xyz\" verwenden.")+ raise FemError("The supports are not enough, the parts can move as a whole: " + "; ".join(problems)+ + ". Fix more faces or use axes=\"xyz\".")def _solve(K, f, fixed, nodes):@@ -585,7 +585,7 @@ def _solve(K, f, fixed, nodes):Kff = K[free][:, free].tocsr()ff = f[free]u = np.zeros(len(f))- method = "direkt"+ method = "direct"if len(free) <= 12000: # SuperLU wird bei 3D-Netzen schnell langsam (36000 Unbekannte: 21 s), pyamg braucht dort 1 suf = spsolve(Kff.tocsc(), ff, permc_spec="MMD_AT_PLUS_A")else:@@ -595,12 +595,12 @@ def _solve(K, f, fixed, nodes):res = []uf = ml.solve(ff, tol=1e-8, accel="cg", maxiter=800, residuals=res)rel = res[-1] / max(res[0], 1e-30) if res else 1.0- method = f"pyamg, {len(res) - 1} Schritte"+ method = f"pyamg, {len(res) - 1} iterations"if not rel < 1e-6:- raise FemError(f"Der Löser kam nicht ans Ziel (Rest {rel:.1e}). Netz gröber (Study(mesh=...)) oder Lagerung prüfen.")+ raise FemError(f"The solver did not converge (residual {rel:.1e}). Use a coarser mesh (Study(mesh=...)) or check the supports.")u[free] = ufif not np.isfinite(u).all():- raise FemError("Die Rechnung lieferte keine Zahlen (Lagerung unzureichend?)")+ raise FemError("The calculation gave no numbers (supports insufficient?)")return u, method@@ -645,7 +645,7 @@ def _analyse(parts, study, mats, h, progress=None):progress.total += len(tets) # Fortschritt nach Elementen, sobald ihre Zahl bekannt istK, bad = _assemble(nodes, tets, D, progress)if bad:- raise FemError(f"{bad} verzerrte Elemente im Netz (sehr kleine oder spitze Stellen). Netz feiner wählen: Study(mesh=...)")+ raise FemError(f"{bad} distorted elements in the mesh (very small or sharp spots). Choose a finer mesh: Study(mesh=...)")el, k = _boundary(tets)tri6 = _tri6(nodes, tets, el, k)key = np.sort(tri6[:, :3], axis=1)@@ -662,7 +662,7 @@ def _analyse(parts, study, mats, h, progress=None):pos = np.clip(pos, 0, len(order) - 1)hit = order[pos][code[order][pos] == c]if not len(hit):- raise FemError(f"{_describe(bc)}: die Flächen liegen nicht außen am Netz (innen an einem anderen Teil?)")+ raise FemError(f"{_describe(bc)}: the faces are not on the outside of the mesh (inside, against another part?)")t6 = tri6[hit]out = dict(kind=bc["kind"], part=bc["part"], label=_describe(bc), tri=t6, el=el[hit])if bc["kind"] == "fix":@@ -716,12 +716,12 @@ def run(root, study_rel, name=None, threshold=None):try:all_parts = build.run_model(root)except build.BuildError as e:- raise FemError(f"Das Modell lässt sich nicht bauen: {e.message}" + (f" ({e.file}:{e.line})" if e.file and e.line else "")) from None+ raise FemError(f"The model does not build: {e.message}" + (f" ({e.file}:{e.line})" if e.file and e.line else "")) from Nonerel = Path(study_rel).as_posix()study = load_study(root, rel)safety = float(threshold) if threshold is not None else study.safetyif not safety > 0:- raise FemError("Der Sicherheitsfaktor muss größer als 0 sein")+ raise FemError("The safety factor must be greater than 0")by_name = {}for p in all_parts:by_name.setdefault(p["name"], p)@@ -729,7 +729,7 @@ def run(root, study_rel, name=None, threshold=None):missing = [w for w in wanted if w not in by_name]if missing:names = ", ".join(repr(p["name"]) for p in all_parts[:30])- raise FemError(f"Bauteil {missing[0]!r} gibt es nicht. Bauteile: {names}")+ raise FemError(f"There is no part {missing[0]!r}. Parts: {names}")parts = [by_name[w] for w in wanted]index = {p["name"]: i for i, p in enumerate(parts)}mats = [material(study.materials.get(p["name"], study.material_spec), study.across_layers) for p in parts]@@ -741,7 +741,7 @@ def run(root, study_rel, name=None, threshold=None):diag = float(np.linalg.norm(hi - lo))h = study.mesh or round(max(diag / 30, 0.3), 3)t_start = time.perf_counter()- progress = Progress("soma analyze fem", 1, "Elemente")+ progress = Progress("soma analyze fem", 1, "elements")fine = _analyse(parts, study, mats, h, progress)coarse = Noneif study.check_mesh:@@ -805,9 +805,9 @@ def _write(root, rel, study, all_parts, parts, mats, fine, coarse, h, diag, safest["coarse"] = dict(stress=round(c_max, 3), change=round(change, 4))flags = []if len(fixed_nodes) and np.min(np.linalg.norm(nodes[fixed_nodes] - nodes[w_s], axis=1)) < 1.5 * h:- flags.append("am Rand einer Einspannung")+ flags.append("at the edge of a fixed support")if len(load_nodes) and np.min(np.linalg.norm(nodes[load_nodes] - nodes[w_s], axis=1)) < 1.5 * h:- flags.append("an einer Lastfläche")+ flags.append("at a loaded face")st["peakAt"] = flagsstats.append(st)# Netz fuers Bild: die geschlossene Huelle des Teils. Wo es ein anderes Teil beruehrt, liegt die Flaeche im Ganzen innen und@@ -850,7 +850,7 @@ def _write(root, rel, study, all_parts, parts, mats, fine, coarse, h, diag, safeentry = dict(kind=b["kind"], part=b["part"], label=b["label"], area=round(float(b["area"]), 2), at=[round(float(x), 2) for x in c])hit, sel = b["match"]if sel > 0 and abs(hit - sel) > 0.02 * sel:- notes.append(f"{b['label']}: im Netz {hit:.1f} von {sel:.1f} mm² gefunden. Prüfe die Markierung im Bild.")+ notes.append(f"{b['label']}: found {hit:.1f} of {sel:.1f} mm² in the mesh. Check the marking in the picture.")if b["kind"] == "fix":entry["axes"] = b["axes"]entry["reaction"] = [round(float(x), 3) + 0.0 for x in b["reaction"]]@@ -861,18 +861,18 @@ def _write(root, rel, study, all_parts, parts, mats, fine, coarse, h, diag, safebcs_meta.append(entry)max_disp = float(disp.max())if max_disp > 0.05 * diag: # ab etwa 5 % der Modellgröße aendert die Verformung die Lastwege merklich- notes.append(f"Die Verformung ist groß ({max_disp:.2f} mm, {100 * max_disp / diag:.1f} % der Modellgröße). Die lineare "- "Rechnung gilt dann nur grob, echte Spannungen und Wege weichen ab.")+ notes.append(f"The deformation is large ({max_disp:.2f} mm, {100 * max_disp / diag:.1f} % of the model size). The linear "+ "calculation is then only a rough guide, real stresses and displacements differ.")for st in stats:ch = st.get("coarse", {}).get("change")- where = " und ".join(st["peakAt"])+ where = " and ".join(st["peakAt"])if ch is not None and abs(ch) > 0.15:- notes.append(f"{st['name']}: Die Höchstspannung haengt vom Netz ab ({st['coarse']['stress']:.1f} MPa grob, {st['stress']['value']:.1f} MPa fein)"- + (f", sie liegt {where}" if where else ", vermutlich an einer scharfen Innenkante")- + ". Dort ist der Wert nicht verlässlich: Radius vorsehen oder die Stelle mit etwas Abstand beurteilen.")+ notes.append(f"{st['name']}: The peak stress depends on the mesh ({st['coarse']['stress']:.1f} MPa coarse, {st['stress']['value']:.1f} MPa fine)"+ + (f", it is {where}" if where else ", probably at a sharp inner edge")+ + ". The value is not reliable there: add a radius or judge the spot from a little distance.")elif where:- notes.append(f"{st['name']}: Die Höchstspannung liegt {where}. Eine starre Einspannung oder eine Last auf kleiner Fläche "- "erzeugt dort oft eine zu hohe Spitze: Werte mit etwas Abstand davon beurteilen.")+ notes.append(f"{st['name']}: The peak stress is {where}. A rigid fixed support or a load on a small face "+ "often gives too high a peak there: judge values a little away from it.")if st["material"]["note"]:notes.append(f"{st['name']} ({st['material']['name']}): {st['material']['note']}")rid = name or Path(rel).stem@@ -883,7 +883,7 @@ def _write(root, rel, study, all_parts, parts, mats, fine, coarse, h, diag, safeapplied = fine["applied"]reaction = fine["reaction"]balance = float(np.linalg.norm(applied + reaction) / max(np.linalg.norm(applied), 1e-12))- meta = dict(version=1, id=rid, kind="fem", title=study.title, quantity="Sicherheit", unit="", bad="low", threshold=safety,+ meta = dict(version=1, id=rid, kind="fem", title=study.title, quantity="Safety factor", unit="", bad="low", threshold=safety,tolerance=None, range=rng, up=None, parts=stats, notes=list(dict.fromkeys(notes)), created=time.time(), neutral=None,seconds=round(seconds, 2),command=["analyze", "fem", rel] + ([f"--threshold={safety:g}"] if safety != study.safety else []) + ([f"--name={name}"] if name else []),@@ -910,36 +910,36 @@ def _v(v, unit="N"):def summary_text(meta):fe = meta["fem"]safety = meta["threshold"]- lines = [f"FEM \"{meta['title']}\" ({fe['study']}, linear-elastisch, Sicherheit {safety:g} gefordert, kritisch darunter):"]+ lines = [f"FEM \"{meta['title']}\" ({fe['study']}, linear elastic, safety factor {safety:g} required, critical below):"]for b in fe["bcs"]:if b["kind"] == "fix":- ax = "" if b["axes"] == "xyz" else f" nur in {', '.join(b['axes'].upper())}"- lines.append(f" fest{ax}: {b['label']} ({b['area']:.1f} mm²), Lagerkraft {_v(b['reaction'])}")+ ax = "" if b["axes"] == "xyz" else f" only in {', '.join(b['axes'].upper())}"+ lines.append(f" fixed{ax}: {b['label']} ({b['area']:.1f} mm²), reaction force {_v(b['reaction'])}")elif b["kind"] == "force":- lines.append(f" Kraft: {b['label']} ({b['area']:.1f} mm²), {_v(b['total'])}")+ lines.append(f" force: {b['label']} ({b['area']:.1f} mm²), {_v(b['total'])}")else:- lines.append(f" Druck: {b['label']} ({b['area']:.1f} mm²), {b['value']:g} MPa, zusammen {_v(b['total'])}")+ lines.append(f" pressure: {b['label']} ({b['area']:.1f} mm²), {b['value']:g} MPa, in total {_v(b['total'])}")if fe.get("gravity"):- lines.append(f" Eigengewicht: {_v(fe['gravity'], 'm/s²')}")+ lines.append(f" self-weight: {_v(fe['gravity'], 'm/s²')}")for st in meta["parts"]:mat = st["material"]s, d, w = st["stress"], st["displacement"], st["worst"]- crit = f"{st['critical'] / 100:.2f} cm² unter {safety:g}" if st["critical"] > 0 else f"nichts unter {safety:g}"- lines.append(f" {st['name']} ({mat['name']}, E {mat['E']:g} MPa, Festigkeit {mat['strength']:g} MPa): höchste Vergleichsspannung "- f"{s['value']:.1f} MPa bei {analysis._where(s['at'])}, kleinste Sicherheit {w['value']:.2f}, {crit}, "- f"größte Verschiebung {d['value']:.3f} mm bei {analysis._where(d['at'])}")+ crit = f"{st['critical'] / 100:.2f} cm² below {safety:g}" if st["critical"] > 0 else f"nothing below {safety:g}"+ lines.append(f" {st['name']} ({mat['name']}, E {mat['E']:g} MPa, strength {mat['strength']:g} MPa): highest von Mises stress "+ f"{s['value']:.1f} MPa at {analysis._where(s['at'])}, lowest safety factor {w['value']:.2f}, {crit}, "+ f"largest displacement {d['value']:.3f} mm at {analysis._where(d['at'])}")for r in st.get("regions", []):lines.append(f" {analysis._region_line(r, '')}")if st.get("regionsMore"):mo = st["regionsMore"]- lines.append(f" und {mo['count']} weitere Stelle{'n' if mo['count'] > 1 else ''}, zusammen {analysis._mm2(mo['area'])}")+ lines.append(f" and {mo['count']} more spot{'s' if mo['count'] > 1 else ''}, {analysis._mm2(mo['area'])} in total")m = fe["mesh"]- check = f"Netz {m['elements']} Tetraeder (10 Knoten, Kantenlänge bis {m['size']:g} mm), {m['dofs']} Unbekannte, {m['solver']}"+ check = f"Mesh {m['elements']} tetrahedra (10 nodes, edge length up to {m['size']:g} mm), {m['dofs']} unknowns, {m['solver']}"for st in meta["parts"]:if st.get("coarse"):- check += f"; {st['name']} mit gröberem Netz {st['coarse']['stress']:.1f} MPa ({round(100 * st['coarse']['change']) + 0:+d} % zum feinen)"- lines.append(f"Kontrolle: Lagerkräfte zusammen {_v(fe['reaction'])}, Lasten {_v(fe['applied'])}"- f"{' (im Gleichgewicht)' if fe['balance'] < 1e-3 else f' (Abweichung {100 * fe['balance']:.2f} %)'}. {check}.")+ check += f"; {st['name']} with a coarser mesh {st['coarse']['stress']:.1f} MPa (fine mesh {round(100 * st['coarse']['change']) + 0:+d} %)"+ lines.append(f"Check: reaction forces in total {_v(fe['reaction'])}, loads {_v(fe['applied'])}"+ f"{' (in equilibrium)' if fe['balance'] < 1e-3 else f' (deviation {100 * fe['balance']:.2f} %)'}. {check}.")for n in meta.get("notes") or []:- lines.append(f"Hinweis: {n}")+ lines.append(f"Note: {n}")return "\n".join(lines)diff --git a/python/soma/gltf.py b/python/soma/gltf.pyindex a1ad789..2bfc051 100644--- a/python/soma/gltf.py+++ b/python/soma/gltf.py@@ -108,8 +108,8 @@ def read_json(path):with open(path, "rb") as f:magic, _version, _total = struct.unpack("<III", f.read(12))if magic != 0x46546C67:- raise ValueError(f"{path} ist keine GLB-Datei")+ raise ValueError(f"{path} is not a GLB file")length, kind = struct.unpack("<II", f.read(8))if kind != 0x4E4F534A:- raise ValueError(f"{path}: JSON-Teil fehlt")+ raise ValueError(f"{path}: the JSON chunk is missing")return json.loads(f.read(length).decode("utf-8"))diff --git a/python/soma/measure.py b/python/soma/measure.pyindex 624343d..3b3c043 100644--- a/python/soma/measure.py+++ b/python/soma/measure.py@@ -52,11 +52,11 @@ class Model:try:self.map = json.loads((folder / "model.map.json").read_text(encoding="utf-8"))except (OSError, ValueError) as e:- raise MeasureError(f"model.map.json fehlt oder ist unlesbar: {e}")+ raise MeasureError(f"model.map.json is missing or unreadable: {e}")self.build = self.map.get("build")brep = folder / "geometry" / f"{self.build}.brep"if not self.build or not brep.is_file():- raise MeasureError("Zu diesem Stand gibt es keine Geometrie zum Messen. Einmal neu bauen hilft.")+ raise MeasureError("There is no geometry to measure for this version. Building it once more helps.")comp = cq.Shape.importBrep(str(brep))it = TopoDS_Iterator(comp.wrapped)self.shapes = []@@ -66,28 +66,28 @@ class Model:self.parts = {p["id"]: i for i, p in enumerate(self.map.get("parts", []))}self.names = {p["id"]: p.get("name", p["id"]) for p in self.map.get("parts", [])}if len(self.shapes) != len(self.parts):- raise MeasureError("Geometrie und Bauteilliste passen nicht zusammen. Einmal neu bauen hilft.")+ raise MeasureError("Geometry and part list do not match. Building it once more helps.")self._cache = {"face": {}, "edge": {}, "vertex": {}}def shape(self, part):if part not in self.parts:- raise MeasureError(f"Unbekanntes Bauteil {part!r}.", stale=True)+ raise MeasureError(f"Unknown part {part!r}.", stale=True)return self.shapes[self.parts[part]]def sub(self, ent):"""Flaeche, Kante oder Eckpunkt eines Bauteils. Prueft Flaecheninhalt, Laenge bzw. Lage gegen den Viewer."""part, kind, i = ent["part"], ent["kind"], int(ent["id"])if kind not in self._cache:- raise MeasureError(f"Unbekannte Art {kind!r}.")+ raise MeasureError(f"Unknown kind {kind!r}.")cache = self._cache[kind]if part not in cache:s = self.shape(part)cache[part] = s.Faces() if kind == "face" else s.Edges() if kind == "edge" else s.Vertices()items = cache[part]if not 0 <= i < len(items):- raise MeasureError("Diese Stelle gibt es im aktuellen Stand nicht mehr.", stale=True)+ raise MeasureError("This spot no longer exists in the current version.", stale=True)sub = items[i]- stale = MeasureError("Die Geometrie passt nicht zum angezeigten Stand. Bitte neu anklicken.", stale=True)+ stale = MeasureError("The geometry does not match the version shown. Please click again.", stale=True)if kind == "vertex":pt = ent.get("point")if pt is not None and math.dist(sub.toTuple(), [float(x) for x in pt]) > 1e-3:@@ -135,7 +135,7 @@ def _dist(a, b):"""Kuerzester Abstand zweier Formen mit den beiden naechsten Punkten."""d = BRepExtrema_DistShapeShape(a, b)if not d.IsDone() or d.NbSolution() < 1:- raise MeasureError("Der Abstand liess sich nicht bestimmen.")+ raise MeasureError("The distance could not be determined.")return d.Value(), _xyz(d.PointOnShape1(1)), _xyz(d.PointOnShape2(1))@@ -296,7 +296,7 @@ def serve(stdin=sys.stdin, stdout=sys.stdout):folder = str(req["folder"])current = json.loads((Path(folder) / "model.map.json").read_text(encoding="utf-8")).get("build")if req.get("build") and req["build"] != current:- raise MeasureError("Das Modell wurde inzwischen neu gebaut. Bitte neu anklicken.", stale=True)+ raise MeasureError("The model has been rebuilt in the meantime. Please click again.", stale=True)m = models.get(folder)if m is None or m.build != current:m = models[folder] = Model(folder)diff --git a/python/soma/preview.py b/python/soma/preview.pyindex 5e560ca..0c413f5 100644--- a/python/soma/preview.py+++ b/python/soma/preview.py@@ -25,7 +25,7 @@ def step_to_glb(step_path, out_dir):"""Schreibt <out_dir>/model.glb und model.map.json. Liefert die Bauteilliste."""step_path, out = Path(step_path), Path(out_dir)if not step_path.is_file():- raise FileNotFoundError(f"STEP-Datei nicht gefunden: {step_path}")+ raise FileNotFoundError(f"STEP file not found: {step_path}")out.mkdir(parents=True, exist_ok=True)assy = cq.Assembly.importStep(str(step_path))items = []@@ -35,13 +35,13 @@ def step_to_glb(step_path, out_dir):items.append((name, shape, color.toTuple() if color is not None else (0.62, 0.66, 0.72, 1.0)))groups.append("/".join(grp) or None)if not items:- raise ValueError("Die STEP-Datei enthaelt keine Geometrie")+ raise ValueError("The STEP file contains no geometry")tol = build.auto_tolerance([s for _, s, _ in items])build_id = uuid.uuid4().hexmeasure.write_geometry(out, [s for _, s, _ in items], build_id) # damit sich auch alte Staende vermessen lassenglb_parts, map_parts = [], []for i, (name, shape, rgba) in enumerate(items):- name = name or f"Teil {i + 1}"+ name = name or f"Part {i + 1}"pid = f"{i}:{name}"bb = shape.BoundingBox()map_parts.append(dict(id=pid, name=name, role="basic", group=groups[i],diff --git a/python/soma/progress.py b/python/soma/progress.pyindex 902f038..9458a6d 100644--- a/python/soma/progress.py+++ b/python/soma/progress.py@@ -15,7 +15,7 @@ def _dur(s):class Progress:- def __init__(self, what, total, unit="Schritte", after=5.0, every=15.0):+ def __init__(self, what, total, unit="steps", after=5.0, every=15.0):self.what, self.total, self.unit = what, max(1, int(total)), unitself.after, self.every = after, everyself.done = 0@@ -30,11 +30,11 @@ class Progress:returnself.last = nowrest = elapsed / max(self.done, 1) * (self.total - self.done)- self._say(f"{self.what}: {self.done} von {self.total} {self.unit}, noch etwa {_dur(rest)}")+ self._say(f"{self.what}: {self.done} of {self.total} {self.unit}, about {_dur(rest)} left")def finish(self):if self.last is not None:- self._say(f"{self.what}: fertig nach {_dur(time.perf_counter() - self.start)}")+ self._say(f"{self.what}: done after {_dur(time.perf_counter() - self.start)}")@staticmethoddef _say(text):diff --git a/python/soma/registry.py b/python/soma/registry.pyindex eb3aad2..dce3ec1 100644--- a/python/soma/registry.py+++ b/python/soma/registry.py@@ -1,4 +1,4 @@-"""Bauteil-Registrierung: add_part merkt sich Objekt, Rolle, Farbe sowie Datei und Zeilenbereich des Aufrufs."""+"""Part registry: add_part records the object, role and color plus the file and line range of the call."""import inspectimport mathimport unicodedata@@ -30,11 +30,11 @@ def to_shape(obj):if isinstance(obj, cq.Workplane):vals = obj.vals()if not vals:- raise ValueError("Die Workplane ist leer (keine Geometrie). Pruefe die Operationen davor.")+ raise ValueError("The Workplane is empty (no geometry). Check the operations before it.")return vals[0] if len(vals) == 1 else cq.Compound.makeCompound(vals)if isinstance(obj, cq.Shape):return obj- raise TypeError(f"add_part erwartet cq.Workplane, cq.Shape oder ein Normteil aus soma.fasteners, nicht {type(obj).__name__}")+ raise TypeError(f"add_part expects a cq.Workplane, a cq.Shape or a standard part from soma.fasteners, not {type(obj).__name__}")def _group_path(group):@@ -42,7 +42,7 @@ def _group_path(group):if group is None:return ()if not isinstance(group, str):- raise ValueError("group muss ein Text sein, z. B. \"Gehaeuse\" oder \"Gehaeuse/Schrauben\"")+ raise ValueError("group must be a text, e.g. \"Housing\" or \"Housing/Screws\"")return tuple(s.strip() for s in group.split("/") if s.strip())@@ -67,17 +67,17 @@ def _unique(name, taken):def add_part(name, obj, role=None, color=None, group=None):- """Registriert ein Bauteil. Pflicht fuer jedes Bauteil, sonst kennen Viewer und Export es nicht.-- name eindeutiger Name (Umlaute erlaubt, in der STEP-Datei wird er als ASCII geschrieben)- obj cq.Workplane oder cq.Shape, ein Normteil aus soma.fasteners (Screw, Nut ...) oder eine Baugruppe aus- import_assembly(): Dann wird jeder Koerper ein eigenes Bauteil mit seinem Namen und seiner Farbe, die- Unterbaugruppen werden Gruppen unter `name`- role "part" (eigenes Teil, Standard), "reference" (mitgebrachtes Teil: halbtransparent, eigener Ast, nicht im- Export) oder "hardware" (Zukaufteil wie Schrauben: deckend, in der STEP bei seiner Gruppe, nicht in- export --all). Normteile aus soma.fasteners sind ohne Angabe "hardware"- color optional (r, g, b) mit Werten 0..1 (bei einer Baugruppe fuer alle Teile). Normteile haben eine eigene- group optional, Gruppe im Bauteilbaum und in der STEP-Datei, verschachtelt mit "/", z. B. "Gehaeuse/Schrauben"+ """Registers a part. Required for every part, otherwise the viewer and the export do not know it.++ name unique name (any characters, in the STEP file it is written as ASCII)+ obj cq.Workplane or cq.Shape, a standard part from soma.fasteners (Screw, Nut ...) or an assembly from+ import_assembly(): then every body becomes a part of its own with its name and color, the+ sub-assemblies become groups under `name`+ role "part" (own part, default), "reference" (part brought along: semi-transparent, own branch, not in the+ export) or "hardware" (purchased part like screws: opaque, in the STEP file with its group, not in+ export --all). Standard parts from soma.fasteners are "hardware" if not given+ color optional (r, g, b) with values 0..1 (for an assembly for all parts). Standard parts have their own+ group optional, group in the part tree and in the STEP file, nested with "/", e.g. "Housing/Screws""""if IGNORE_ADD:return@@ -87,9 +87,9 @@ def add_part(name, obj, role=None, color=None, group=None):if color is None and standard_part:color = getattr(obj, "color", None)if role not in ROLES:- raise ValueError(f"role muss einer von {ROLES} sein, nicht {role!r}")+ raise ValueError(f"role must be one of {ROLES}, not {role!r}")if not isinstance(name, str) or not name.strip():- raise ValueError("Der Bauteilname muss ein nichtleerer Text sein")+ raise ValueError("The part name must be a non-empty text")groups = _group_path(group)frame = inspect.currentframe().f_backpos = inspect.getframeinfo(frame, context=0).positions # Startzeile und Endzeile des Aufrufs@@ -97,7 +97,7 @@ def add_part(name, obj, role=None, color=None, group=None):if isinstance(obj, cq.Assembly):leaves = list(_leaves(obj, cq.Location(), (), None))if not leaves:- raise ValueError(f"Die Baugruppe fuer {name!r} enthaelt keine Geometrie")+ raise ValueError(f"The assembly for {name!r} contains no geometry")if len(leaves) == 1: # nur ein Koerper: ein Bauteil unter dem angegebenen Namen, ohne eigene Gruppe_, _, o, c, loc = leaves[0]_register(name, to_shape(o).moved(loc), role, color or (c.toTuple()[:3] if c else None), groups, where)@@ -106,12 +106,12 @@ def add_part(name, obj, role=None, color=None, group=None):for sub_groups, leaf_name, o, c, loc in leaves:# Die oberste Baugruppe traegt den Namen aus add_part, darunter die Namen aus der Dateipath = groups + (name,) + sub_groups[1:]- nm = _unique(leaf_name or "Teil", taken)+ nm = _unique(leaf_name or "Part", taken)taken.add(nm)_register(nm, to_shape(o).moved(loc), role, color or (c.toTuple()[:3] if c else None), path, where, unique_step=True)returnif any(p["name"] == name for p in REGISTRY):- raise ValueError(f"Bauteilname {name!r} ist schon vergeben (Namen muessen eindeutig sein)")+ raise ValueError(f"Part name {name!r} is already taken (names must be unique)")_register(name, to_shape(obj), role, color, groups, where, axis=_axis(obj))@@ -134,7 +134,7 @@ def _register(name, shape, role, color, groups, where, unique_step=False, axis=Nstep_name = ascii_name(name)if any(p["step_name"] == step_name for p in REGISTRY):if not unique_step:- raise ValueError(f"Bauteilname {name!r} ergibt den STEP-Namen {step_name!r}, der schon vergeben ist")+ raise ValueError(f"Part name {name!r} gives the STEP name {step_name!r}, which is already taken")i = 2while any(p["step_name"] == f"{step_name}_{i}" for p in REGISTRY):i += 1@@ -147,12 +147,12 @@ def _register(name, shape, role, color, groups, where, unique_step=False, axis=Ndef import_step(path):- """Importiert eine mitgebrachte STEP-Datei (z. B. aus inputs/) als eine Form. Teile und Gruppen der Datei gehen- dabei in einem Koerper auf. Sollen sie erhalten bleiben: import_assembly()."""+ """Imports a STEP file brought along (e.g. from inputs/) as one shape. The parts and groups of the file merge into+ one body. To keep them: import_assembly()."""return cq.importers.importStep(str(path)).val()def import_assembly(path):- """Importiert eine STEP-Datei mit ihrer Struktur: Teile mit Namen und Farben, Unterbaugruppen als Gruppen.- Verschieben als Ganzes mit `asm.loc = cq.Location((x, y, z))`, registrieren mit add_part("Name", asm)."""+ """Imports a STEP file with its structure: parts with names and colors, sub-assemblies as groups.+ Move it as a whole with `asm.loc = cq.Location((x, y, z))`, register it with add_part("Name", asm)."""return cq.Assembly.importStep(str(path))diff --git a/python/soma/render.py b/python/soma/render.pyindex 23fde69..645bfba 100644--- a/python/soma/render.py+++ b/python/soma/render.py@@ -23,10 +23,10 @@ def _size(text, default):return defaultm = re.fullmatch(r"\s*(\d{2,5})\s*[xX*]\s*(\d{2,5})\s*", text)if not m:- raise RenderError(f"--size {text!r}: erwartet Breite x Hoehe, z. B. 1280x720")+ raise RenderError(f"--size {text!r}: expected width x height, e.g. 1280x720")w, h = int(m.group(1)), int(m.group(2))if not (64 <= w <= MAX_SIDE and 64 <= h <= MAX_SIDE):- raise RenderError(f"--size {text!r}: Breite und Hoehe zwischen 64 und {MAX_SIDE} Pixeln")+ raise RenderError(f"--size {text!r}: width and height between 64 and {MAX_SIDE} pixels")return w, h@@ -35,7 +35,7 @@ def _grid(text):return 3, 3m = re.fullmatch(r"\s*(\d)\s*[xX]\s*(\d)\s*", str(text))if not m or not (1 <= int(m.group(1)) <= 6 and 1 <= int(m.group(2)) <= 6):- raise RenderError(f"--sheet {text!r}: erwartet Spalten x Zeilen, z. B. 3x3 (hoechstens 6x6)")+ raise RenderError(f"--sheet {text!r}: expected columns x rows, e.g. 3x3 (at most 6x6)")return int(m.group(1)), int(m.group(2))@@ -45,12 +45,12 @@ def _out(root, out, default, ext):try:rel = rel.resolve().relative_to(root)except ValueError:- raise RenderError(f"--out {out!r} liegt nicht im Projektordner") from None+ raise RenderError(f"--out {out!r} is not in the project folder") from Nonep = rel.as_posix()if ".." in rel.parts or p.startswith((".git/", ".soma/")):- raise RenderError(f"--out {out!r}: Ziel muss im Projektordner liegen, nicht in .git/ oder .soma/")+ raise RenderError(f"--out {out!r}: the target must be in the project folder, not in .git/ or .soma/")if rel.suffix.lower() != ext:- raise RenderError(f"--out {out!r}: Die Datei muss auf {ext} enden")+ raise RenderError(f"--out {out!r}: the file must end in {ext}")return p@@ -63,14 +63,14 @@ def prepare(root, args):root = Path(root).resolve()job = dict(project=str(root), view=args.view or None, warnings=[])if args.view and args.view not in VIEWS:- raise RenderError(f"--view {args.view!r} gibt es nicht. Moeglich: {', '.join(VIEWS)}")+ raise RenderError(f"--view {args.view!r} does not exist. Possible: {', '.join(VIEWS)}")modes = [x for x in ("at", "sheet", "video") if getattr(args, x) not in (None, False)]if modes and not args.anim:- raise RenderError(f"--{modes[0]} gehoert zu einer Animation: --anim \"Name\"")+ raise RenderError(f"--{modes[0]} belongs to an animation: --anim \"Name\"")if len(modes) > 1:- raise RenderError("Nur eins von --at, --sheet und --video")+ raise RenderError("Only one of --at, --sheet and --video")if args.anim and args.result:- raise RenderError("--anim und --result gehen nicht zusammen")+ raise RenderError("--anim and --result do not go together")# analysis und animrun laden cadquery (rund 4 s), deshalb erst hier: eine Ansicht des Modells braucht es nichtif args.result or args.anim:from . import analysis, animrun@@ -78,9 +78,9 @@ def prepare(root, args):meta = analysis.find(root, args.result)if not meta:have = [m["id"] for m in analysis.list_results(root)]- raise RenderError(f"Kein Ergebnis {args.result!r}. " + (f"Vorhanden: {', '.join(have)}" if have else "Erst auswerten, z. B. soma analyze overhang"))+ raise RenderError(f"No result {args.result!r}. " + (f"Available: {', '.join(have)}" if have else "Run an analysis first, e.g. soma analyze overhang"))if animrun.newest_source(root) > meta["created"]:- job["warnings"].append(f"Das Ergebnis {meta['id']!r} ist aelter als der Code. Neu berechnen: soma {' '.join(meta['command'])}")+ job["warnings"].append(f"The result {meta['id']!r} is older than the code. Recalculate: soma {' '.join(meta['command'])}")job["result"] = meta["file"]if args.anim:try:@@ -94,17 +94,17 @@ def prepare(root, args):job["size"] = _size(args.size, (1280, 720))job["fps"] = args.fpsif not 1 <= args.fps <= 60:- raise RenderError("--fps zwischen 1 und 60")+ raise RenderError("--fps between 1 and 60")job["out"] = _out(root, args.out, f"renders/{entry['id']}.mp4", ".mp4")elif args.sheet not in (None, False):job["kind"] = "sheet"job["grid"] = _grid(args.sheet)job["size"] = _size(args.size, (480, 300)) # Groesse eines Einzelbilds- job["out"] = _out(root, args.out, f"renders/{entry['id']}-uebersicht.png", ".png")+ job["out"] = _out(root, args.out, f"renders/{entry['id']}-sheet.png", ".png")else:t = 0.0 if args.at is None else float(args.at)if not 0 <= t <= dur + 1e-6:- raise RenderError(f"--at {t:g}: Die Animation dauert {dur:g} s")+ raise RenderError(f"--at {t:g}: the animation lasts {dur:g} s")job["kind"] = "still"job["at"] = tjob["size"] = _size(args.size, (1280, 800))@@ -112,7 +112,7 @@ def prepare(root, args):else:job["kind"] = "still"job["size"] = _size(args.size, (1280, 800))- name = f"ergebnis-{Path(job['result']).stem}" if args.result else f"ansicht-{args.view or 'iso'}"+ name = f"result-{Path(job['result']).stem}" if args.result else f"view-{args.view or 'iso'}"job["out"] = _out(root, args.out, f"renders/{name}.png", ".png")return job@@ -121,8 +121,8 @@ def send(job, timeout=900):"""Schickt den Auftrag an die App und wartet auf das Ergebnis."""addr, token = os.environ.get("SOMA_APP"), os.environ.get("SOMA_APP_TOKEN")if not addr or not token:- raise RenderError("soma render braucht die laufende App: Fuehre den Befehl im Terminal der App aus "- "(dort sind SOMA_APP und SOMA_APP_TOKEN gesetzt).")+ raise RenderError("soma render needs the running app: run the command in a terminal of the app "+ "(SOMA_APP and SOMA_APP_TOKEN are set there).")host, _, port = addr.rpartition(":")try:conn = http.client.HTTPConnection(host or "127.0.0.1", int(port), timeout=timeout)@@ -131,8 +131,8 @@ def send(job, timeout=900):resp = conn.getresponse()data = json.loads(resp.read().decode("utf-8") or "{}")except (OSError, ValueError) as e:- raise RenderError(f"Die App antwortet nicht ({addr}): {e}. Laeuft sie noch? Neue Terminals bekommen die neue Adresse.") from None+ raise RenderError(f"The app does not answer ({addr}): {e}. Is it still running? New terminals get the new address.") from Noneif not data.get("ok"):- raise RenderError(data.get("error") or f"Die App meldet einen Fehler (HTTP {resp.status})")+ raise RenderError(data.get("error") or f"The app reports an error (HTTP {resp.status})")data["warnings"] = job.get("warnings", []) + data.get("warnings", [])return data