Compare commits
2
Commits
429b823b44
...
f053723791
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f053723791 | ||
|
|
e6e7de0375 |
+62
-68
@@ -836,42 +836,50 @@ def _clean_output(directory: Path) -> None:
|
||||
stale.unlink()
|
||||
|
||||
|
||||
def summarise_repeats(runs: list[list[dict]], tolerance_px: float = 0.0) -> list[dict]:
|
||||
"""Mean and standard deviation of each line over repeated frames.
|
||||
def ten_percent_widths(spectrum: "SpectrumData", line: dict,
|
||||
fraction: float = 0.10,
|
||||
limit_px: float = float("nan")) -> dict:
|
||||
"""Left and right half-widths where the profile falls to ``fraction`` of the peak.
|
||||
|
||||
Cross-frame matching uses the nearest centre within `tolerance` (default
|
||||
1.5 x the reference FWHM), so a line that drifts by more than that is left as
|
||||
a missing sample instead of being matched to its neighbour.
|
||||
Measured on the primary channel's net profile, relative to the fitted centre,
|
||||
with linear interpolation between samples. The ratio right/left is a direct
|
||||
asymmetry measure: 1.0 is symmetric, >1 means the red wing is broader.
|
||||
"""
|
||||
|
||||
if not runs:
|
||||
return []
|
||||
reference = runs[0]
|
||||
summary = []
|
||||
for line in reference:
|
||||
width = line["fwhm_px"] if np.isfinite(line["fwhm_px"]) else 8.0
|
||||
limit = tolerance_px if tolerance_px > 0 else max(2.0, 1.5 * width)
|
||||
centres, widths = [], []
|
||||
for run in runs:
|
||||
match = None
|
||||
for candidate in run:
|
||||
distance = abs(candidate["sensor_x_px"] - line["sensor_x_px"])
|
||||
if distance <= limit and (match is None or distance < abs(
|
||||
match["sensor_x_px"] - line["sensor_x_px"])):
|
||||
match = candidate
|
||||
if match is None:
|
||||
continue
|
||||
centres.append(match["sensor_x_px"])
|
||||
if np.isfinite(match["fwhm_px"]):
|
||||
widths.append(match["fwhm_px"])
|
||||
entry = {"id": line["id"], "n": len(centres),
|
||||
"x_mean": float(np.mean(centres)) if centres else float("nan"),
|
||||
"x_std": float(np.std(centres, ddof=1)) if len(centres) > 1 else float("nan"),
|
||||
"fwhm_mean": float(np.mean(widths)) if widths else float("nan"),
|
||||
"fwhm_std": float(np.std(widths, ddof=1)) if len(widths) > 1 else float("nan"),
|
||||
"wavelength_nm": line.get("wavelength_nm", float("nan"))}
|
||||
summary.append(entry)
|
||||
return summary
|
||||
channel = line.get("primary_channel") or next(iter(line["channels"]))
|
||||
peak = line["channels"][channel]
|
||||
x = spectrum.x_px[channel]
|
||||
net = spectrum.net[channel]
|
||||
center = float(peak["center_px"])
|
||||
height = float(peak["height_net_adu"])
|
||||
empty = {"channel": channel, "left_px": float("nan"), "right_px": float("nan"),
|
||||
"ratio": float("nan"), "level_adu": float("nan")}
|
||||
if not np.isfinite(center) or not np.isfinite(height) or height <= 0:
|
||||
return empty
|
||||
level = fraction * height
|
||||
index = int(np.argmin(np.abs(x - center)))
|
||||
|
||||
def walk(step: int) -> float:
|
||||
previous = float(net[index])
|
||||
position = index
|
||||
while 0 <= position + step < net.size:
|
||||
if np.isfinite(limit_px) and abs(float(x[position]) - center) > limit_px:
|
||||
return float("nan") # the wing is cut off by the next line
|
||||
position += step
|
||||
current = float(net[position])
|
||||
if current <= level:
|
||||
# interpolate between the two bracketing samples
|
||||
span = previous - current
|
||||
offset = (previous - level) / span if span else 0.0
|
||||
return float(x[position]) - step * offset * float(x[1] - x[0])
|
||||
previous = current
|
||||
return float("nan")
|
||||
|
||||
left = center - walk(-1)
|
||||
right = walk(+1) - center
|
||||
ratio = (right / left) if np.isfinite(left) and np.isfinite(right) and left > 0 else float("nan")
|
||||
return {"channel": channel, "left_px": left, "right_px": right,
|
||||
"ratio": ratio, "level_adu": level}
|
||||
|
||||
|
||||
def export_all(hq, spectrum: SpectrumData, lines: list[dict], calibration,
|
||||
@@ -1351,8 +1359,6 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
detect.add_argument("--fit-window", type=float, default=0.0, metavar="PX",
|
||||
help="half-width of the fit window in sensor px; 0 = automatic")
|
||||
detect.add_argument("--shape", choices=SHAPES, default="gauss", help="line-shape model")
|
||||
detect.add_argument("--stability", type=int, default=1, metavar="N",
|
||||
help="also analyse N consecutive frames and report centre/FWHM scatter")
|
||||
|
||||
export = parser.add_argument_group("selection and export")
|
||||
export.add_argument("--select", default="all", metavar="TOKENS",
|
||||
@@ -1378,8 +1384,6 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
def validate_arguments(args) -> None:
|
||||
if args.average < 1:
|
||||
raise ValueError("--average must be >= 1")
|
||||
if args.stability < 1:
|
||||
raise ValueError("--stability must be >= 1")
|
||||
if args.max_peaks < 1:
|
||||
raise ValueError("--max-peaks must be >= 1")
|
||||
if args.peak_distance <= 0 or args.baseline_window < 0 or args.fwhm_span <= 0:
|
||||
@@ -1499,43 +1503,23 @@ def run(args) -> int:
|
||||
else:
|
||||
selected = parse_selection(args.select, lines)
|
||||
|
||||
summary = None
|
||||
if getattr(args, "stability", 1) > 1:
|
||||
base_frame, runs = args.frame, [lines]
|
||||
try:
|
||||
for step in range(1, args.stability):
|
||||
args.frame, args.average = base_frame + step, 1
|
||||
try:
|
||||
runs.append(analyse(args, tell=lambda *a, **k: None).lines)
|
||||
except (ValueError, RuntimeError, OSError):
|
||||
break
|
||||
finally:
|
||||
args.frame = base_frame
|
||||
if len(runs) > 1:
|
||||
summary = summarise_repeats(runs)
|
||||
|
||||
if args.output is None:
|
||||
args.output = str(default_output_directory(args.input, indices))
|
||||
meta_out = {"created": _timestamp(),
|
||||
"recording": str(Path(args.input).expanduser().resolve())}
|
||||
result = export_all(hq, spectrum, lines, calibration, selected, args, meta_out)
|
||||
|
||||
if summary:
|
||||
write_csv(result["output"] / "peak_summary.csv",
|
||||
["id", "n_frames", "x_mean_px", "x_std_px", "fwhm_mean_px",
|
||||
"fwhm_std_px", "wavelength_nm"],
|
||||
([row["id"], row["n"], _num(row["x_mean"], 4), _num(row["x_std"], 4),
|
||||
_num(row["fwhm_mean"], 4), _num(row["fwhm_std"], 4),
|
||||
_num(row["wavelength_nm"], 7)] for row in summary))
|
||||
tell("")
|
||||
tell(f"centre/width scatter over {args.stability} frame(s):")
|
||||
tell(f"{'id':6s}{'n':>3s}{'x_px':>11s}{'s_x':>8s}{'FWHM':>9s}{'s_FWHM':>8s}")
|
||||
for row in summary:
|
||||
def _f(value, width, digits):
|
||||
return f"{'nan':>{width}s}" if not np.isfinite(value) else f"{value:{width}.{digits}f}"
|
||||
tell(f"{row['id']:6s}{row['n']:3d}{_f(row['x_mean'], 11, 3)}"
|
||||
f"{_f(row['x_std'], 9, 3)}{_f(row['fwhm_mean'], 9, 3)}"
|
||||
f"{_f(row['fwhm_std'], 9, 3)}")
|
||||
shapes = []
|
||||
for line in lines:
|
||||
gaps = [abs(other["sensor_x_px"] - line["sensor_x_px"])
|
||||
for other in lines if other is not line]
|
||||
limit = 0.5 * min(gaps) if gaps else float("nan")
|
||||
shapes.append(ten_percent_widths(spectrum, line, limit_px=limit))
|
||||
write_csv(result["output"] / "peak_summary.csv",
|
||||
["id", "x_px", "left_10pct_px", "right_10pct_px", "ratio_right_over_left"],
|
||||
([line["id"], _num(line["sensor_x_px"], 4), _num(shape["left_px"], 4),
|
||||
_num(shape["right_px"], 4), _num(shape["ratio"], 4)]
|
||||
for line, shape in zip(lines, shapes)))
|
||||
|
||||
tell("")
|
||||
tell(f"{'':2s}{'id':4s}{'nm':>10s}{'x_px':>10s}{'ch':>4s}{'SNR':>9s}{'height':>9s}"
|
||||
@@ -1557,6 +1541,16 @@ def run(args) -> int:
|
||||
total = sum(len(items) for items in analysis.per_channel.values())
|
||||
tell("")
|
||||
tell(f"{len(lines)} line(s) from {total} channel peak(s); {len(selected)} selected.")
|
||||
if lines:
|
||||
tell("")
|
||||
tell("10% height widths (asymmetry = right / left):")
|
||||
tell(f"{'id':6s}{'x_px':>11s}{'left':>9s}{'right':>9s}{'ratio':>8s}")
|
||||
for line, shape in zip(lines, shapes):
|
||||
def _shape(value):
|
||||
return f"{'nan':>8s}" if not np.isfinite(value) else f"{value:8.3f}"
|
||||
tell(f"{line['id']:6s}{line['sensor_x_px']:11.3f}"
|
||||
f"{_shape(shape['left_px'])}{_shape(shape['right_px'])}"
|
||||
f"{_shape(shape['ratio'])}")
|
||||
tell(f"exported : {result['output'].expanduser().resolve()}")
|
||||
if calibration is not None:
|
||||
outside = [line["id"] for line in lines if line["extrapolated"]]
|
||||
|
||||
Reference in new issue
Block a user