新增 --from-export:从已有导出重算简表,不读原始帧
- 读 peaks.json + peaks/<id>_shape.csv + selected_peaks.csv - 可配 --calibration 现算 lambda 与 R_50%H,输出 peak_summary.csv 到导出目录
This commit is contained in:
1 parent
234e3c1bb5
commit
e2992c5825
1 file changed
+142
-1
+142
-1
@@ -1312,6 +1312,140 @@ def pick_peaks(spectrum: SpectrumData, lines: list[dict], calibration,
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def half_widths_at_half(x, net, center: float, fraction: float = 0.50,
|
||||
limit_px: float = float("nan")) -> dict:
|
||||
"""Left/right widths where one profile falls to ``fraction`` of its peak."""
|
||||
|
||||
x = np.asarray(x, dtype=float)
|
||||
net = np.asarray(net, dtype=float)
|
||||
index = int(np.argmin(np.abs(x - center)))
|
||||
level = fraction * float(net[index])
|
||||
empty = {"left_px": float("nan"), "right_px": float("nan"),
|
||||
"ratio": float("nan"), "level_adu": level}
|
||||
if not np.isfinite(level) or level <= 0:
|
||||
return empty
|
||||
|
||||
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")
|
||||
position += step
|
||||
current = float(net[position])
|
||||
if current <= level:
|
||||
span = previous - current
|
||||
fraction_from_low = (level - current) / span if span else 0.0
|
||||
crossing = (float(x[position])
|
||||
+ fraction_from_low * (float(x[position - step]) - float(x[position])))
|
||||
return abs(crossing - center)
|
||||
previous = current
|
||||
return float("nan")
|
||||
|
||||
left, right = walk(-1), walk(+1)
|
||||
ratio = right / left if np.isfinite(left) and np.isfinite(right) and left > 0 else float("nan")
|
||||
return {"left_px": left, "right_px": right, "ratio": ratio, "level_adu": level}
|
||||
|
||||
|
||||
def read_export(directory: Path) -> tuple[list[dict], list[str]]:
|
||||
"""Peaks of an exported folder plus the ids that were selected for export."""
|
||||
|
||||
manifest = json.loads((directory / "peaks.json").read_text(encoding="utf-8-sig"))
|
||||
peaks = manifest.get("peaks") or []
|
||||
selected_path = directory / "selected_peaks.csv"
|
||||
selected = []
|
||||
if selected_path.is_file():
|
||||
with open(selected_path, newline="", encoding="utf-8-sig") as handle:
|
||||
selected = [row["id"] for row in csv.DictReader(handle) if row.get("id")]
|
||||
return peaks, selected
|
||||
|
||||
|
||||
def run_from_export(args) -> int:
|
||||
"""Recompute the summary table from an existing export; no RAW frames involved."""
|
||||
|
||||
directory = Path(args.from_export).expanduser().resolve()
|
||||
peaks, selected = read_export(directory)
|
||||
if not peaks:
|
||||
raise ValueError(f"{directory} has no peaks in peaks.json")
|
||||
if args.select not in ("all", None):
|
||||
chosen = [peak for peak in peaks if peak["id"] in parse_selection(
|
||||
args.select, [{"id": peak["id"], "wavelength_nm": peak.get("wavelength_nm"),
|
||||
"x_plot": peak.get("wavelength_nm", float("nan")),
|
||||
"sensor_x_px": peak["sensor_x_px"]} for peak in peaks])]
|
||||
elif selected:
|
||||
chosen = [peak for peak in peaks if peak["id"] in set(selected)]
|
||||
else:
|
||||
chosen = list(peaks)
|
||||
|
||||
calibration = Calibration(args.calibration, args.wavelength_offset) if args.calibration else None
|
||||
dispersion = float(abs(calibration.coeff[0])) if calibration is not None else float("nan")
|
||||
|
||||
rows = []
|
||||
for peak in chosen:
|
||||
shape_path = directory / "peaks" / f"peak_{peak['id']}_shape.csv"
|
||||
best = None
|
||||
if shape_path.is_file():
|
||||
with open(shape_path, newline="", encoding="utf-8-sig") as handle:
|
||||
table = list(csv.DictReader(handle))
|
||||
for channel in sorted({row["channel"] for row in table}):
|
||||
subset = sorted((float(row["sensor_x_px"]), float(row["net_adu"]))
|
||||
for row in table if row["channel"] == channel)
|
||||
xs = np.array([item[0] for item in subset])
|
||||
ys = np.array([item[1] for item in subset])
|
||||
result = half_widths_at_half(xs, ys, peak["sensor_x_px"])
|
||||
if not (np.isfinite(result["left_px"]) and np.isfinite(result["right_px"])):
|
||||
continue
|
||||
height = float(ys.max())
|
||||
if best is None or height > best[0]:
|
||||
best = (height, channel, result)
|
||||
channels = peak.get("channels") or ""
|
||||
channel = best[1] if best else (peak.get("primary_channel") or channels[:1])
|
||||
result = best[2] if best else {"left_px": float("nan"), "right_px": float("nan"),
|
||||
"ratio": float("nan")}
|
||||
wavelength = (float(np.polyval(calibration.coeff, peak["sensor_x_px"]))
|
||||
if calibration is not None else float("nan"))
|
||||
fwhm_nm = peak["fwhm_px"] * dispersion if np.isfinite(dispersion) else float("nan")
|
||||
power = (wavelength / fwhm_nm
|
||||
if np.isfinite(wavelength) and np.isfinite(fwhm_nm) and fwhm_nm > 0
|
||||
else float("nan"))
|
||||
rows.append({"id": peak["id"], "channel": channel, "x": peak["sensor_x_px"],
|
||||
"wavelength": wavelength, "fwhm_px": peak["fwhm_px"],
|
||||
"fwhm_nm": fwhm_nm, "power": power,
|
||||
"left": result["left_px"], "right": result["right_px"],
|
||||
"ratio": result["ratio"], "sat": peak.get("saturated", False)})
|
||||
|
||||
ratios = [row["ratio"] for row in rows if np.isfinite(row["ratio"]) and row["ratio"] > 0]
|
||||
q_system = float(np.exp(np.mean(np.abs(np.log(ratios))))) if ratios else float("nan")
|
||||
|
||||
if not args.quiet:
|
||||
print(f"export : {directory}")
|
||||
print(f"calibration : {calibration.describe() if calibration else 'none'}")
|
||||
print(f"\n{'id':6s}{'ch':>3s}{'x_px':>10s}{'lambda':>9s}{'FWHMnm':>8s}{'R_50%H':>8s}"
|
||||
f"{'left':>7s}{'right':>7s}{'ratio':>7s}")
|
||||
for row in rows:
|
||||
def _f(value, width, digits):
|
||||
return f"{'nan':>{width}s}" if not np.isfinite(value) else f"{value:{width}.{digits}f}"
|
||||
print(f"{row['id']:6s}{row['channel']:>3s}{row['x']:10.1f}"
|
||||
f"{_f(row['wavelength'], 9, 2)}{_f(row['fwhm_nm'], 8, 3)}"
|
||||
f"{_f(row['power'], 8, 0)}{_f(row['left'], 7, 2)}"
|
||||
f"{_f(row['right'], 7, 2)}{_f(row['ratio'], 7, 2)}"
|
||||
+ (" [sat]" if row["sat"] else ""))
|
||||
if np.isfinite(q_system):
|
||||
print(f"\nQ_system = exp(mean|ln A_i|) = {q_system:.4f} N = {len(ratios)} of {len(rows)}")
|
||||
print("A_i = " + ", ".join(f"{value:.2f}" for value in ratios))
|
||||
|
||||
out = Path(args.output).expanduser() if args.output else directory
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
write_csv(out / "peak_summary.csv",
|
||||
["id", "x_px", "left_half_px", "right_half_px", "ratio_right_over_left",
|
||||
"wavelength_nm", "fwhm_nm", "R_50pctH"],
|
||||
([row["id"], _num(row["x"], 4), _num(row["left"], 4), _num(row["right"], 4),
|
||||
_num(row["ratio"], 4), _num(row["wavelength"], 4), _num(row["fwhm_nm"], 4),
|
||||
_num(row["power"], 5)] for row in rows))
|
||||
print(f"written : {out / 'peak_summary.csv'}")
|
||||
return 0
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Find spectral peaks in hq_record RAW recordings, calibrate them and "
|
||||
@@ -1320,8 +1454,11 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
epilog=__doc__,
|
||||
)
|
||||
io_group = parser.add_argument_group("input")
|
||||
io_group.add_argument("--input", required=True, metavar="REC_DIR",
|
||||
io_group.add_argument("--input", default=None, metavar="REC_DIR",
|
||||
help="hq_record recording directory")
|
||||
io_group.add_argument("--from-export", default=None, metavar="DIR",
|
||||
help="recompute peak_summary.csv from an existing export "
|
||||
"(no frames are read)")
|
||||
io_group.add_argument("--frame", type=int, default=0, help="zero-based frame index (default 0)")
|
||||
io_group.add_argument("--average", type=int, default=1,
|
||||
help="mean this many consecutive frames starting at --frame (default 1)")
|
||||
@@ -1482,6 +1619,10 @@ def analyse(args, tell=print) -> "Analysis":
|
||||
|
||||
|
||||
def run(args) -> int:
|
||||
if getattr(args, "from_export", None):
|
||||
return run_from_export(args)
|
||||
if not args.input:
|
||||
raise ValueError("--input REC_DIR is required unless --from-export is used")
|
||||
analysis = analyse(args)
|
||||
hq, spectrum, lines = analysis.hq, analysis.spectrum, analysis.lines
|
||||
calibration, indices = analysis.calibration, analysis.indices
|
||||
|
||||
Reference in new issue
Block a user