mse_motion_ref.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #!/usr/bin/env python3
  2. """Independent MSE motion reference model (Scheme A full-feature math).
  3. Not a translation of RTL. Validates DDA / profile / travel-normalization semantics
  4. from the designated round-2 contract.
  5. """
  6. from __future__ import annotations
  7. from dataclasses import dataclass, field
  8. from typing import Iterable, List, Sequence, Tuple
  9. PROFILE_SCALE = (
  10. 64,
  11. 66,
  12. 73,
  13. 84,
  14. 98,
  15. 114,
  16. 132,
  17. 150,
  18. 170,
  19. 188,
  20. 206,
  21. 222,
  22. 236,
  23. 247,
  24. 254,
  25. 256,
  26. )
  27. PROFILE_FULL = 256
  28. MAX_STEP_HZ = 1000
  29. CLOCK_HZ = 25_000_000
  30. MOTION_SERVICE_US_DEFAULT = 25
  31. CAL_RAMP_UNIT = 8
  32. def derive_motion_params(clock_hz: int = CLOCK_HZ, motion_service_us: int = MOTION_SERVICE_US_DEFAULT):
  33. if motion_service_us <= 0 or motion_service_us > 50:
  34. raise ValueError("motion_service_us must be in 1..50")
  35. if (clock_hz * motion_service_us) % 1_000_000 != 0:
  36. raise ValueError("MOTION_SERVICE_CLKS must be integer")
  37. service_clks = (clock_hz * motion_service_us) // 1_000_000
  38. service_hz = clock_hz // service_clks
  39. numer = service_hz * PROFILE_FULL
  40. denom = 2 * MAX_STEP_HZ
  41. if numer % denom != 0:
  42. raise ValueError("PHASE_FACTOR must be integer exact")
  43. phase_factor = numer // denom
  44. return {
  45. "clock_hz": clock_hz,
  46. "motion_service_us": motion_service_us,
  47. "motion_service_clks": service_clks,
  48. "service_hz": service_hz,
  49. "phase_factor": phase_factor,
  50. "profile_full": PROFILE_FULL,
  51. "max_step_hz": MAX_STEP_HZ,
  52. }
  53. PARAMS = derive_motion_params()
  54. PHASE_FACTOR = PARAMS["phase_factor"]
  55. SERVICE_HZ = PARAMS["service_hz"]
  56. def profile_scale(level: int) -> int:
  57. if not 0 <= level <= 15:
  58. raise ValueError("level out of range")
  59. return PROFILE_SCALE[level]
  60. def ramp_unit(distance: int) -> int:
  61. if distance < 0:
  62. raise ValueError("distance must be >= 0")
  63. if distance == 0:
  64. return 1
  65. return max(1, (distance + 63) >> 6)
  66. def compute_level(done: int, remaining: int, unit: int) -> int:
  67. """level = min(15, floor(done/unit), floor((remaining-1)/unit))."""
  68. if unit < 1:
  69. unit = 1
  70. rem_term = 0 if remaining < 1 else (remaining - 1) // unit
  71. return min(15, done // unit, rem_term)
  72. def phase_threshold(max_travel: int, phase_factor: int = PHASE_FACTOR) -> int:
  73. return max_travel * phase_factor
  74. def rate_quantum(travel: int, level: int) -> int:
  75. return travel * profile_scale(level)
  76. def bit_width_needed(max_value: int) -> int:
  77. if max_value < 0:
  78. raise ValueError("negative")
  79. w = 0
  80. v = max_value
  81. while v:
  82. w += 1
  83. v >>= 1
  84. return max(w, 1)
  85. def assert_bit_widths() -> None:
  86. max_thr = 5000 * PHASE_FACTOR # 25_600_000
  87. max_rq = 5000 * 256 # 1_280_000
  88. # Actual max sum with rq<=travel*256 and thr=max_travel*5120 fits in 25 bits.
  89. # Contract still sizes RTL at 26 bits for the conservative bound (2*threshold-1).
  90. max_sum_actual = (max_thr - 1) + max_rq
  91. max_sum_contract = 2 * max_thr - 1
  92. assert bit_width_needed(max_thr) == 25
  93. assert bit_width_needed(max_rq) == 21
  94. assert bit_width_needed(max_sum_actual) == 25
  95. assert bit_width_needed(max_sum_contract) == 26
  96. @dataclass
  97. class AxisDda:
  98. travel: int
  99. max_travel: int
  100. phase: int = 0
  101. level: int = 0
  102. done: int = 0
  103. distance: int = 0
  104. unit: int = 1
  105. active: bool = False
  106. cal_mode: bool = False
  107. crawl: bool = False
  108. toggles: int = 0
  109. rises: int = 0
  110. @property
  111. def threshold(self) -> int:
  112. if self.cal_mode:
  113. return PHASE_FACTOR
  114. return phase_threshold(self.max_travel)
  115. @property
  116. def quantum(self) -> int:
  117. if self.crawl:
  118. lvl = 0
  119. else:
  120. lvl = self.level
  121. if self.cal_mode:
  122. return profile_scale(lvl)
  123. return rate_quantum(self.travel, lvl)
  124. def service(self) -> bool:
  125. """One motion service update. Returns True if toggle fired."""
  126. if not self.active:
  127. return False
  128. thr = self.threshold
  129. rq = self.quantum
  130. if rq <= 0 or rq > thr:
  131. raise AssertionError(f"bad quantum {rq} thr {thr}")
  132. if self.phase >= thr:
  133. raise AssertionError("accumulator must stay < threshold")
  134. s = self.phase + rq
  135. if s >= thr:
  136. self.phase = s - thr
  137. if self.phase >= thr:
  138. raise AssertionError("post-subtract still >= thr")
  139. self.toggles += 1
  140. return True
  141. self.phase = s
  142. return False
  143. def on_gated_rise(self) -> None:
  144. self.rises += 1
  145. self.done += 1
  146. if self.cal_mode:
  147. # soft-start only: every CAL_RAMP_UNIT rises bump level
  148. if self.level < 15 and (self.rises % CAL_RAMP_UNIT) == 0:
  149. self.level += 1
  150. else:
  151. remaining = max(0, self.distance - self.done)
  152. self.level = compute_level(self.done, remaining, self.unit)
  153. def long_run_step_hz(travel: int, max_travel: int, level: int, services: int = 400_000) -> float:
  154. """Measure average STEP rise rate over many services (toggle/2 ≈ rise)."""
  155. ax = AxisDda(travel=travel, max_travel=max_travel, level=level, active=True, distance=10**9, unit=1)
  156. toggles = 0
  157. for _ in range(services):
  158. if ax.service():
  159. toggles += 1
  160. rises = toggles / 2.0
  161. seconds = services / SERVICE_HZ
  162. return rises / seconds
  163. def expected_step_hz(travel: int, max_travel: int, level: int) -> float:
  164. return MAX_STEP_HZ * (travel / max_travel) * (profile_scale(level) / PROFILE_FULL)
  165. def level_sequence(distance: int) -> List[int]:
  166. unit = ramp_unit(distance)
  167. seq = []
  168. done = 0
  169. for _ in range(distance):
  170. remaining = distance - done
  171. lvl = compute_level(done, remaining, unit)
  172. seq.append(lvl)
  173. done += 1
  174. return seq
  175. def check_level_shape(distance: int) -> None:
  176. seq = level_sequence(distance)
  177. assert all(0 <= x <= 15 for x in seq)
  178. if not seq:
  179. return
  180. # Find peak region; accel non-decreasing to first peak, decel non-increasing after last peak
  181. peak = max(seq)
  182. first = seq.index(peak)
  183. last = len(seq) - 1 - seq[::-1].index(peak)
  184. for i in range(1, first + 1):
  185. assert seq[i] >= seq[i - 1], (distance, i, seq)
  186. for i in range(last + 1, len(seq)):
  187. assert seq[i] <= seq[i - 1], (distance, i, seq)
  188. def simulate_move_time_services(
  189. travel: int,
  190. max_travel: int,
  191. distance: int,
  192. ) -> int:
  193. """Services from first rise to last target rise (inclusive window via toggles)."""
  194. if distance <= 0:
  195. return 0
  196. ax = AxisDda(
  197. travel=travel,
  198. max_travel=max_travel,
  199. active=True,
  200. distance=distance,
  201. unit=ramp_unit(distance),
  202. level=0,
  203. )
  204. services = 0
  205. rises = 0
  206. first_rise_svc = None
  207. last_rise_svc = None
  208. # Drive until distance gated rises
  209. while rises < distance:
  210. services += 1
  211. if ax.service():
  212. # treat every other toggle as rise starting from low
  213. # start step low; odd toggles are rises
  214. if ax.toggles % 2 == 1:
  215. ax.on_gated_rise()
  216. rises += 1
  217. if first_rise_svc is None:
  218. first_rise_svc = services
  219. last_rise_svc = services
  220. if services > 50_000_000:
  221. raise RuntimeError("simulate runaway")
  222. assert first_rise_svc is not None and last_rise_svc is not None
  223. return last_rise_svc - first_rise_svc + 1
  224. def timing_alignment_ok(
  225. travels: Sequence[int],
  226. from_pct: int,
  227. to_pct: int,
  228. tol_frac: float = 0.02,
  229. tol_ms: float = 5.0,
  230. ) -> Tuple[bool, dict]:
  231. max_travel = max(travels)
  232. distances = []
  233. for tr in travels:
  234. # half-up percent positions
  235. def pos(p: int, travel: int = tr) -> int:
  236. if p <= 0:
  237. return 0
  238. if p >= 100:
  239. return travel
  240. v = (travel * p + 50) // 100
  241. return min(max(v, 1), travel - 1)
  242. distances.append(abs(pos(to_pct) - pos(from_pct)))
  243. # Skip axes with zero mid-distance (tiny travel + mid-mid can collapse)
  244. pairs = [(tr, d) for tr, d in zip(travels, distances) if d > 0]
  245. if len(pairs) < 2:
  246. return True, {
  247. "travels": list(travels),
  248. "distances": distances,
  249. "seconds": [],
  250. "delta": 0.0,
  251. "budget": 0.0,
  252. "ok": True,
  253. "note": "insufficient nonzero distances for alignment check",
  254. }
  255. times = [simulate_move_time_services(tr, max_travel, d) for tr, d in pairs]
  256. seconds = [t / SERVICE_HZ for t in times]
  257. lo, hi = min(seconds), max(seconds)
  258. budget = max(tol_frac * hi, tol_ms / 1000.0)
  259. ok = (hi - lo) <= budget
  260. return ok, {
  261. "travels": list(travels),
  262. "distances": distances,
  263. "seconds": seconds,
  264. "delta": hi - lo,
  265. "budget": budget,
  266. "ok": ok,
  267. }
  268. @dataclass
  269. class EndpointSimResult:
  270. profile_levels: List[int]
  271. crawl_levels: List[int]
  272. crawl_rises: int
  273. completed: bool
  274. faulted: bool
  275. early_limit: bool
  276. def simulate_endpoint_two_phase(
  277. travel: int,
  278. *,
  279. start_pos: int,
  280. close: bool,
  281. limit_at_rise: int | None = None,
  282. crawl_extra_before_limit: int = 0,
  283. never_limit: bool = False,
  284. guard_extra: int = 500,
  285. ) -> EndpointSimResult:
  286. """Reference: S-curve to estimate, then optional level-0 crawl.
  287. limit_at_rise: absolute gated-rise index (1-based from move start) when limit asserts.
  288. None + never_limit → crawl until travel+guard_extra then fault.
  289. None + crawl_extra_before_limit → limit asserts that many crawl rises after estimate.
  290. """
  291. target = travel if close else 0
  292. distance = abs(start_pos - target)
  293. ax = AxisDda(
  294. travel=travel,
  295. max_travel=travel,
  296. active=True,
  297. distance=max(distance, 1) if distance else 0,
  298. unit=ramp_unit(distance) if distance else 1,
  299. level=0,
  300. crawl=False,
  301. )
  302. profile_levels: List[int] = []
  303. crawl_levels: List[int] = []
  304. pos = start_pos
  305. rises = 0
  306. crawl_rises = 0
  307. in_crawl = distance == 0
  308. if in_crawl:
  309. ax.crawl = True
  310. ax.distance = 10**9
  311. completed = False
  312. faulted = False
  313. early_limit = False
  314. guard = travel + guard_extra
  315. # Drive toggles until done; count rises on odd toggles
  316. services = 0
  317. while True:
  318. services += 1
  319. if services > 20_000_000:
  320. raise RuntimeError("endpoint sim runaway")
  321. if not ax.service():
  322. continue
  323. if ax.toggles % 2 != 1:
  324. continue
  325. # gated rise
  326. rises += 1
  327. if close:
  328. if pos < travel:
  329. pos += 1
  330. else:
  331. if pos > 0:
  332. pos -= 1
  333. if not in_crawl:
  334. profile_levels.append(ax.level)
  335. ax.on_gated_rise()
  336. at_est = pos == target
  337. if limit_at_rise is not None and rises >= limit_at_rise and not at_est:
  338. early_limit = True
  339. completed = True
  340. break
  341. if at_est:
  342. if limit_at_rise is not None and rises >= limit_at_rise:
  343. completed = True
  344. break
  345. in_crawl = True
  346. ax.crawl = True
  347. ax.level = 0
  348. continue
  349. else:
  350. crawl_rises += 1
  351. crawl_levels.append(0)
  352. if never_limit:
  353. if rises >= guard:
  354. faulted = True
  355. break
  356. else:
  357. need = crawl_extra_before_limit
  358. if limit_at_rise is not None:
  359. if rises >= limit_at_rise:
  360. completed = True
  361. break
  362. elif crawl_rises > need:
  363. completed = True
  364. break
  365. if rises >= guard:
  366. faulted = True
  367. break
  368. return EndpointSimResult(
  369. profile_levels=profile_levels,
  370. crawl_levels=crawl_levels,
  371. crawl_rises=crawl_rises,
  372. completed=completed,
  373. faulted=faulted,
  374. early_limit=early_limit,
  375. )
  376. def run_selftest() -> None:
  377. assert PARAMS["phase_factor"] == 5120
  378. assert PARAMS["motion_service_clks"] == 625
  379. assert_bit_widths()
  380. # long-run rates
  381. hz15 = long_run_step_hz(5000, 5000, 15, services=200_000)
  382. assert abs(hz15 - 1000.0) / 1000.0 < 0.01, hz15
  383. hz0 = long_run_step_hz(5000, 5000, 0, services=200_000)
  384. assert abs(hz0 - 250.0) / 250.0 < 0.02, hz0
  385. short = long_run_step_hz(2500, 5000, 15, services=200_000)
  386. assert abs(short - 500.0) / 500.0 < 0.02, short
  387. for d in (1, 2, 3, 63, 64, 65, 127, 128, 129, 5000):
  388. check_level_shape(d)
  389. for travels in ((5000, 3500, 2000), (4800, 4100, 2750)):
  390. ok, info = timing_alignment_ok(travels, 0, 100)
  391. assert ok, info
  392. ok2, info2 = timing_alignment_ok(travels, 20, 80)
  393. assert ok2, info2
  394. ok3, info3 = timing_alignment_ok(travels, 25, 75)
  395. assert ok3, info3
  396. # Extreme tiny travel vs max: document separately (not silently widen tolerance).
  397. ok_ex, info_ex = timing_alignment_ok((5000, 4999, 2), 0, 100)
  398. assert not ok_ex, "expected extreme 2-step axis to miss 2% budget vs 5000"
  399. assert info_ex["delta"] > info_ex["budget"]
  400. # Near-equal long axes still align when tiny axis excluded by zero/skip? keep pair check:
  401. ok_pair, info_pair = timing_alignment_ok((5000, 4999), 0, 100)
  402. assert ok_pair, info_pair
  403. # 50us still exact
  404. p50 = derive_motion_params(motion_service_us=50)
  405. assert p50["phase_factor"] == 2560
  406. # Endpoint two-phase: 0→100 should accel then crawl level0
  407. ep = simulate_endpoint_two_phase(64, start_pos=0, close=True, crawl_extra_before_limit=3)
  408. assert ep.completed and not ep.faulted
  409. assert max(ep.profile_levels) > 0, ep.profile_levels
  410. assert ep.crawl_rises == 4 # >3 means assert after 4th? wait: crawl_rises > need → need=3 means 4 rises
  411. assert all(x == 0 for x in ep.crawl_levels)
  412. ep_early = simulate_endpoint_two_phase(64, start_pos=0, close=True, limit_at_rise=10)
  413. assert ep_early.early_limit and ep_early.completed
  414. assert ep_early.crawl_rises == 0
  415. ep_fault = simulate_endpoint_two_phase(8, start_pos=0, close=True, never_limit=True, guard_extra=2)
  416. assert ep_fault.faulted and ep_fault.crawl_rises >= 1
  417. print("mse_motion_ref selftest PASS")
  418. print("extreme_tiny_travel_note:", {k: info_ex[k] for k in ("travels", "distances", "seconds", "delta", "budget")})
  419. if __name__ == "__main__":
  420. run_selftest()