| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476 |
- #!/usr/bin/env python3
- """Independent MSE motion reference model (Scheme A full-feature math).
- Not a translation of RTL. Validates DDA / profile / travel-normalization semantics
- from the designated round-2 contract.
- """
- from __future__ import annotations
- from dataclasses import dataclass, field
- from typing import Iterable, List, Sequence, Tuple
- PROFILE_SCALE = (
- 64,
- 66,
- 73,
- 84,
- 98,
- 114,
- 132,
- 150,
- 170,
- 188,
- 206,
- 222,
- 236,
- 247,
- 254,
- 256,
- )
- PROFILE_FULL = 256
- MAX_STEP_HZ = 1000
- CLOCK_HZ = 25_000_000
- MOTION_SERVICE_US_DEFAULT = 25
- CAL_RAMP_UNIT = 8
- def derive_motion_params(clock_hz: int = CLOCK_HZ, motion_service_us: int = MOTION_SERVICE_US_DEFAULT):
- if motion_service_us <= 0 or motion_service_us > 50:
- raise ValueError("motion_service_us must be in 1..50")
- if (clock_hz * motion_service_us) % 1_000_000 != 0:
- raise ValueError("MOTION_SERVICE_CLKS must be integer")
- service_clks = (clock_hz * motion_service_us) // 1_000_000
- service_hz = clock_hz // service_clks
- numer = service_hz * PROFILE_FULL
- denom = 2 * MAX_STEP_HZ
- if numer % denom != 0:
- raise ValueError("PHASE_FACTOR must be integer exact")
- phase_factor = numer // denom
- return {
- "clock_hz": clock_hz,
- "motion_service_us": motion_service_us,
- "motion_service_clks": service_clks,
- "service_hz": service_hz,
- "phase_factor": phase_factor,
- "profile_full": PROFILE_FULL,
- "max_step_hz": MAX_STEP_HZ,
- }
- PARAMS = derive_motion_params()
- PHASE_FACTOR = PARAMS["phase_factor"]
- SERVICE_HZ = PARAMS["service_hz"]
- def profile_scale(level: int) -> int:
- if not 0 <= level <= 15:
- raise ValueError("level out of range")
- return PROFILE_SCALE[level]
- def ramp_unit(distance: int) -> int:
- if distance < 0:
- raise ValueError("distance must be >= 0")
- if distance == 0:
- return 1
- return max(1, (distance + 63) >> 6)
- def compute_level(done: int, remaining: int, unit: int) -> int:
- """level = min(15, floor(done/unit), floor((remaining-1)/unit))."""
- if unit < 1:
- unit = 1
- rem_term = 0 if remaining < 1 else (remaining - 1) // unit
- return min(15, done // unit, rem_term)
- def phase_threshold(max_travel: int, phase_factor: int = PHASE_FACTOR) -> int:
- return max_travel * phase_factor
- def rate_quantum(travel: int, level: int) -> int:
- return travel * profile_scale(level)
- def bit_width_needed(max_value: int) -> int:
- if max_value < 0:
- raise ValueError("negative")
- w = 0
- v = max_value
- while v:
- w += 1
- v >>= 1
- return max(w, 1)
- def assert_bit_widths() -> None:
- max_thr = 5000 * PHASE_FACTOR # 25_600_000
- max_rq = 5000 * 256 # 1_280_000
- # Actual max sum with rq<=travel*256 and thr=max_travel*5120 fits in 25 bits.
- # Contract still sizes RTL at 26 bits for the conservative bound (2*threshold-1).
- max_sum_actual = (max_thr - 1) + max_rq
- max_sum_contract = 2 * max_thr - 1
- assert bit_width_needed(max_thr) == 25
- assert bit_width_needed(max_rq) == 21
- assert bit_width_needed(max_sum_actual) == 25
- assert bit_width_needed(max_sum_contract) == 26
- @dataclass
- class AxisDda:
- travel: int
- max_travel: int
- phase: int = 0
- level: int = 0
- done: int = 0
- distance: int = 0
- unit: int = 1
- active: bool = False
- cal_mode: bool = False
- crawl: bool = False
- toggles: int = 0
- rises: int = 0
- @property
- def threshold(self) -> int:
- if self.cal_mode:
- return PHASE_FACTOR
- return phase_threshold(self.max_travel)
- @property
- def quantum(self) -> int:
- if self.crawl:
- lvl = 0
- else:
- lvl = self.level
- if self.cal_mode:
- return profile_scale(lvl)
- return rate_quantum(self.travel, lvl)
- def service(self) -> bool:
- """One motion service update. Returns True if toggle fired."""
- if not self.active:
- return False
- thr = self.threshold
- rq = self.quantum
- if rq <= 0 or rq > thr:
- raise AssertionError(f"bad quantum {rq} thr {thr}")
- if self.phase >= thr:
- raise AssertionError("accumulator must stay < threshold")
- s = self.phase + rq
- if s >= thr:
- self.phase = s - thr
- if self.phase >= thr:
- raise AssertionError("post-subtract still >= thr")
- self.toggles += 1
- return True
- self.phase = s
- return False
- def on_gated_rise(self) -> None:
- self.rises += 1
- self.done += 1
- if self.cal_mode:
- # soft-start only: every CAL_RAMP_UNIT rises bump level
- if self.level < 15 and (self.rises % CAL_RAMP_UNIT) == 0:
- self.level += 1
- else:
- remaining = max(0, self.distance - self.done)
- self.level = compute_level(self.done, remaining, self.unit)
- def long_run_step_hz(travel: int, max_travel: int, level: int, services: int = 400_000) -> float:
- """Measure average STEP rise rate over many services (toggle/2 ≈ rise)."""
- ax = AxisDda(travel=travel, max_travel=max_travel, level=level, active=True, distance=10**9, unit=1)
- toggles = 0
- for _ in range(services):
- if ax.service():
- toggles += 1
- rises = toggles / 2.0
- seconds = services / SERVICE_HZ
- return rises / seconds
- def expected_step_hz(travel: int, max_travel: int, level: int) -> float:
- return MAX_STEP_HZ * (travel / max_travel) * (profile_scale(level) / PROFILE_FULL)
- def level_sequence(distance: int) -> List[int]:
- unit = ramp_unit(distance)
- seq = []
- done = 0
- for _ in range(distance):
- remaining = distance - done
- lvl = compute_level(done, remaining, unit)
- seq.append(lvl)
- done += 1
- return seq
- def check_level_shape(distance: int) -> None:
- seq = level_sequence(distance)
- assert all(0 <= x <= 15 for x in seq)
- if not seq:
- return
- # Find peak region; accel non-decreasing to first peak, decel non-increasing after last peak
- peak = max(seq)
- first = seq.index(peak)
- last = len(seq) - 1 - seq[::-1].index(peak)
- for i in range(1, first + 1):
- assert seq[i] >= seq[i - 1], (distance, i, seq)
- for i in range(last + 1, len(seq)):
- assert seq[i] <= seq[i - 1], (distance, i, seq)
- def simulate_move_time_services(
- travel: int,
- max_travel: int,
- distance: int,
- ) -> int:
- """Services from first rise to last target rise (inclusive window via toggles)."""
- if distance <= 0:
- return 0
- ax = AxisDda(
- travel=travel,
- max_travel=max_travel,
- active=True,
- distance=distance,
- unit=ramp_unit(distance),
- level=0,
- )
- services = 0
- rises = 0
- first_rise_svc = None
- last_rise_svc = None
- # Drive until distance gated rises
- while rises < distance:
- services += 1
- if ax.service():
- # treat every other toggle as rise starting from low
- # start step low; odd toggles are rises
- if ax.toggles % 2 == 1:
- ax.on_gated_rise()
- rises += 1
- if first_rise_svc is None:
- first_rise_svc = services
- last_rise_svc = services
- if services > 50_000_000:
- raise RuntimeError("simulate runaway")
- assert first_rise_svc is not None and last_rise_svc is not None
- return last_rise_svc - first_rise_svc + 1
- def timing_alignment_ok(
- travels: Sequence[int],
- from_pct: int,
- to_pct: int,
- tol_frac: float = 0.02,
- tol_ms: float = 5.0,
- ) -> Tuple[bool, dict]:
- max_travel = max(travels)
- distances = []
- for tr in travels:
- # half-up percent positions
- def pos(p: int, travel: int = tr) -> int:
- if p <= 0:
- return 0
- if p >= 100:
- return travel
- v = (travel * p + 50) // 100
- return min(max(v, 1), travel - 1)
- distances.append(abs(pos(to_pct) - pos(from_pct)))
- # Skip axes with zero mid-distance (tiny travel + mid-mid can collapse)
- pairs = [(tr, d) for tr, d in zip(travels, distances) if d > 0]
- if len(pairs) < 2:
- return True, {
- "travels": list(travels),
- "distances": distances,
- "seconds": [],
- "delta": 0.0,
- "budget": 0.0,
- "ok": True,
- "note": "insufficient nonzero distances for alignment check",
- }
- times = [simulate_move_time_services(tr, max_travel, d) for tr, d in pairs]
- seconds = [t / SERVICE_HZ for t in times]
- lo, hi = min(seconds), max(seconds)
- budget = max(tol_frac * hi, tol_ms / 1000.0)
- ok = (hi - lo) <= budget
- return ok, {
- "travels": list(travels),
- "distances": distances,
- "seconds": seconds,
- "delta": hi - lo,
- "budget": budget,
- "ok": ok,
- }
- @dataclass
- class EndpointSimResult:
- profile_levels: List[int]
- crawl_levels: List[int]
- crawl_rises: int
- completed: bool
- faulted: bool
- early_limit: bool
- def simulate_endpoint_two_phase(
- travel: int,
- *,
- start_pos: int,
- close: bool,
- limit_at_rise: int | None = None,
- crawl_extra_before_limit: int = 0,
- never_limit: bool = False,
- guard_extra: int = 500,
- ) -> EndpointSimResult:
- """Reference: S-curve to estimate, then optional level-0 crawl.
- limit_at_rise: absolute gated-rise index (1-based from move start) when limit asserts.
- None + never_limit → crawl until travel+guard_extra then fault.
- None + crawl_extra_before_limit → limit asserts that many crawl rises after estimate.
- """
- target = travel if close else 0
- distance = abs(start_pos - target)
- ax = AxisDda(
- travel=travel,
- max_travel=travel,
- active=True,
- distance=max(distance, 1) if distance else 0,
- unit=ramp_unit(distance) if distance else 1,
- level=0,
- crawl=False,
- )
- profile_levels: List[int] = []
- crawl_levels: List[int] = []
- pos = start_pos
- rises = 0
- crawl_rises = 0
- in_crawl = distance == 0
- if in_crawl:
- ax.crawl = True
- ax.distance = 10**9
- completed = False
- faulted = False
- early_limit = False
- guard = travel + guard_extra
- # Drive toggles until done; count rises on odd toggles
- services = 0
- while True:
- services += 1
- if services > 20_000_000:
- raise RuntimeError("endpoint sim runaway")
- if not ax.service():
- continue
- if ax.toggles % 2 != 1:
- continue
- # gated rise
- rises += 1
- if close:
- if pos < travel:
- pos += 1
- else:
- if pos > 0:
- pos -= 1
- if not in_crawl:
- profile_levels.append(ax.level)
- ax.on_gated_rise()
- at_est = pos == target
- if limit_at_rise is not None and rises >= limit_at_rise and not at_est:
- early_limit = True
- completed = True
- break
- if at_est:
- if limit_at_rise is not None and rises >= limit_at_rise:
- completed = True
- break
- in_crawl = True
- ax.crawl = True
- ax.level = 0
- continue
- else:
- crawl_rises += 1
- crawl_levels.append(0)
- if never_limit:
- if rises >= guard:
- faulted = True
- break
- else:
- need = crawl_extra_before_limit
- if limit_at_rise is not None:
- if rises >= limit_at_rise:
- completed = True
- break
- elif crawl_rises > need:
- completed = True
- break
- if rises >= guard:
- faulted = True
- break
- return EndpointSimResult(
- profile_levels=profile_levels,
- crawl_levels=crawl_levels,
- crawl_rises=crawl_rises,
- completed=completed,
- faulted=faulted,
- early_limit=early_limit,
- )
- def run_selftest() -> None:
- assert PARAMS["phase_factor"] == 5120
- assert PARAMS["motion_service_clks"] == 625
- assert_bit_widths()
- # long-run rates
- hz15 = long_run_step_hz(5000, 5000, 15, services=200_000)
- assert abs(hz15 - 1000.0) / 1000.0 < 0.01, hz15
- hz0 = long_run_step_hz(5000, 5000, 0, services=200_000)
- assert abs(hz0 - 250.0) / 250.0 < 0.02, hz0
- short = long_run_step_hz(2500, 5000, 15, services=200_000)
- assert abs(short - 500.0) / 500.0 < 0.02, short
- for d in (1, 2, 3, 63, 64, 65, 127, 128, 129, 5000):
- check_level_shape(d)
- for travels in ((5000, 3500, 2000), (4800, 4100, 2750)):
- ok, info = timing_alignment_ok(travels, 0, 100)
- assert ok, info
- ok2, info2 = timing_alignment_ok(travels, 20, 80)
- assert ok2, info2
- ok3, info3 = timing_alignment_ok(travels, 25, 75)
- assert ok3, info3
- # Extreme tiny travel vs max: document separately (not silently widen tolerance).
- ok_ex, info_ex = timing_alignment_ok((5000, 4999, 2), 0, 100)
- assert not ok_ex, "expected extreme 2-step axis to miss 2% budget vs 5000"
- assert info_ex["delta"] > info_ex["budget"]
- # Near-equal long axes still align when tiny axis excluded by zero/skip? keep pair check:
- ok_pair, info_pair = timing_alignment_ok((5000, 4999), 0, 100)
- assert ok_pair, info_pair
- # 50us still exact
- p50 = derive_motion_params(motion_service_us=50)
- assert p50["phase_factor"] == 2560
- # Endpoint two-phase: 0→100 should accel then crawl level0
- ep = simulate_endpoint_two_phase(64, start_pos=0, close=True, crawl_extra_before_limit=3)
- assert ep.completed and not ep.faulted
- assert max(ep.profile_levels) > 0, ep.profile_levels
- assert ep.crawl_rises == 4 # >3 means assert after 4th? wait: crawl_rises > need → need=3 means 4 rises
- assert all(x == 0 for x in ep.crawl_levels)
- ep_early = simulate_endpoint_two_phase(64, start_pos=0, close=True, limit_at_rise=10)
- assert ep_early.early_limit and ep_early.completed
- assert ep_early.crawl_rises == 0
- ep_fault = simulate_endpoint_two_phase(8, start_pos=0, close=True, never_limit=True, guard_extra=2)
- assert ep_fault.faulted and ep_fault.crawl_rises >= 1
- print("mse_motion_ref selftest PASS")
- print("extreme_tiny_travel_note:", {k: info_ex[k] for k in ("travels", "distances", "seconds", "delta", "budget")})
- if __name__ == "__main__":
- run_selftest()
|