pylever-dyn 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pylever/__init__.py +0 -0
- pylever/analysis/__init__.py +0 -0
- pylever/components/__init__.py +20 -0
- pylever/components/dampers.py +119 -0
- pylever/components/force_law.py +211 -0
- pylever/components/slider_crank.py +165 -0
- pylever/components/springs.py +266 -0
- pylever/geometry/__init__.py +4 -0
- pylever/geometry/geometry.py +150 -0
- pylever/geometry/point.py +77 -0
- pylever/io/__init__.py +0 -0
- pylever/mechanism/__init__.py +15 -0
- pylever/mechanism/dynamics.py +156 -0
- pylever/mechanism/lever_system.py +212 -0
- pylever/mechanism/spring_fit.py +365 -0
- pylever/report/__init__.py +25 -0
- pylever/report/lever_report.py +494 -0
- pylever/report/spring_export.py +332 -0
- pylever_dyn-0.0.1.dist-info/METADATA +366 -0
- pylever_dyn-0.0.1.dist-info/RECORD +22 -0
- pylever_dyn-0.0.1.dist-info/WHEEL +4 -0
- pylever_dyn-0.0.1.dist-info/licenses/LICENSE +21 -0
pylever/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from .dampers import LinearDamper, RotaryDamper
|
|
2
|
+
from .force_law import ForceLaw, FunctionLaw, SpringcalcLaw, TableLaw
|
|
3
|
+
from .slider_crank import SliderCrank
|
|
4
|
+
from .springs import CompressionSpring, ExtensionParams, ExtensionSpring, LinearSpringLaw, TorsionParams, TorsionSpring
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"CompressionSpring",
|
|
8
|
+
"ExtensionParams",
|
|
9
|
+
"ExtensionSpring",
|
|
10
|
+
"ForceLaw",
|
|
11
|
+
"FunctionLaw",
|
|
12
|
+
"LinearDamper",
|
|
13
|
+
"LinearSpringLaw",
|
|
14
|
+
"RotaryDamper",
|
|
15
|
+
"SliderCrank",
|
|
16
|
+
"SpringcalcLaw",
|
|
17
|
+
"TableLaw",
|
|
18
|
+
"TorsionParams",
|
|
19
|
+
"TorsionSpring",
|
|
20
|
+
]
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Dampers: velocity-dependent elements. They only act in dynamics (ω ≠ 0).
|
|
2
|
+
|
|
3
|
+
- :class:`LinearDamper`: damper between a ground and a lever anchor (e.g. a
|
|
4
|
+
gas or hydraulic damper). Its force depends on the elongation speed
|
|
5
|
+
``v = dD/dt`` (mm/s).
|
|
6
|
+
- :class:`RotaryDamper`: damper at the pivot; its moment depends on ``ω``.
|
|
7
|
+
|
|
8
|
+
The characteristic is given either as a constant ``c`` (viscous) or as a law
|
|
9
|
+
``F(|v|)`` / ``M(|ω|)``, e.g. a :class:`~pylever.components.TableLaw` from a
|
|
10
|
+
datasheet CSV. The damper always opposes the motion. ``active`` restricts it
|
|
11
|
+
to one direction (one-way dampers).
|
|
12
|
+
|
|
13
|
+
Sign convention as for every element: ``moment(θ, ω)`` is positive when it
|
|
14
|
+
opposes pressing (N·mm). ``theta_deg`` is clockwise-positive, ``omega`` in
|
|
15
|
+
rad/s, positive when pressing.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import math
|
|
21
|
+
from typing import Literal
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from ..geometry.point import Body, Point
|
|
26
|
+
from .force_law import ForceLaw, FunctionLaw
|
|
27
|
+
|
|
28
|
+
XY = tuple[float, float]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _characteristic(c: float | None, law: ForceLaw | None, name: str) -> ForceLaw:
|
|
32
|
+
if (c is None) == (law is None):
|
|
33
|
+
raise ValueError(f"{name}: give either c (viscous) or law (characteristic), not both")
|
|
34
|
+
if c is not None:
|
|
35
|
+
if c < 0:
|
|
36
|
+
raise ValueError(f"{name}: c cannot be negative")
|
|
37
|
+
return FunctionLaw(lambda v, c=float(c): c * v, name=name)
|
|
38
|
+
if not callable(law):
|
|
39
|
+
raise TypeError(f"{name}: law must be callable: F(speed) -> force")
|
|
40
|
+
return law
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class LinearDamper:
|
|
44
|
+
"""Damper between a ground anchor and a lever anchor.
|
|
45
|
+
|
|
46
|
+
``c`` in N·s/mm (``F = c·|v|``) or ``law(|v|)`` with ``v`` in mm/s.
|
|
47
|
+
``active``: ``"both"``, ``"extension"`` (only while the damper lengthens)
|
|
48
|
+
or ``"compression"`` (only while it shortens).
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, ground: XY | Point, lever: XY | Point, c: float | None = None, law: ForceLaw | None = None,
|
|
52
|
+
active: Literal["both", "extension", "compression"] = "both", name: str = "damper"):
|
|
53
|
+
self.ground = ground if isinstance(ground, Point) else Point(
|
|
54
|
+
f"{name}_ground", *map(float, ground), Body.GROUND, "Ground anchor")
|
|
55
|
+
self.lever = lever if isinstance(lever, Point) else Point(
|
|
56
|
+
f"{name}_lever", *map(float, lever), Body.LEVER, "Lever anchor")
|
|
57
|
+
self.name = name
|
|
58
|
+
self.law = _characteristic(c, law, name)
|
|
59
|
+
if active not in ("both", "extension", "compression"):
|
|
60
|
+
raise ValueError(f"{name}: active must be 'both', 'extension' or 'compression'")
|
|
61
|
+
self.active = active
|
|
62
|
+
if np.linalg.norm(self.lever.xy - self.ground.xy) < 1e-9:
|
|
63
|
+
raise ValueError(f"{name}: the anchors cannot coincide")
|
|
64
|
+
|
|
65
|
+
def validate(self, pivot: Point) -> None:
|
|
66
|
+
if np.linalg.norm(self.lever.xy - pivot.xy) < 1e-9:
|
|
67
|
+
raise ValueError(f"{self.name}: the lever anchor cannot coincide with the pivot")
|
|
68
|
+
|
|
69
|
+
def distance_rate(self, theta_deg: float, pivot: Point) -> float:
|
|
70
|
+
"""``dD/dθ`` in mm/rad."""
|
|
71
|
+
t = math.radians(theta_deg)
|
|
72
|
+
c, s = math.cos(t), math.sin(t)
|
|
73
|
+
dx, dy = self.lever.xy - pivot.xy
|
|
74
|
+
a = pivot.xy + np.array([c * dx + s * dy, -s * dx + c * dy])
|
|
75
|
+
e = (a - self.ground.xy) / np.linalg.norm(a - self.ground.xy)
|
|
76
|
+
r = a - pivot.xy
|
|
77
|
+
return float(np.dot(e, [r[1], -r[0]]))
|
|
78
|
+
|
|
79
|
+
def speed(self, theta_deg: float, omega: float, pivot: Point) -> float:
|
|
80
|
+
"""Elongation speed ``v = dD/dt``, mm/s."""
|
|
81
|
+
return self.distance_rate(theta_deg, pivot) * omega
|
|
82
|
+
|
|
83
|
+
def force(self, theta_deg: float, omega: float, pivot: Point) -> float:
|
|
84
|
+
"""Force along G–A, N (positive pushes the anchors apart)."""
|
|
85
|
+
v = self.speed(theta_deg, omega, pivot)
|
|
86
|
+
if v == 0 or (self.active == "extension" and v < 0) or (self.active == "compression" and v > 0):
|
|
87
|
+
return 0.0
|
|
88
|
+
return -math.copysign(float(self.law(abs(v))), v)
|
|
89
|
+
|
|
90
|
+
def moment(self, theta_deg: float, omega: float, pivot: Point) -> float:
|
|
91
|
+
"""Moment on the lever, N·mm (positive opposes pressing)."""
|
|
92
|
+
return -self.force(theta_deg, omega, pivot) * self.distance_rate(theta_deg, pivot)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class RotaryDamper:
|
|
96
|
+
"""Damper at the pivot: ``M = c·|ω|`` (``c`` in N·mm·s/rad) or ``law(|ω|)``, opposing ``ω``.
|
|
97
|
+
|
|
98
|
+
``active``: ``"both"``, ``"press"`` (only while pressing) or
|
|
99
|
+
``"release"`` (only while returning).
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__(self, c: float | None = None, law: ForceLaw | None = None,
|
|
103
|
+
active: Literal["both", "press", "release"] = "both", name: str = "rotary_damper"):
|
|
104
|
+
self.name = name
|
|
105
|
+
self.law = _characteristic(c, law, name)
|
|
106
|
+
if active not in ("both", "press", "release"):
|
|
107
|
+
raise ValueError(f"{name}: active must be 'both', 'press' or 'release'")
|
|
108
|
+
self.active = active
|
|
109
|
+
|
|
110
|
+
def validate(self, pivot: Point) -> None:
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
def moment(self, theta_deg: float, omega: float, pivot: Point) -> float:
|
|
114
|
+
if omega == 0 or (self.active == "press" and omega < 0) or (self.active == "release" and omega > 0):
|
|
115
|
+
return 0.0
|
|
116
|
+
return math.copysign(float(self.law(abs(omega))), omega)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
Damper = LinearDamper | RotaryDamper
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Force laws: force (N) as a function of a displacement ``x`` (mm).
|
|
2
|
+
|
|
3
|
+
``x`` is always the **compression / stroke** of the element that owns the law:
|
|
4
|
+
|
|
5
|
+
- for a compression spring, its deflection from free length (``L0 - L``);
|
|
6
|
+
- for the slider-crank cylinder, the piston stroke from its rest position.
|
|
7
|
+
|
|
8
|
+
Compression springs always come from ``springcalc`` (:class:`SpringcalcLaw`);
|
|
9
|
+
measured curves from :class:`TableLaw` (CSV) and analytic ones from
|
|
10
|
+
:class:`FunctionLaw`. Every law is a callable ``law(x) -> float``. Hysteresis is not handled here:
|
|
11
|
+
the global system friction (added on apply, subtracted on release) belongs to
|
|
12
|
+
``LeverSystem``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import csv
|
|
18
|
+
from collections.abc import Callable, Sequence
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Literal, Protocol, runtime_checkable
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@runtime_checkable
|
|
27
|
+
class ForceLaw(Protocol):
|
|
28
|
+
"""Anything callable as ``law(x) -> force``."""
|
|
29
|
+
|
|
30
|
+
def __call__(self, x: float) -> float: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class FunctionLaw:
|
|
35
|
+
"""Wraps a user function ``f(x) -> force``."""
|
|
36
|
+
|
|
37
|
+
func: Callable[[float], float]
|
|
38
|
+
name: str = ""
|
|
39
|
+
|
|
40
|
+
def __post_init__(self) -> None:
|
|
41
|
+
if not callable(self.func):
|
|
42
|
+
raise TypeError("func must be callable: f(x) -> force")
|
|
43
|
+
|
|
44
|
+
def __call__(self, x: float) -> float:
|
|
45
|
+
return float(self.func(x))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
Extrapolation = Literal["hold", "linear", "error"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class TableLaw:
|
|
53
|
+
"""Linear interpolation over measured (stroke, force) points.
|
|
54
|
+
|
|
55
|
+
Outside the table: ``"hold"`` keeps the end value, ``"linear"`` extends the
|
|
56
|
+
end slope, ``"error"`` raises ``ValueError``.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
x: Sequence[float]
|
|
60
|
+
force: Sequence[float]
|
|
61
|
+
extrapolate: Extrapolation = "hold"
|
|
62
|
+
name: str = ""
|
|
63
|
+
_x: np.ndarray = field(init=False, repr=False, compare=False)
|
|
64
|
+
_f: np.ndarray = field(init=False, repr=False, compare=False)
|
|
65
|
+
|
|
66
|
+
def __post_init__(self) -> None:
|
|
67
|
+
xs = np.asarray(self.x, dtype=float)
|
|
68
|
+
fs = np.asarray(self.force, dtype=float)
|
|
69
|
+
if xs.ndim != 1 or xs.shape != fs.shape:
|
|
70
|
+
raise ValueError("x and force must be 1D sequences of the same length")
|
|
71
|
+
if xs.size < 2:
|
|
72
|
+
raise ValueError("The table needs at least 2 points")
|
|
73
|
+
if not (np.all(np.isfinite(xs)) and np.all(np.isfinite(fs))):
|
|
74
|
+
raise ValueError("The table contains non-finite values")
|
|
75
|
+
order = np.argsort(xs, kind="stable")
|
|
76
|
+
xs, fs = xs[order], fs[order]
|
|
77
|
+
if np.any(np.diff(xs) <= 0):
|
|
78
|
+
raise ValueError("x values must be distinct (repeated strokes found)")
|
|
79
|
+
if self.extrapolate not in ("hold", "linear", "error"):
|
|
80
|
+
raise ValueError("extrapolate must be 'hold', 'linear' or 'error'")
|
|
81
|
+
object.__setattr__(self, "_x", xs)
|
|
82
|
+
object.__setattr__(self, "_f", fs)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def x_range(self) -> tuple[float, float]:
|
|
86
|
+
return float(self._x[0]), float(self._x[-1])
|
|
87
|
+
|
|
88
|
+
def __call__(self, x: float) -> float:
|
|
89
|
+
xs, fs = self._x, self._f
|
|
90
|
+
if x < xs[0] or x > xs[-1]:
|
|
91
|
+
if self.extrapolate == "error":
|
|
92
|
+
raise ValueError(f"x = {x} outside the table range {self.x_range}")
|
|
93
|
+
if self.extrapolate == "linear":
|
|
94
|
+
i, j = (0, 1) if x < xs[0] else (-2, -1)
|
|
95
|
+
return float(fs[i] + (x - xs[i]) * (fs[j] - fs[i]) / (xs[j] - xs[i]))
|
|
96
|
+
return float(np.interp(x, xs, fs))
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_csv(cls, path: str | Path, x_col: int | str = 0, force_col: int | str = 1,
|
|
100
|
+
extrapolate: Extrapolation = "hold") -> TableLaw:
|
|
101
|
+
"""Load a table from CSV.
|
|
102
|
+
|
|
103
|
+
Delimiter (``,`` ``;`` tab) is auto-detected. A header row is optional;
|
|
104
|
+
columns can be selected by index or by header name. With ``;`` or tab
|
|
105
|
+
delimiters a decimal comma is accepted.
|
|
106
|
+
"""
|
|
107
|
+
path = Path(path)
|
|
108
|
+
text = path.read_text(encoding="utf-8-sig")
|
|
109
|
+
try:
|
|
110
|
+
dialect = csv.Sniffer().sniff(text[:4096], delimiters=",;\t")
|
|
111
|
+
delimiter = dialect.delimiter
|
|
112
|
+
except csv.Error:
|
|
113
|
+
delimiter = ","
|
|
114
|
+
rows = [r for r in csv.reader(text.splitlines(), delimiter=delimiter) if any(c.strip() for c in r)]
|
|
115
|
+
if not rows:
|
|
116
|
+
raise ValueError(f"{path}: empty CSV file")
|
|
117
|
+
|
|
118
|
+
def num(cell: str) -> float:
|
|
119
|
+
cell = cell.strip()
|
|
120
|
+
if delimiter != ",":
|
|
121
|
+
cell = cell.replace(",", ".")
|
|
122
|
+
return float(cell)
|
|
123
|
+
|
|
124
|
+
header: list[str] | None = None
|
|
125
|
+
try:
|
|
126
|
+
[num(c) for c in rows[0]]
|
|
127
|
+
except ValueError:
|
|
128
|
+
header, rows = [c.strip() for c in rows[0]], rows[1:]
|
|
129
|
+
|
|
130
|
+
def index(col: int | str) -> int:
|
|
131
|
+
if isinstance(col, int):
|
|
132
|
+
return col
|
|
133
|
+
if header is None or col not in header:
|
|
134
|
+
raise ValueError(f"{path}: column {col!r} not found. Header: {header}")
|
|
135
|
+
return header.index(col)
|
|
136
|
+
|
|
137
|
+
ix, ifc = index(x_col), index(force_col)
|
|
138
|
+
xs, fs = [], []
|
|
139
|
+
for n, row in enumerate(rows, start=2 if header else 1):
|
|
140
|
+
try:
|
|
141
|
+
xs.append(num(row[ix]))
|
|
142
|
+
fs.append(num(row[ifc]))
|
|
143
|
+
except (ValueError, IndexError):
|
|
144
|
+
raise ValueError(f"{path}: invalid row {n}: {row}") from None
|
|
145
|
+
return cls(xs, fs, extrapolate=extrapolate, name=path.stem)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class SpringcalcLaw:
|
|
149
|
+
"""Compression spring designed with ``springcalc`` (``CompressionSpringGeneral``).
|
|
150
|
+
|
|
151
|
+
Supports any geometry springcalc can model (variable diameter and pitch:
|
|
152
|
+
conical, barrel...). The force-deflection curve, including coil-to-coil
|
|
153
|
+
contact, is simulated **once** at construction and then interpolated, so
|
|
154
|
+
evaluating the law is cheap.
|
|
155
|
+
|
|
156
|
+
``law(x)`` takes the deflection ``x = L0 - L`` in mm:
|
|
157
|
+
|
|
158
|
+
- ``x <= 0``: no contact, ``F = 0``;
|
|
159
|
+
- ``x > max_deflection`` (spring at solid length): ``ValueError``.
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
def __init__(self, spring: Any, steps: int = 500, name: str = ""):
|
|
163
|
+
if not hasattr(spring, "simulate_progressive_compression"):
|
|
164
|
+
raise TypeError("spring must be a springcalc spring (CompressionSpringGeneral)")
|
|
165
|
+
self.spring = spring
|
|
166
|
+
self.name = name
|
|
167
|
+
if not getattr(spring, "spring_constant", None):
|
|
168
|
+
spring.calculate_spring_properties()
|
|
169
|
+
deflection, force, _ = spring.simulate_progressive_compression(
|
|
170
|
+
max_deflection=spring.free_length, steps=steps)
|
|
171
|
+
d = np.asarray(deflection.to("mm").magnitude, dtype=float)
|
|
172
|
+
f = np.asarray(force.to("N").magnitude, dtype=float) + spring.initial_force.to("N").magnitude
|
|
173
|
+
d, idx = np.unique(d, return_index=True) # drop repeated deflections at solid length
|
|
174
|
+
self._table = TableLaw(d, f[idx], extrapolate="error", name=name)
|
|
175
|
+
|
|
176
|
+
@classmethod
|
|
177
|
+
def from_json(cls, path: str | Path, steps: int = 500, name: str = "") -> SpringcalcLaw:
|
|
178
|
+
"""Load a spring saved with ``springcalc.save_model``."""
|
|
179
|
+
from springcalc import load_model
|
|
180
|
+
|
|
181
|
+
return cls(load_model(str(path)), steps=steps, name=name or Path(path).stem)
|
|
182
|
+
|
|
183
|
+
@property
|
|
184
|
+
def free_length(self) -> float:
|
|
185
|
+
"""Free length, mm."""
|
|
186
|
+
return float(self.spring.free_length.to("mm").magnitude)
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def max_deflection(self) -> float:
|
|
190
|
+
"""Largest simulated deflection (spring at solid length), mm."""
|
|
191
|
+
return self._table.x_range[1]
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def solid_length(self) -> float:
|
|
195
|
+
"""Length at the largest simulated deflection, mm."""
|
|
196
|
+
return self.free_length - self.max_deflection
|
|
197
|
+
|
|
198
|
+
def force_at_length(self, length: float) -> float:
|
|
199
|
+
"""Force for a given spring length, mm."""
|
|
200
|
+
return self(self.free_length - length)
|
|
201
|
+
|
|
202
|
+
def __call__(self, x: float) -> float:
|
|
203
|
+
if x <= 0.0:
|
|
204
|
+
return 0.0
|
|
205
|
+
if x > self.max_deflection:
|
|
206
|
+
raise ValueError(f"Spring {self.name!r} at solid length: deflection {x:.3f} mm > {self.max_deflection:.3f} mm")
|
|
207
|
+
return self._table(x)
|
|
208
|
+
|
|
209
|
+
def __repr__(self) -> str:
|
|
210
|
+
return (f"SpringcalcLaw({self.name!r}, free_length={self.free_length:.2f} mm, "
|
|
211
|
+
f"max_deflection={self.max_deflection:.2f} mm)")
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Slider-crank: lever rod anchor pushing a piston along a fixed cylinder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from ..geometry.point import Body, Point
|
|
11
|
+
from .force_law import ForceLaw, SpringcalcLaw
|
|
12
|
+
|
|
13
|
+
XY = tuple[float, float]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class SliderCrank:
|
|
18
|
+
"""Rod linking the lever to a piston that slides inside a fixed cylinder.
|
|
19
|
+
|
|
20
|
+
Points (absolute coordinates, lever in its rest position):
|
|
21
|
+
|
|
22
|
+
- ``rod_anchor``: rod joint on the lever (rotates with it).
|
|
23
|
+
- ``cylinder_start``: piston joint at rest. It is the cylinder end closest
|
|
24
|
+
to the lever pivot.
|
|
25
|
+
- ``cylinder_end``: other end of the cylinder. With ``cylinder_start`` it
|
|
26
|
+
defines the sliding axis and the maximum stroke.
|
|
27
|
+
|
|
28
|
+
The rod length is ``|rod_anchor - cylinder_start|`` and stays constant.
|
|
29
|
+
The stroke ``s`` (mm) is the piston travel from ``cylinder_start`` towards
|
|
30
|
+
``cylinder_end``.
|
|
31
|
+
|
|
32
|
+
``force`` is the law ``F(x)`` pushing back on the piston. If it is a
|
|
33
|
+
:class:`SpringcalcLaw`, ``installed_length`` is the spring length with the
|
|
34
|
+
piston at rest (defaults to its free length, i.e. no preload) and the law
|
|
35
|
+
is evaluated at ``x = free_length - installed_length + s``. For any other
|
|
36
|
+
law, ``x = s``.
|
|
37
|
+
|
|
38
|
+
Rotation ``theta_deg`` is clockwise-positive (pressing), as in ``Lever``.
|
|
39
|
+
Methods that depend on the rotation take the lever ``pivot``.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
rod_anchor: Point
|
|
43
|
+
cylinder_start: Point
|
|
44
|
+
cylinder_end: Point
|
|
45
|
+
force: ForceLaw
|
|
46
|
+
installed_length: float | None = None
|
|
47
|
+
name: str = "slider_crank"
|
|
48
|
+
|
|
49
|
+
def __post_init__(self) -> None:
|
|
50
|
+
if self.max_stroke < 1e-9:
|
|
51
|
+
raise ValueError("cylinder_start and cylinder_end cannot coincide")
|
|
52
|
+
if self.rod_length < 1e-9:
|
|
53
|
+
raise ValueError("rod_anchor cannot coincide with cylinder_start")
|
|
54
|
+
if abs(self._axial0) < 1e-9 * self.rod_length:
|
|
55
|
+
raise ValueError("The rod cannot be perpendicular to the cylinder axis at rest")
|
|
56
|
+
if not callable(self.force):
|
|
57
|
+
raise TypeError("force must be a force law: F(x) -> force")
|
|
58
|
+
if self.installed_length is not None:
|
|
59
|
+
if not isinstance(self.force, SpringcalcLaw):
|
|
60
|
+
raise ValueError("installed_length is only used when the force is a spring (SpringcalcLaw)")
|
|
61
|
+
if not 0 < self.installed_length <= self.force.free_length:
|
|
62
|
+
raise ValueError(f"installed_length must be in (0, {self.force.free_length}] mm "
|
|
63
|
+
f"(spring free length), not {self.installed_length}")
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_xy(cls, rod_anchor: XY, cylinder_start: XY, cylinder_end: XY, force: ForceLaw,
|
|
67
|
+
installed_length: float | None = None, name: str = "slider_crank") -> SliderCrank:
|
|
68
|
+
"""Build from absolute Cartesian coordinates."""
|
|
69
|
+
return cls(
|
|
70
|
+
rod_anchor=Point("rod_anchor", *map(float, rod_anchor), Body.LEVER, "Rod anchor"),
|
|
71
|
+
cylinder_start=Point("cylinder_start", *map(float, cylinder_start), Body.GROUND,
|
|
72
|
+
"Cylinder start (piston at rest)"),
|
|
73
|
+
cylinder_end=Point("cylinder_end", *map(float, cylinder_end), Body.GROUND, "Cylinder end"),
|
|
74
|
+
force=force,
|
|
75
|
+
installed_length=installed_length,
|
|
76
|
+
name=name,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# --- fixed geometry -------------------------------------------------------
|
|
80
|
+
@property
|
|
81
|
+
def axis(self) -> np.ndarray:
|
|
82
|
+
"""Unit vector of the sliding axis, start → end."""
|
|
83
|
+
return (self.cylinder_end.xy - self.cylinder_start.xy) / self.max_stroke
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def max_stroke(self) -> float:
|
|
87
|
+
"""Cylinder length |end - start|, mm."""
|
|
88
|
+
return float(np.linalg.norm(self.cylinder_end.xy - self.cylinder_start.xy))
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def rod_length(self) -> float:
|
|
92
|
+
"""Constant rod length, mm."""
|
|
93
|
+
return float(np.linalg.norm(self.rod_anchor.xy - self.cylinder_start.xy))
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def _axial0(self) -> float:
|
|
97
|
+
# projection of (anchor - start) on the axis at rest; its sign picks the solution branch
|
|
98
|
+
return float(np.dot(self.rod_anchor.xy - self.cylinder_start.xy, self.axis))
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def preload_deflection(self) -> float:
|
|
102
|
+
"""Spring deflection with the piston at rest, mm (0 if the force is not a spring)."""
|
|
103
|
+
if isinstance(self.force, SpringcalcLaw) and self.installed_length is not None:
|
|
104
|
+
return self.force.free_length - self.installed_length
|
|
105
|
+
return 0.0
|
|
106
|
+
|
|
107
|
+
def validate(self, pivot: Point) -> None:
|
|
108
|
+
"""Check the geometry against the lever pivot."""
|
|
109
|
+
d_start = np.linalg.norm(self.cylinder_start.xy - pivot.xy)
|
|
110
|
+
d_end = np.linalg.norm(self.cylinder_end.xy - pivot.xy)
|
|
111
|
+
if d_start > d_end:
|
|
112
|
+
raise ValueError("cylinder_start must be the cylinder end closest to the pivot "
|
|
113
|
+
f"({d_start:.3f} mm > {d_end:.3f} mm)")
|
|
114
|
+
if math.isclose(float(np.linalg.norm(self.rod_anchor.xy - pivot.xy)), 0.0, abs_tol=1e-9):
|
|
115
|
+
raise ValueError("rod_anchor cannot coincide with the pivot")
|
|
116
|
+
|
|
117
|
+
# --- kinematics -----------------------------------------------------------
|
|
118
|
+
def anchor_at(self, theta_deg: float, pivot: Point) -> np.ndarray:
|
|
119
|
+
"""Rod anchor position after rotating the lever ``theta_deg`` clockwise."""
|
|
120
|
+
t = math.radians(theta_deg)
|
|
121
|
+
c, s = math.cos(t), math.sin(t)
|
|
122
|
+
dx, dy = self.rod_anchor.xy - pivot.xy
|
|
123
|
+
return pivot.xy + np.array([c * dx + s * dy, -s * dx + c * dy])
|
|
124
|
+
|
|
125
|
+
def stroke(self, theta_deg: float, pivot: Point) -> float:
|
|
126
|
+
"""Piston stroke ``s`` (mm) for a lever rotation ``theta_deg``.
|
|
127
|
+
|
|
128
|
+
Solves ``|start + s·u - A(θ)| = rod_length`` on the branch that gives
|
|
129
|
+
``s = 0`` at rest.
|
|
130
|
+
"""
|
|
131
|
+
d = self.anchor_at(theta_deg, pivot) - self.cylinder_start.xy
|
|
132
|
+
b = float(np.dot(d, self.axis))
|
|
133
|
+
disc = b * b - float(np.dot(d, d)) + self.rod_length**2
|
|
134
|
+
if disc < 0:
|
|
135
|
+
raise ValueError(f"{self.name}: θ = {theta_deg}° out of reach, the rod does not reach the cylinder axis")
|
|
136
|
+
branch = -1.0 if self._axial0 > 0 else 1.0
|
|
137
|
+
s = b + branch * math.sqrt(disc)
|
|
138
|
+
if s > self.max_stroke + 1e-9:
|
|
139
|
+
raise ValueError(f"{self.name}: θ = {theta_deg}°, stroke {s:.3f} mm > cylinder length "
|
|
140
|
+
f"{self.max_stroke:.3f} mm")
|
|
141
|
+
return s
|
|
142
|
+
|
|
143
|
+
def piston_at(self, theta_deg: float, pivot: Point) -> np.ndarray:
|
|
144
|
+
"""Piston joint position for a lever rotation ``theta_deg``."""
|
|
145
|
+
return self.cylinder_start.xy + self.stroke(theta_deg, pivot) * self.axis
|
|
146
|
+
|
|
147
|
+
def stroke_rate(self, theta_deg: float, pivot: Point) -> float:
|
|
148
|
+
"""``ds/dθ`` in mm/rad (the effective lever arm of the cylinder force)."""
|
|
149
|
+
a = self.anchor_at(theta_deg, pivot)
|
|
150
|
+
rod = self.cylinder_start.xy + self.stroke(theta_deg, pivot) * self.axis - a # anchor → piston
|
|
151
|
+
r = a - pivot.xy
|
|
152
|
+
da = np.array([r[1], -r[0]]) # dA/dθ for clockwise rotation
|
|
153
|
+
denom = float(np.dot(rod, self.axis))
|
|
154
|
+
if abs(denom) < 1e-12:
|
|
155
|
+
raise ValueError(f"{self.name}: θ = {theta_deg}°, rod perpendicular to the axis (dead centre)")
|
|
156
|
+
return float(np.dot(rod, da)) / denom
|
|
157
|
+
|
|
158
|
+
# --- loads ----------------------------------------------------------------
|
|
159
|
+
def piston_force(self, theta_deg: float, pivot: Point) -> float:
|
|
160
|
+
"""Force on the piston along the axis, N (positive pushes back against the rod)."""
|
|
161
|
+
return float(self.force(self.preload_deflection + self.stroke(theta_deg, pivot)))
|
|
162
|
+
|
|
163
|
+
def moment(self, theta_deg: float, pivot: Point) -> float:
|
|
164
|
+
"""Moment on the lever about the pivot, N·mm. Positive opposes pressing."""
|
|
165
|
+
return self.piston_force(theta_deg, pivot) * self.stroke_rate(theta_deg, pivot)
|