debug: measure lines against the slow axis, and stop hiding the MCS
CI for csaxs_bec / test (push) Successful in 1m42s

Two faults visible in the run against S00473 and S00254.

**Bug 1 reported nothing at all.** Candidates were restricted to the
`monitored` readout group, but the MCS channels -- which are the per-point scan
data, 203 x 428 = 86884 for S00473 -- are not in it. The filter excluded exactly
the arrays the check exists to examine, so both tables came out empty. The
restriction is gone; positions are still skipped, by ramp shape rather than by
group membership.

**Bug 2 could not find a line structure in S00473.** The monitored stream is
sampled while the line runs, so samples per line vary and the trace does not
reshape into a rectangle; requiring the sample count to divide evenly rejected
it outright. Segmentation now works from the boundaries themselves and tolerates
ragged lines.

That fix alone was not enough, and the reason matters. A line whose motion
failed produces no flyback, so it merges into its neighbour and the merged
segment shows a full, healthy span: **the stall erases the evidence of itself.**
Testing against ragged data with four stalls, the fast axis yielded 103 segments
for 107 lines and pronounced them all consistent.

So lines are now delimited by the **slow** axis, which steps once per line
whatever the fast axis did and stays a valid ruler across a stall. With that,
the same file gives exactly 107 segments and all four stalls, correctly reported
as clustering in the final tenth of the scan.

Where several positioner traces exist, the one with the largest travel per line
is taken as the fast axis and the runners-up are listed with their spans, so a
wrong pick is visible rather than silent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
menzelandClaude Opus 5 committed 2026-08-25 12:14:31 +02:00
1 parent 1b99ffeee9
commit 95409036bb
1 file changed
+73 -20
+73 -20
View File
@@ -167,6 +167,30 @@ def infer_grid(n: int, meta: dict) -> tuple[int, int] | None:
return None
def line_breaks(arr: np.ndarray) -> np.ndarray | None:
"""Indices where a scanned axis starts a new line.
Returns the boundaries themselves rather than a count, because the monitored
stream is sampled opportunistically: the number of samples per line varies,
so the trace cannot be reshaped into a rectangle. Segmenting on the actual
boundaries handles ragged lines, which is what these files contain.
"""
d = np.diff(arr)
nz = np.abs(d[d != 0])
if nz.size < 4:
return None
typical = float(np.median(nz))
if typical <= 0:
return None
for cand in (np.where(np.abs(d) > 5 * typical)[0] + 1, # raster flyback
np.where(np.diff(np.sign(np.where(d == 0, 1, d))) != 0)[0] + 1): # snake
if cand.size >= 2:
sizes = np.diff(np.concatenate(([0], cand, [arr.size])))
if sizes.min() >= 2 and sizes.size >= 3:
return cand
return None
def detect_lines(arr: np.ndarray) -> int | None:
"""Recover the number of lines from a scanned axis, without metadata.
@@ -266,8 +290,6 @@ def check_end_of_line(signals, grid, monitored, fast_axis) -> None:
if arr.size != lines * per_line:
continue
dev = name.split("/")[0]
if monitored and dev not in monitored:
continue
if fast_axis and name == fast_axis:
continue
block = arr.reshape(lines, per_line)
@@ -296,9 +318,6 @@ def check_end_of_line(signals, grid, monitored, fast_axis) -> None:
for name, arr in sorted(signals.items()):
if arr.size != lines * per_line:
continue
dev = name.split("/")[0]
if monitored and dev not in monitored:
continue
block = arr.reshape(lines, per_line)
if monotonicity(block) > 0.9:
continue
@@ -351,25 +370,59 @@ def check_line_motion_from_motor(signals, motors, meta) -> None:
return
expected = int(meta["num_lines"]) if meta.get("num_lines") else None
best = None
# Segment on the SLOW axis, not the fast one. The fast axis cannot define its
# own line boundaries here: a line where motion failed has no flyback, so it
# merges into its neighbour and the resulting segment looks perfectly healthy
# -- the stall erases the very evidence of itself. The slow axis steps once per
# line regardless of what the fast axis did, so it stays a valid ruler.
slow_name, slow_breaks = None, None
for name, arr in sorted(cands.items()):
found = detect_lines(arr)
if found and (best is None or (expected and abs(found - expected) < abs(best[1] - expected))):
best = (name, found, arr)
if best is None:
changes = np.where(np.abs(np.diff(arr)) > 0)[0] + 1
if changes.size == 0:
continue
if expected and abs(changes.size - (expected - 1)) <= max(1, 0.05 * expected):
slow_name, slow_breaks = name, changes
break
if slow_breaks is not None:
print(f" lines delimited by the slow axis {slow_name}"
f" ({slow_breaks.size + 1} segments)")
scored = []
for name, arr in sorted(cands.items()):
if name == slow_name:
continue
breaks = slow_breaks if slow_breaks is not None else line_breaks(arr)
if breaks is None:
continue
starts = np.concatenate(([0], breaks, [arr.size]))
segs = [arr[a:b] for a, b in zip(starts[:-1], starts[1:])]
spans = np.array([np.ptp(sg) for sg in segs])
if np.median(spans) <= 0:
continue
scored.append((name, arr, segs, spans))
if not scored:
print(f" positioner traces found ({', '.join(sorted(cands))}) but none shows")
print(" a line structure -- the axis may not have been the scanned one.")
print(" a line structure. For a continuous scan the position is sampled")
print(" while the line runs, so an irregular or too-sparse trace can hide it.")
return
name, found, arr = best
per_line = arr.size // found
print(f" fast axis : {name} ({arr.size} samples, {found} lines detected"
+ (f", metadata says {expected}" if expected else "") + ")")
if expected and found != expected:
print(f" NOTE: detected {found} lines but metadata says {expected}."
" Treat the per-line numbers below with care.")
block = arr[: found * per_line].reshape(found, per_line)
spans = np.ptp(block, axis=1)
# Prefer the trace whose travel per line is largest -- that is the scanned axis;
# the slow axis steps a little and the rest sit still.
scored.sort(key=lambda t: -float(np.median(t[3])))
if len(scored) > 1:
others = ", ".join(f"{n} (median span {np.median(sp):.4g}, {len(sg)} segments)"
for n, _, sg, sp in scored[1:4])
print(f" other positioner traces: {others}")
name, arr, segs, spans = scored[0]
found = len(segs)
per_line = int(np.median([len(sg) for sg in segs]))
print(f" fast axis : {name} ({arr.size} samples, {found} line segments"
+ (f", metadata says {expected} lines" if expected else "") + ")")
if expected and abs(found - expected) > max(1, 0.02 * expected):
print(f" NOTE: segmented into {found} but metadata says {expected}. The extra"
" or missing")
print(" boundaries are themselves suspicious -- a stalled line has no flyback.")
median = float(np.median(spans))
if median <= 0:
print(" the axis does not move -- check that this is the scanned motor")