Metadata-Version: 2.5
Name: pylever-dyn
Version: 0.0.1
Summary: Kinematic and dynamic analysis of planar levers, oriented to the design of brake pedals
Author: Ernesto Avedillo
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.13
Requires-Dist: matplotlib>=3.8
Requires-Dist: numpy>=2.0
Requires-Dist: pypdf>=5
Requires-Dist: reportlab>=4
Requires-Dist: scipy>=1.18.1
Requires-Dist: springcalc>=0.1.27
Provides-Extra: all
Requires-Dist: matplotlib>=3.8; extra == 'all'
Requires-Dist: pandas>=2.2; extra == 'all'
Requires-Dist: xlrd>=2.0; extra == 'all'
Provides-Extra: excel
Requires-Dist: xlrd>=2.0; extra == 'excel'
Provides-Extra: pandas
Requires-Dist: pandas>=2.2; extra == 'pandas'
Provides-Extra: plot
Requires-Dist: matplotlib>=3.8; extra == 'plot'
Provides-Extra: step
Requires-Dist: cadquery>=2.8.0; extra == 'step'
Description-Content-Type: text/markdown

# pylever

Kinematics, statics, and dynamics of planar levers, focused on the design of **pedals**
(brake, clutch, and accelerator): compression, extension, and torsion springs, slider-crank
(booster / CMC), weight, friction, and dampers.

Two ways to work:

- **Forward calculation**: given the lever and its components, calculate the force-travel curve
  (press and release) and **free return** (velocity and energy) from any percentage of travel.
- **Inverse calculation**: given a customer curve (CSV), find the anchor positions and springs
  that reproduce it, and design real springs with [springcalc](https://pypi.org/project/springcalc/).

The full mathematical explanation is in [docs/palanca_paper.tex](docs/palanca_paper.tex).

## Installation

```bash
uv sync                  # development environment
uv sync --extra step     # + cadquery, to export springs to STEP
uv run pytest            # tests
uv run python examples/direct_calculation.py
uv run python examples/inverse_design.py
uv run python examples/report.py
```

Dependencies: `numpy`, `scipy`, `springcalc`, `matplotlib`, `reportlab`, and `pypdf`. STEP export
also requires `cadquery` (the optional `step` extra), which is a large dependency.

## Conventions

| Quantity | Unit / convention |
|---|---|
| Lengths | mm |
| Forces | N |
| Moments | N·mm. **Positive when opposing pedal application** |
| Mass / inertia | kg / kg·m² |
| Axes | X to the right, Y upward (gravity in −Y) |
| Polar angles | degrees, **clockwise** from +X (as in the old Excel file) |
| Lever rotation θ | degrees, positive clockwise (= pressing). θ = 0 is the rest position |
| Travel | **Chord** of the force application point: straight-line distance from the rest position, `2·L·sin(θ/2)` |
| User force | At the force application point, perpendicular to the lever: `F = M_total / L` |

All points are given in absolute coordinates with the lever at rest.

## Structure

```
src/pylever/
├── geometry/      Lever (pivot, force application point, center of mass), Point
├── components/    Force laws, springs, slider-crank, dampers
├── mechanism/     LeverSystem, spring fitting (spring_fit), dynamics (dynamics)
└── report/        PDF report (LeverReport), JSON/STEP export for each spring
```

## Components

### Geometry: `Lever`

```python
from pylever.geometry import Lever

lever = Lever.from_xy(force=(0, -200), com=(0, -90), pivot=(0, 0))
lever = Lever.from_json("examples/pedal_2021_geometry.json")   # x/y or r/angle from the pivot
lever.length, lever.com_distance, lever.angle
lever.rotated(10)            # lever rotated 10° (pressed)
```

### Force laws `F(x)`

`x` is always the compression / stroke of the component (mm).

| Class | Use |
|---|---|
| `SpringcalcLaw(spring)` | springcalc compression spring (`CompressionSpringGeneral`: variable diameter and pitch). The curve, including coil contact, is simulated once and interpolated. Raises an error if it reaches solid height |
| `SpringcalcLaw.from_json(path)` | Spring saved with `springcalc.save_model` |
| `TableLaw(x, F)` / `TableLaw.from_csv(path)` | Measured curve. CSV with or without a header, `,`, `;`, or tab delimiter; decimal commas are accepted |
| `FunctionLaw(f)` | Any function `f(x) -> F` |

### Lever springs

All springs are mounted between a fixed anchor `G` and an anchor on the lever `A`, and are
created from a springcalc spring.

| Class | springcalc spring | Force |
|---|---|---|
| `CompressionSpring(G, A, spring, length_offset=0)` | `CompressionSpringGeneral` | Pushes along G–A. Spring length = `\|A−G\| + length_offset` (seats) |
| `ExtensionSpring(G, A, spring, length_offset=0)` | `ExtensionSpring` | Pulls along G–A: `F₀ + k·ΔL` if ΔL > 0 |
| `TorsionSpring(G, A, spring)` | `TorsionSpring` | Floating coil with legs articulated at G and A. Torque `k·(α_free − α)`. Force **along G–A** (solid loaded at two points) |

Names match those in springcalc: if importing both, use an alias
(`from pylever.components import ExtensionSpring as LeverExtensionSpring`).

### Slider-crank: `SliderCrank`

```python
from pylever.components import SliderCrank, TableLaw

booster = SliderCrank.from_xy(
    rod_anchor=(0, -40),           # on the lever
    cylinder_start=(-120, -40),    # piston at rest (end closest to the pivot)
    cylinder_end=(-160, -40),      # cylinder axis and maximum stroke
    force=TableLaw.from_csv("booster.csv"),   # or SpringcalcLaw(...) or FunctionLaw(...)
    installed_length=None,         # only if force is a spring: installed length (preload)
)
```

Exact stroke from circle-line intersection; moment `M = F·ds/dθ`.

### Dampers

Only active during dynamics (ω ≠ 0). Viscous coefficient `c` or force law `F(|v|)` (e.g. a catalog CSV).

| Class | Parameters |
|---|---|
| `LinearDamper(G, A, c=None, law=None, active="both")` | `c` in N·s/mm, `v` in mm/s. `active`: `"both"`, `"extension"`, `"compression"` |
| `RotaryDamper(c=None, law=None, active="both")` | At the pivot. `c` in N·mm·s/rad. `active`: `"both"`, `"press"`, `"release"` |

### System: `LeverSystem`

```python
from pylever.mechanism import LeverSystem

system = LeverSystem(
    lever=lever, travel_deg=15,
    mass=0.5,            # kg, weight at the center of mass
    friction=3.0,        # N at the force application point: + on press, − on release
    inertia=0.004,       # kg·m² about the pivot (None: point mass at the center of mass)
    compression_springs=[...], extension_springs=[...], torsion_springs=[...],
    slider_crank=booster, dampers=[...],
)
```

On creation, it validates component types, unique names, and the geometry of each component relative to the pivot.

## Forward calculation

Complete example: [examples/direct_calculation.py](examples/direct_calculation.py).

```python
from springcalc import CompressionSpringGeneral, ExtensionSpring, Material, ureg
from pylever.components import CompressionSpring, LinearDamper, SliderCrank, TableLaw
from pylever.components import ExtensionSpring as LeverExtensionSpring
from pylever.geometry import Lever
from pylever.mechanism import LeverSystem, return_report

material = Material(material_name="SH")
ocs = CompressionSpringGeneral(material=material, wire_diameter=2.0)
ocs.set_geometry(f_mean_diameter=lambda h: 20 * ureg.mm, f_pitch=lambda h: 6 * ureg.mm,
                 free_length=60 * ureg.mm)
ocs.calculate_spring_properties()

ret = ExtensionSpring(material=material, wire_diameter=1.5, initial_force=5)
ret.set_diameter(outer_diameter=15)
ret.calculate_spring_properties(nr_coils=10, free_length=40)

system = LeverSystem(
    lever=Lever.from_xy(force=(0, -200), com=(0, -90)), travel_deg=15,
    mass=0.5, friction=3.0, inertia=0.004,
    compression_springs=[CompressionSpring((-50, 30), (0, -30), ocs, length_offset=-25, name="ocs")],
    extension_springs=[LeverExtensionSpring((60, 0), (0, -30), ret, name="return")],
    slider_crank=SliderCrank.from_xy(rod_anchor=(0, -40), cylinder_start=(-120, -40),
                                     cylinder_end=(-160, -40),
                                     force=TableLaw([0, 5, 10, 20], [0, 20, 60, 200])),
    dampers=[LinearDamper((60, -10), (0, -50), c=0.05, name="damper")],
)

curve = system.curve(n=41)
curve.travel      # chord of the force application point, mm
curve.force       # force without friction, N
curve.apply       # press (+ friction)
curve.release     # release (− friction)
curve.moments     # moment of each component, including "weight", N·mm

system.user_force(10, direction=+1)   # force at 10° while pressing
system.moments(10)                    # {"weight": ..., "ocs": ..., "return": ..., "slider_crank": ...}
```

Example output:

```
travel [mm]  apply [N]  release [N]
      0.00      13.48        7.48
      8.73      15.39        9.39
     17.45      17.27       11.27
     26.16      19.29       13.29
     34.86      22.45       16.45
     43.55      25.51       19.51
     52.21      28.85       22.85
```

### Free return (velocity and energy)

The user releases the lever at a percentage of its travel, and it returns on its own. The equation
`I·θ̈ = −(M_el + M_damper − M_friction)` is integrated until it reaches the rest stop or comes to a halt.

```python
results = system.free_return([25, 50, 75, 100])
print(return_report(results))

r = results[-1]
r.returned, r.stuck            # reaches the stop / does not start moving (held by friction)
r.time                         # time to the stop, s
r.impact_speed, r.impact_omega # speed at the force application point, m/s; rad/s
r.kinetic_energy               # kinetic energy at impact, J
r.elastic_energy               # energy released by springs + weight + slider-crank, J
r.friction_energy, r.damping_energy   # energy dissipated, J
r.balance_error                # check: Eel − Ekin − Wfr − Wdam ≈ 0
r.t, r.theta_deg, r.speed, r.kinetic  # curves over time
```

```
    %  θ0 [°]    status   t [ms]  v [m/s]  ω [rad/s]  Ekin [mJ]  Eel [mJ]  Wfr [mJ]  Wdam [mJ]
   25    3.75      stop     17.3    1.342      6.712      90.10    155.93     39.27      26.56
   50    7.50      stop     22.4    1.958      9.790     191.69    348.88     78.54      78.66
   75   11.25      stop     24.4    2.531     12.657     320.42    593.16    117.81     154.93
  100   15.00      stop     25.4    3.116     15.580     485.50    897.81    157.08     255.23
```

## Inverse calculation: finding springs

Complete example: [examples/inverse_design.py](examples/inverse_design.py).

**Inputs**: the customer curve in CSV (travel as the chord of the force application point in mm, force in N,
**without friction**), the number of springs of each type, and whether to use the slider-crank (which remains fixed).

```csv
travel,force
0,30
5,34.6
...
```

### Stage 1: anchors and ideal springs

```python
from pylever.mechanism import FitBounds

base = LeverSystem(lever, travel_deg=15, mass=0.5, friction=3.0, slider_crank=booster)

fit = base.fit_springs(
    "customer_curve.csv",
    compression=1, extension=1, torsion=0,
    use_slider_crank=True,
    bounds=FitBounds(ground_region=(-120, 120, -80, 60),   # allowed region for fixed anchors
                     lever_region=(-25, 25, -150, 0)),      # allowed region on the lever
    seed=1, maxiter=150,
)
print(fit.report())
fit.system     # LeverSystem with ideal springs
fit.springs    # per spring: type, anchors, parameters, and working range
```

- Variables: anchors `G` and `A` for each spring and its ideal parameters
  (compression: k, L0; extension: k, L0, F0; torsion: k, free angle, legs).
- Global optimizer `scipy.optimize.differential_evolution` minimizes the RMS error against the curve.
- Constraints: each spring is loaded throughout the entire travel (`require_active`) and compression
  deflection ≤ 60% of L0 (`max_deflection_ratio`). Limits can be adjusted in `FitBounds`.
- Mass, friction, inertia, the slider-crank, and dampers are taken from the base system;
  its springs are ignored.

### Stage 2: real compression springs with springcalc

```python
real = fit.realize_compression(material="SH", safety_factor=1.2, designer="conical", seed=1)
print(real.report())
real.system    # LeverSystem with real springs
real.designs   # springcalc design objects (wire, diameters, pitch, coils, safety factor...)
```

For each spring, its working force-deflection curve is generated and passed to the springcalc
inverse designer (`"conical"`: seconds; `"general"`: minutes or hours). Since the real free length
differs from the ideal one, `length_offset` (seats) is adjusted to maintain the deflection at each
position without moving the anchors. Extension and torsion springs currently retain their ideal
parameters (springcalc does not yet support their inverse design).

Example output:

```
Stage 1 (ideal springs)
RMS = 0.185 N, max error = 0.537 N (29893 evaluations)
  compression_1 [compression] G=(101.13, -78.46) A=(14.51, -20.54): k=12.58, free_length=136.1
      range: length=(104.2, 107.5), force=(359.5, 400.9)
  extension_1 [extension] G=(19.19, -70.84) A=(-2.71, -119.71): k=9.98, free_length=33.66, initial_force=20.59
      range: length=(53.55, 68.78), force=(219.1, 371.1)

Stage 2 (springcalc)
RMS = 0.185 N, max error = 0.537 N
  compression_1: d=4.25 mm, Dm=37.07 mm→44.66 mm, p=33.96 mm→17.72 mm, L0=93.07 mm, n=3.73, Lc=15.84 mm, FS=1.20, length_offset=-43.00 mm
```

The solution is not unique: constrain the anchor regions to the available physical space and set
`seed` for reproducible results.

## PDF report and spring export

`LeverReport` generates a PDF containing:

1. A system summary and the coordinates of all points.
2. A drawing of the mechanism at rest (solid line) and at full travel (dashed line).
3. A plot of each spring's load and a plot of pedal force: each component's contribution, the total
   without friction, press/release with friction, and, if provided, the customer curve.
4. A curve table and each spring's working points (rest and full travel).
5. The springcalc report for each spring (data, 3D view, curves, Goodman diagram), with the
   mechanism's working points used as load positions. Ideal (not yet designed) springs are shown
   as a parameter table.

```python
from pylever.report import LeverReport

report = LeverReport(system, title="Pedal 2021", target="customer_curve.csv")  # target is optional
report.build("pedal.pdf")                 # PDF only
report.export_springs("pedal_springs")    # <spring>.json and <spring>.step
report.export("pedal_out")                # everything: report.pdf + JSON + STEP
```

For each spring:

- **JSON**: `springcalc.save_model` format (can be read again with `springcalc.load_model`), with
  working points as positions and a `"pylever"` section containing the mounting information (anchors,
  `length_offset`) and working points. The original spring is not modified; a copy is used.
- **STEP** (requires `uv sync --extra step`): spring wire in its free state, along the Z axis, in
  the spring's local coordinates. Compression: springcalc exporter (any diameter and pitch profile).
  Extension: body with `nr_coils` turns and one complete eye at each end, adjusted so the inner
  distance between the eyes equals the free length. Torsion: body with tangent legs whose tips are
  `fixed_leg_radius`/`mobile_leg_radius` from the axis and form `free_angle` (the body angle is
  adjusted by less than half a turn). This is reference geometry for assembly and interference
  checks, not a manufacturing drawing for hooks or legs.

The slider-crank is treated as a spring when its force is a `SpringcalcLaw`.

## Limitations

- Quasi-static except for `free_return`: the mass of springs, rod, and piston is not considered.
- Torsion spring: the angle between the legs is constrained to (0°, 180°); the legs cannot pass through alignment.
- Global Coulomb friction is constant at the force application point.
- Stage 2 supports compression springs only.
- `springcalc` has no 3D view for extension springs; its report indicates this in that section.
