-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflat_bottom_detector_final.py
More file actions
1366 lines (1198 loc) · 49.7 KB
/
Copy pathflat_bottom_detector_final.py
File metadata and controls
1366 lines (1198 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flat-Bottom (Plateau-at-Minimum) Detector — polished plotting + FITS banner
What's new (per request)
------------------------
1) **색상 고정**: 메인 플롯(보정 산점), 추세선(이동평균), 탐지 구간 음영을 서로 **다른 고정 색상**으로 통일.
2) **--y-raw-col**: raw 시리즈를 플롯에 얇게 오버레이(탐지엔 미사용).
3) **--fits-dir**: 해당 CSV의 번호(%04d 등)와 매칭되는 FITS 헤더를 읽어 메타(RIGHT_LINES) 구성.
4) **--banner / --logo-path**: Matplotlib 플롯을 이미지로 만든 뒤, 상단 배너(좌상단 로고, 중앙 제목, 우상단 메타)를 합성하여
`plots_bannered` 폴더에 `{원본이름}_bannered.확장자`로 저장. 시작 시 폴더 내용 전체 삭제.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass, asdict
from typing import Any, Dict, List, Optional, Tuple
from pathlib import Path
import shutil
import hashlib
import re
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# --------------------------- Global plot colors --------------------------- #
# (Requested: fixed distinct colors per layer, not per file)
COLOR_MAIN = (0.298, 0.471, 0.659) # blue-ish for corrected scatter
COLOR_TREND = (0.961, 0.521, 0.094) # orange for moving avg
COLOR_REGION = (0.329, 0.643, 0.294) # green for detected span
COLOR_RAW = (0.6, 0.6, 0.6 ) # grey for raw overlay (smoothed)
# --------------------------- Robust helpers --------------------------- #
def mad(x: np.ndarray) -> float:
med = np.median(x)
return float(np.median(np.abs(x - med)))
def robust_scale(x: np.ndarray, eps: float = 1e-12) -> float:
return 1.4826 * mad(x) + eps
def moving_average_centered(y: np.ndarray, window: int) -> np.ndarray:
"""Centered moving average using reflect padding; output has same length as y."""
N = len(y)
if window <= 1 or N == 0:
return y.copy()
if window % 2 == 0:
window += 1
pad = window // 2
ypad = np.pad(y, pad_width=pad, mode="reflect")
k = np.ones(window, dtype=float) / window
conv = np.convolve(ypad, k, mode="valid")
if len(conv) != N: # fallback safety
conv = np.convolve(y, k, mode="same")
conv = conv[:N]
return conv
def boolean_runs(mask: np.ndarray) -> List[Tuple[int, int]]:
"""Return inclusive (start, end) index pairs for contiguous True runs."""
if mask.size == 0:
return []
diff = np.diff(mask.astype(int))
starts = list(np.where(diff == 1)[0] + 1)
ends = list(np.where(diff == -1)[0])
if mask[0]:
starts = [0] + starts
if mask[-1]:
ends = ends + [len(mask) - 1]
return list(zip(starts, ends))
# --------------------------- Data classes ----------------------------- #
@dataclass
class PlateauSegment:
start_idx: int
end_idx: int # inclusive
start_x: float
end_x: float
x_span: float
mean_y: float
min_y: float
max_abs_slope: float
mean_abs_slope: float
mean_abs_curv: float
score: float # generic score/improve used internally
@dataclass
class DetectionParams:
# smoothing & flatness thresholds
window: int = 20
slope_mad_mult: float = 1.0
curv_mad_mult: float = 1.0
# legacy/heuristic thresholds (kept for compatibility/fallbacks)
y_thresh_mode: str = "both" # {"min+mad","percentile","both"}
y_quantile: float = 0.10
y_mad_mult: float = 0.5
# size constraints
min_points: int = 5
min_x_span_frac: float = 0.05
edge_margin_points: int = 3
# triple-tangent stationary detection (fallback)
slope_zero_mad_mult: float = 0.5
stationary_min_sep_pts: int = 3
use_legacy_mask: bool = False
contrast_min: float = 0.0
# model selection (plateau vs quadratic)
use_model_selection: bool = True
model_improve_min: float = 0.10
model_contrast_min: float = 0.00
# prefer wider & deeper in candidate scoring
width_pref: float = 0.5
depth_pref: float = 0.5
widen_rel_tol: float = 0.02
# FP suppression: depth/shoulders filters (hard accept criteria)
depth_min: float = 0.15
depth_bilateral_min: float = 0.08
shoulder_win_frac: float = 0.5
slope_sign_frac_min: float = 0.6
inside_flat_frac_min: float = 0.6
baseline_line_depth_min: float = 0.0
# edge-monotone rejection (from boundaries straight into plateau)
edge_monotone_frac_min: float = 0.75
edge_drop_min: float = 0.50
# scope: only consider edge-monotone if plateau is near edges
edge_monotone_scope_pts: int = 12
edge_monotone_scope_x_frac: float = 0.06
# hard padding from x-ends
plateau_pad_points: int = 8
plateau_pad_x_frac: float = 0.02
# ---------------------------- FITS helpers ---------------------------- #
def _read_fits_header(fits_path: Path) -> Optional[Dict[str, Any]]:
try:
from astropy.io import fits # pip install astropy
with fits.open(fits_path) as hdul:
hdr = dict(hdul[0].header)
if not hdr and len(hdul) > 1:
hdr = dict(hdul[1].header)
return hdr
except Exception:
return None
def _safe_get(h: Dict[str, Any], keys: List[str]) -> Optional[Any]:
if not h:
return None
for k in keys:
if k in h:
return h[k]
for hk in h.keys():
if hk.upper() == k.upper():
return h[hk]
return None
def _parse_iso_datetime(s: str):
import datetime as dt
try:
s = s.strip().replace('T', ' ')
for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
try:
return dt.datetime.strptime(s, fmt).replace(tzinfo=dt.timezone.utc)
except ValueError:
pass
except Exception:
pass
return None
def _mjd_to_utc_datetime(mjd: float):
import datetime as dt
base = dt.datetime(1858, 11, 17, 0, 0, 0, tzinfo=dt.timezone.utc)
return base + dt.timedelta(days=float(mjd))
def _deg_to_hms(ra_deg: float) -> str:
try:
total_hours = (float(ra_deg) / 15.0) % 24.0
h = int(total_hours); m = int((total_hours - h) * 60)
s = (total_hours - h - m/60.0) * 3600.0
return f"{h:02d}:{m:02d}:{s:05.2f}"
except Exception:
return "N/A"
def _deg_to_dms(dec_deg: float) -> str:
try:
sign = '+' if float(dec_deg) >= 0 else '-'
val = abs(float(dec_deg))
d = int(val); m = int((val - d) * 60)
s = (val - d - m/60.0) * 3600.0
return f"{sign}{d:02d}:{m:02d}:{s:05.2f}"
except Exception:
return "N/A"
def _sexagesimal_to_deg(text: str, is_ra: bool) -> Optional[float]:
try:
t = text.strip()
t = re.sub(r'[hHdD]', ':', t); t = re.sub(r'[mM]', ':', t); t = re.sub(r'[sS]', '', t)
t = t.replace(' ', ':')
parts = [p for p in t.split(':') if p]
if len(parts) < 2:
return None
a = float(parts[0]); b = float(parts[1]); c = float(parts[2]) if len(parts) > 2 else 0.0
if is_ra:
hours = abs(a) + b/60.0 + c/3600.0
if a < 0: hours = -hours
return hours * 15.0
else:
sign = -1.0 if str(parts[0]).strip().startswith('-') else 1.0
deg = abs(a) + b/60.0 + c/3600.0
return sign * deg
except Exception:
return None
def _build_right_lines_from_header(hdr: Optional[Dict[str, Any]]) -> List[str]:
import datetime as dt
if not hdr:
return ["Obs: N/A", "Dur: N/A / Exp: N/A", "Filter: N/A", "RA/Dec: N/A"]
# Obs time
obs_dt = None
date_obs = _safe_get(hdr, ["DATE-OBS"]); time_obs = _safe_get(hdr, ["TIME-OBS"])
if isinstance(date_obs, str):
obs_dt = _parse_iso_datetime(date_obs if not time_obs else f"{date_obs} {time_obs}")
if obs_dt is None:
mjd_obs = _safe_get(hdr, ["MJD-OBS"])
try:
if mjd_obs is not None:
obs_dt = _mjd_to_utc_datetime(float(mjd_obs))
except Exception:
pass
obs_str = obs_dt.strftime("%Y-%m-%d %H:%M (UT)") if obs_dt else "N/A"
# Duration
duration_sec = None
for key in ["ELAPTIME", "DURATION", "TELAPSE", "TEXPTIME", "TOTALEXP", "TOTTIME"]:
v = _safe_get(hdr, [key])
try:
if v is not None:
duration_sec = float(v); break
except Exception: pass
if duration_sec is None:
date_end = _safe_get(hdr, ["DATE-END"])
if isinstance(date_end, str) and obs_dt:
end_dt = _parse_iso_datetime(date_end)
if end_dt: duration_sec = (end_dt - obs_dt).total_seconds()
if duration_sec is None:
mjd_end = _safe_get(hdr, ["MJD-END"]); mjd_obs = _safe_get(hdr, ["MJD-OBS"])
try:
if mjd_end is not None and mjd_obs is not None:
duration_sec = (float(mjd_end) - float(mjd_obs)) * 86400.0
except Exception: pass
if isinstance(duration_sec, (int, float)) and duration_sec > 0:
hours = duration_sec / 3600.0
dur_str = f"{hours:.1f}h" if hours >= 1.0 else f"{duration_sec:.0f}s"
else:
dur_str = "N/A"
# Exposure
exp = _safe_get(hdr, ["EXPTIME", "EXPOSURE", "ITIME", "EXPTime"])
try:
exp_str = f"{float(exp):g}s" if exp is not None else "N/A"
except Exception:
exp_str = "N/A"
# Filter
filt = _safe_get(hdr, ["FILTER", "FILTER1", "FILTER2", "FILTERS"])
filt_str = " ".join(map(str, filt)) if isinstance(filt, (list, tuple)) else (str(filt) if filt is not None else "N/A")
# RA/Dec
ra_deg = dec_deg = None
ra_str = dec_str = "N/A"
ra_txt = _safe_get(hdr, ["OBJCTRA", "RA_OBJ", "RA-TARG", "RASTRNG"])
dec_txt = _safe_get(hdr, ["OBJCTDEC", "DEC_OBJ", "DEC-TARG", "DECSTRNG"])
if isinstance(ra_txt, str) and isinstance(dec_txt, str):
ra_deg = _sexagesimal_to_deg(ra_txt, is_ra=True)
dec_deg = _sexagesimal_to_deg(dec_txt, is_ra=False)
ra_str, dec_str = ra_txt.strip(), dec_txt.strip()
if ra_deg is None:
v = _safe_get(hdr, ["RA", "CRVAL1", "OBJRA"])
try:
if v is not None: ra_deg = float(v)
except Exception: pass
if dec_deg is None:
v = _safe_get(hdr, ["DEC", "CRVAL2", "OBJDEC"])
try:
if v is not None: dec_deg = float(v)
except Exception: pass
if not (isinstance(ra_txt, str) and isinstance(dec_txt, str)):
if ra_deg is not None: ra_str = _deg_to_hms(ra_deg)
if dec_deg is not None: dec_str = _deg_to_dms(dec_deg)
return [f"{obs_str}", f"Dur: {dur_str} / Exp: {exp_str}", f"Filter: {filt_str}", f"RA/Dec: {ra_str} {dec_str}"]
def _extract_number_from_stem(stem: str) -> Optional[str]:
m = re.search(r'(\d{4,})', stem) # prefer 4+ digits (e.g., %04d)
return m.group(1) if m else None
def _find_matching_fits(fits_dir: Optional[Path], data_path: Path) -> Optional[Path]:
if not fits_dir:
return None
try:
if not fits_dir.exists():
return None
except Exception:
return None
num = _extract_number_from_stem(data_path.stem)
patterns = ["*.fits", "*.fit", "*.fits.fz", "*.fz"]
if num:
for pat in patterns:
for fp in fits_dir.rglob(pat):
if num in fp.stem:
return fp
# fallback: any one file
for pat in patterns:
cands = list(fits_dir.rglob(pat))
if cands:
return cands[0]
return None
# ------------------------- Model selection pieces ---------------------- #
def _fit_quadratic(x: np.ndarray, y: np.ndarray) -> Tuple[float, np.ndarray, np.ndarray]:
X = np.vstack([x**2, x, np.ones_like(x)]).T
beta, *_ = np.linalg.lstsq(X, y, rcond=None)
yhat = X @ beta
sse = float(np.sum((y - yhat) ** 2))
return sse, beta, yhat
def _best_plateau_piecewise(
x: np.ndarray,
y: np.ndarray,
min_points: int,
edge_margin: int,
min_x_frac: float,
width_pref: float,
depth_pref: float,
widen_rel_tol: float,
pad_pts: int,
pad_x_frac: float,
) -> Optional[Dict[str, Any]]:
n = len(x)
if n < min_points + 2 * edge_margin + 1:
return None
xspan = float(x[-1] - x[0])
y_scale = robust_scale(y)
def refit_for_span(s: int, e: int) -> Dict[str, Any]:
# design matrix for piecewise [1, left_term, right_term]
rows: List[List[float]] = []
rhs: List[float] = []
if s > 0:
xs = x[s]
for i in range(0, s):
rows.append([1.0, (x[i] - xs), 0.0])
rhs.append(float(y[i]))
for i in range(s, e + 1):
rows.append([1.0, 0.0, 0.0])
rhs.append(float(y[i]))
if e < n - 1:
xe = x[e]
for i in range(e + 1, n):
rows.append([1.0, 0.0, (x[i] - xe)])
rhs.append(float(y[i]))
A = np.asarray(rows, dtype=float)
b = np.asarray(rhs, dtype=float)
params, *_ = np.linalg.lstsq(A, b, rcond=None)
y0, mL, mR = params.tolist()
yhat = np.empty_like(y, dtype=float)
if s > 0:
yhat[:s] = y0 + mL * (x[:s] - x[s])
yhat[s : e + 1] = y0
if e < n - 1:
yhat[e + 1 :] = y0 + mR * (x[e + 1 :] - x[e])
sse = float(np.sum((y - yhat) ** 2))
# compute contrast (depth) vs surroundings
halfw = max(min_points, (e - s) // 2)
Ls, Le = max(edge_margin, s - halfw), s
Rs, Re = e + 1, min(n - edge_margin, e + 1 + halfw)
if Le - Ls >= min_points and Re - Rs >= min_points:
left_med = float(np.median(y[Ls:Le]))
right_med = float(np.median(y[Rs:Re]))
inside_med = float(np.median(y[s : e + 1]))
surround = min(left_med, right_med)
contrast = (surround - inside_med) / (y_scale + 1e-12)
else:
contrast = 0.0
width = float(x[e] - x[s])
width_norm = width / (xspan + 1e-12)
sse_norm = sse / ((y_scale**2) * n + 1e-12)
score = -sse_norm + width_pref * width_norm + depth_pref * max(0.0, contrast)
return {
"s": s,
"e": e,
"y0": y0,
"mL": mL,
"mR": mR,
"sse": sse,
"yhat": yhat,
"contrast": contrast,
"width": width,
"width_norm": width_norm,
"sse_norm": sse_norm,
"score": score,
}
best: Optional[Dict[str, Any]] = None
# brute-force candidate search with hard padding
for s in range(edge_margin, n - edge_margin - min_points):
for e in range(s + min_points - 1, n - edge_margin):
# padding constraints
if (s < pad_pts) or ((n - 1 - e) < pad_pts):
continue
if (x[s] - x[0]) < (pad_x_frac * xspan) or (x[-1] - x[e]) < (pad_x_frac * xspan):
continue
if (x[e] - x[s]) < (min_x_frac * xspan):
continue
try:
cand = refit_for_span(s, e)
except np.linalg.LinAlgError:
continue
if (best is None) or (cand["score"] > best["score"]):
best = cand
if best is None:
return None
# greedy widening within tolerance
improved = True
while improved:
improved = False
# extend left
if best["s"] > max(edge_margin, pad_pts):
s_new, e_new = best["s"] - 1, best["e"]
if (x[e_new] - x[s_new]) >= (min_x_frac * xspan) and (x[s_new] - x[0]) >= (pad_x_frac * xspan):
cand = refit_for_span(s_new, e_new)
if cand["sse"] <= best["sse"] * (1.0 + widen_rel_tol):
best = cand
improved = True
continue
# extend right
if best["e"] < min(n - edge_margin - 1, n - 1 - pad_pts):
s_new, e_new = best["s"], best["e"] + 1
if (x[e_new] - x[s_new]) >= (min_x_frac * xspan) and (x[-1] - x[e_new]) >= (pad_x_frac * xspan):
cand = refit_for_span(s_new, e_new)
if cand["sse"] <= best["sse"] * (1.0 + widen_rel_tol):
best = cand
improved = True
continue
return best
# --------------------- FP-suppression filters ------------------------- #
def _depth_shoulders_filter(
x: np.ndarray,
y_s: np.ndarray,
s: int,
e: int,
slope: np.ndarray,
y_scale: float,
params: DetectionParams,
) -> Tuple[bool, Dict[str, float]]:
n = len(x)
width_pts = e - s + 1
halfw = max(params.min_points, int(params.shoulder_win_frac * width_pts))
Ls, Le = max(params.edge_margin_points, s - halfw), s
Rs, Re = e + 1, min(n - params.edge_margin_points, e + 1 + halfw)
if Le - Ls < params.min_points or Re - Rs < params.min_points:
return False, {"reason": "shoulder_windows_too_small"}
inside_med = float(np.median(y_s[s : e + 1]))
left_med = float(np.median(y_s[Ls:Le]))
right_med = float(np.median(y_s[Rs:Re]))
gapL = (left_med - inside_med) / (y_scale + 1e-12)
gapR = (right_med - inside_med) / (y_scale + 1e-12)
depth_ok = (min(gapL, gapR) >= params.depth_min) and \
(gapL >= params.depth_bilateral_min) and (gapR >= params.depth_bilateral_min)
# slope-based checks
left_sl = slope[Ls:Le]
right_sl = slope[Rs:Re]
inside_sl = slope[s : e + 1]
left_neg_frac = float(np.mean(left_sl < 0)) if len(left_sl) else 0.0
right_pos_frac = float(np.mean(right_sl > 0)) if len(right_sl) else 0.0
slope_sign_ok = (left_neg_frac >= params.slope_sign_frac_min) and \
(right_pos_frac >= params.slope_sign_frac_min)
slope_scale = robust_scale(slope)
inside_flat_frac = float(np.mean(np.abs(inside_sl) <= params.slope_mad_mult * slope_scale))
inside_flat_ok = inside_flat_frac >= params.inside_flat_frac_min
# linear baseline depth at center
xc = 0.5 * (x[s] + x[e])
# left line
XL = np.vstack([x[Ls:Le], np.ones(Le - Ls)]).T
betaL, *_ = np.linalg.lstsq(XL, y_s[Ls:Le], rcond=None)
yL_mid = float(betaL[0] * xc + betaL[1])
# right line
XR = np.vstack([x[Rs:Re], np.ones(Re - Rs)]).T
betaR, *_ = np.linalg.lstsq(XR, y_s[Rs:Re], rcond=None)
yR_mid = float(betaR[0] * xc + betaR[1])
baseline_mid = min(yL_mid, yR_mid)
base_gap = (baseline_mid - inside_med) / (y_scale + 1e-12)
baseline_ok = base_gap >= params.baseline_line_depth_min
ok = depth_ok and slope_sign_ok and inside_flat_ok and baseline_ok
return ok, {
"gapL": gapL,
"gapR": gapR,
"left_neg_frac": left_neg_frac,
"right_pos_frac": right_pos_frac,
"inside_flat_frac": inside_flat_frac,
"base_gap": base_gap,
}
def _edge_monotone_reject(
x: np.ndarray,
y_s: np.ndarray,
s: int,
e: int,
slope: np.ndarray,
y_scale: float,
params: DetectionParams,
) -> Tuple[bool, Dict[str, float]]:
"""
Reject if the curve descends (or ascends) into the plateau directly from the left (or right) boundary,
but only if the plateau touches the scope near the edges (points or x-fraction).
"""
n = len(x)
xspan = float(x[-1] - x[0]) if n > 1 else 1.0
inside_med = float(np.median(y_s[s : e + 1]))
left_scope = (s <= params.edge_monotone_scope_pts) or ((x[s] - x[0]) <= params.edge_monotone_scope_x_frac * xspan)
right_scope = ((n - 1 - e) <= params.edge_monotone_scope_pts) or ((x[-1] - x[e]) <= params.edge_monotone_scope_x_frac * xspan)
# left side
if s > 0:
left_neg_frac = float(np.mean(slope[:s] < 0))
left_edge_med = float(np.median(y_s[:s]))
left_drop = (left_edge_med - inside_med) / (y_scale + 1e-12)
else:
left_neg_frac, left_drop = 1.0, float("inf")
# right side
if e < n - 1:
right_pos_frac = float(np.mean(slope[e + 1 :] > 0))
right_edge_med = float(np.median(y_s[e + 1 :]))
right_drop = (right_edge_med - inside_med) / (y_scale + 1e-12)
else:
right_pos_frac, right_drop = 1.0, float("inf")
left_reject = left_scope and (left_neg_frac >= params.edge_monotone_frac_min) and (left_drop >= params.edge_drop_min)
right_reject = right_scope and (right_pos_frac >= params.edge_monotone_frac_min) and (right_drop >= params.edge_drop_min)
reject = left_reject or right_reject
return reject, {
"left_neg_frac": left_neg_frac,
"left_drop": left_drop,
"right_pos_frac": right_pos_frac,
"right_drop": right_drop,
"left_reject": left_reject,
"right_reject": right_reject,
}
# ---------------------- Triple-tangent fallback ------------------------ #
def stationary_points_from_slope(
slope: np.ndarray,
slope_scale: float,
edge_margin_points: int,
zero_mult: float,
min_sep: int,
) -> List[int]:
n = len(slope)
thr = zero_mult * slope_scale + 1e-12
small = np.abs(slope) <= thr
runs = boolean_runs(small)
cand: List[int] = []
for s, e in runs:
i = s + int(np.argmin(np.abs(slope[s : e + 1])))
if i <= edge_margin_points or i >= n - 1 - edge_margin_points:
continue
cand.append(i)
# sign changes
sign = np.sign(slope)
sc = np.where(sign[:-1] * sign[1:] < 0)[0]
for idx in sc:
i = idx if abs(slope[idx]) <= abs(slope[idx + 1]) else idx + 1
if i <= edge_margin_points or i >= n - 1 - edge_margin_points:
continue
cand.append(i)
cand = sorted(set(cand))
filtered: List[int] = []
for i in cand:
if not filtered or i - filtered[-1] >= min_sep:
filtered.append(i)
return filtered
def detect_flat_bottom_triple(
x: np.ndarray,
y: np.ndarray,
params: DetectionParams,
) -> Tuple[Optional[PlateauSegment], Dict[str, Any]]:
n = len(x)
if n < max(7, params.window):
return None, {"reason": "too_few_points"}
# smoothing & derivatives
y_s = moving_average_centered(y, params.window)
dx = np.gradient(x)
eps = 1e-12
slope = np.gradient(y_s) / (dx + eps)
curv = np.gradient(slope) / (dx + eps)
y_scale = robust_scale(y_s)
slope_scale = robust_scale(slope)
x_span_total = float(x[-1] - x[0]) if n > 1 else 1.0
# stationary points
stat_idx = stationary_points_from_slope(
slope=slope,
slope_scale=slope_scale,
edge_margin_points=params.edge_margin_points,
zero_mult=params.slope_zero_mad_mult,
min_sep=params.stationary_min_sep_pts,
)
if len(stat_idx) < 3:
return None, {"reason": "insufficient_stationary_points", "stationary_idx": stat_idx}
min_x_span = params.min_x_span_frac * x_span_total
candidates: List[PlateauSegment] = []
details: List[Dict[str, Any]] = []
for k in range(len(stat_idx) - 2):
i1, i2, i3 = stat_idx[k], stat_idx[k + 1], stat_idx[k + 2]
# hard padding from both ends
if (i1 < params.plateau_pad_points) or ((n - 1 - i3) < params.plateau_pad_points):
continue
if (x[i1] - x[0]) < (params.plateau_pad_x_frac * x_span_total) or \
(x[-1] - x[i3]) < (params.plateau_pad_x_frac * x_span_total):
continue
if i3 - i1 + 1 < params.min_points:
continue
x_span = float(x[i3] - x[i1])
if x_span < min_x_span:
continue
inside_y = y_s[i1 : i3 + 1]
inside_med = float(np.median(inside_y))
# shoulders
halfw = max(params.min_points, (i3 - i1) // 2)
Ls, Le = max(params.edge_margin_points, i1 - halfw), i1
Rs, Re = i3 + 1, min(n - params.edge_margin_points, i3 + 1 + halfw)
if Le - Ls < params.min_points or Re - Rs < params.min_points:
continue
left_med = float(np.median(y_s[Ls:Le]))
right_med = float(np.median(y_s[Rs:Re]))
surround = min(left_med, right_med)
contrast = (surround - inside_med) / (y_scale + 1e-12)
if contrast <= params.contrast_min:
continue
seg_slope = slope[i1 : i3 + 1]
seg_curv = curv[i1 : i3 + 1]
flat_frac = float(np.mean(np.abs(seg_slope) <= params.slope_mad_mult * robust_scale(slope)))
curv_flat_frac = float(np.mean(np.abs(seg_curv) <= params.curv_mad_mult * robust_scale(curv)))
span_score = x_span / (x_span_total + 1e-12)
score = contrast * (0.6 * flat_frac + 0.4 * curv_flat_frac) * span_score
candidates.append(
PlateauSegment(
start_idx=i1,
end_idx=i3,
start_x=float(x[i1]),
end_x=float(x[i3]),
x_span=x_span,
mean_y=float(np.mean(inside_y)),
min_y=float(np.min(inside_y)),
max_abs_slope=float(np.max(np.abs(seg_slope))),
mean_abs_slope=float(np.mean(np.abs(seg_slope))),
mean_abs_curv=float(np.mean(np.abs(seg_curv))),
score=float(score),
)
)
details.append(
{
"i1": int(i1),
"i2": int(i2),
"i3": int(i3),
"left_med": left_med,
"right_med": right_med,
"inside_med": inside_med,
"contrast": contrast,
"span_score": span_score,
"score": score,
}
)
if not candidates:
return None, {"reason": "no_triple_tangent_candidates", "stationary_idx": stat_idx}
best = max(candidates, key=lambda seg: seg.score)
# Before accepting, run FP-suppression filters and edge-monotone rejection
dx = np.gradient(x)
eps = 1e-12
slope_arr = np.gradient(y_s) / (dx + eps)
y_sc = robust_scale(y_s)
ok, filt = _depth_shoulders_filter(
x=x, y_s=y_s, s=best.start_idx, e=best.end_idx, slope=slope_arr, y_scale=y_sc, params=params
)
if not ok:
return None, {"reason": "depth_filter_reject_fallback", "filters": filt}
em_reject, em = _edge_monotone_reject(
x=x, y_s=y_s, s=best.start_idx, e=best.end_idx, slope=slope_arr, y_scale=y_sc, params=params
)
if em_reject:
return None, {"reason": "edge_monotone_reject_fallback", "edge_metrics": em}
debug = {
"y_s": y_s,
"slope": slope,
"curv": curv,
"stationary_idx": stat_idx,
"method": "triple_tangent",
"best": asdict(best),
}
return best, debug
# ------------------------- Main detector (model) ----------------------- #
def detect_flat_bottom_modelselect(
x: np.ndarray,
y: np.ndarray,
params: DetectionParams,
) -> Tuple[Optional[PlateauSegment], Dict[str, Any]]:
n = len(x)
if n < max(7, params.window):
return None, {"reason": "too_few_points"}
# smoothing
y_s = moving_average_centered(y, params.window)
# quadratic
quad_sse, quad_beta, quad_yhat = _fit_quadratic(x, y_s)
# plateau piecewise
best_pl = _best_plateau_piecewise(
x=x,
y=y_s,
min_points=params.min_points,
edge_margin=params.edge_margin_points,
min_x_frac=params.min_x_span_frac,
width_pref=params.width_pref,
depth_pref=params.depth_pref,
widen_rel_tol=params.widen_rel_tol,
pad_pts=params.plateau_pad_points,
pad_x_frac=params.plateau_pad_x_frac,
)
if best_pl is None:
return None, {"reason": "no_piecewise_candidate", "y_s": y_s, "quad_sse": quad_sse}
improve = (quad_sse - best_pl["sse"]) / (quad_sse + 1e-12)
if not ((improve >= params.model_improve_min) and (best_pl["contrast"] >= params.model_contrast_min)):
return None, {
"reason": "model_selection_reject",
"y_s": y_s,
"quad_sse": quad_sse,
"piecewise": best_pl,
"improve_ratio": improve,
"threshold_improve": params.model_improve_min,
"threshold_contrast": params.model_contrast_min,
}
# extra FP suppression filters
dx = np.gradient(x)
eps = 1e-12
slope = np.gradient(y_s) / (dx + eps)
y_scale = robust_scale(y_s)
ok, filt = _depth_shoulders_filter(
x=x, y_s=y_s, s=best_pl["s"], e=best_pl["e"], slope=slope, y_scale=y_scale, params=params
)
if not ok:
return None, {
"reason": "depth_filter_reject",
"y_s": y_s,
"quad_sse": quad_sse,
"piecewise": best_pl,
"improve_ratio": improve,
"filters": filt,
}
# Edge-monotone rejection
em_reject, em = _edge_monotone_reject(
x=x, y_s=y_s, s=best_pl["s"], e=best_pl["e"], slope=slope, y_scale=y_scale, params=params
)
if em_reject:
return None, {
"reason": "edge_monotone_reject",
"y_s": y_s,
"quad_sse": quad_sse,
"piecewise": best_pl,
"improve_ratio": improve,
"edge_metrics": em,
}
# build segment
s = best_pl["s"]
e = best_pl["e"]
seg_y = y_s[s : e + 1]
curv = np.gradient(slope) / (dx + eps)
seg_slope = slope[s : e + 1]
seg_curv = curv[s : e + 1]
seg = PlateauSegment(
start_idx=s,
end_idx=e,
start_x=float(x[s]),
end_x=float(x[e]),
x_span=float(x[e] - x[s]),
mean_y=float(np.mean(seg_y)),
min_y=float(np.min(seg_y)),
max_abs_slope=float(np.max(np.abs(seg_slope))),
mean_abs_slope=float(np.mean(np.abs(seg_slope))),
mean_abs_curv=float(np.mean(np.abs(seg_curv))),
score=float(improve),
)
debug = {
"y_s": y_s,
"quad_sse": quad_sse,
"piecewise": best_pl,
"improve_ratio": improve,
"method": "model_selection",
"filters": filt,
}
return seg, debug
# ---------------------------- Plot helper ------------------------------ #
def plot_with_plateau(
x: np.ndarray,
y: np.ndarray,
y_s: np.ndarray,
best: Optional[PlateauSegment],
out_path: Path,
title: str,
y_raw: Optional[np.ndarray] = None,
right_meta_lines: Optional[List[str]] = None,
) -> None:
out_path.parent.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(9, 5))
# Main detrended scatter
ax.scatter(x, y, s=6, alpha=0.60, label="Detrended (scatter)", color=COLOR_MAIN)
# Trendline (moving average on detrended)
ax.plot(x, y_s, linewidth=1.2, alpha=0.95, label="moving avg (detrended)", color=COLOR_TREND)
# Optional raw overlay (light smoothing for readability)
if y_raw is not None and len(y_raw) == len(y):
w = max(3, min(51, (len(x)//50)*2 + 1))
ax.scatter(x, moving_average_centered(y_raw, w), s=12, alpha=0.8,
label="raw", color=COLOR_RAW)
# Detected plateau region
if best is not None:
ax.axvspan(best.start_x, best.end_x, alpha=0.20, label="detected flat-bottom", color=COLOR_REGION)
ax.axvline(best.start_x, linewidth=1.2, linestyle="--", alpha=0.85, color=COLOR_REGION)
ax.axvline(best.end_x, linewidth=1.2, linestyle="--", alpha=0.85, color=COLOR_REGION)
print(title)
ax.set_title(title)
ax.set_xlabel("x"); ax.set_ylabel("y")
ax.legend(loc="best")
# RIGHT_LINES metadata as an inside-plot helper (still keep; banner will add headline)
if right_meta_lines:
text = "\n".join(right_meta_lines)
bbox_props = dict(boxstyle="round,pad=0.5", facecolor="white", alpha=0.9, edgecolor="0.8")
ax.text(0.99, 0.01, text, transform=ax.transAxes, va="bottom", ha="right", fontsize=8, bbox=bbox_props)
fig.tight_layout()
fig.savefig(out_path, dpi=160)
plt.close(fig)
# ---------------------------- Banner helpers --------------------------- #
EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"}
def _banner_clear_out(out_dir: Path) -> None:
out_dir.mkdir(parents=True, exist_ok=True)
# safety: require folder name endswith "plots_bannered"
if not str(out_dir).lower().endswith("plots_bannered"):
raise RuntimeError(f"Safety: unexpected banner output folder: {out_dir}")
for child in out_dir.rglob("*"):
try:
if child.is_file() or child.is_symlink():
child.unlink()
except Exception:
pass
for child in sorted([d for d in out_dir.rglob("*") if d.is_dir()], reverse=True):
try:
dlist = list(child.iterdir())
if not dlist:
child.rmdir()
except Exception:
pass
def _add_header_banner(
input_path: str,
output_path: str,
title: str,
right_meta_lines: Optional[List[str]] = None,
logo_path: Optional[str] = None,
banner_height: int = 180,
padding: int = 28,
) -> str:
"""PIL로 상단 배너 합성 (좌상 로고, 중앙 제목, 우상 메타)."""
try:
from PIL import Image, ImageDraw, ImageFont, ImageOps
except Exception as e:
raise RuntimeError("Pillow(PIL)가 필요합니다. pip install pillow") from e
def _load_font(name: str, size: int):
try:
return ImageFont.truetype(name, size=size)
except Exception:
try:
return ImageFont.truetype("Arial.ttf", size=size)
except Exception:
return ImageFont.load_default()
base = Image.open(input_path).convert("RGBA")
W, H = base.size
# 배너+본문 캔버스
canvas = Image.new("RGBA", (W, H + banner_height), (255, 255, 255, 255))
canvas.paste(base, (0, banner_height))
draw = ImageDraw.Draw(canvas)
title_font = _load_font("arialbd.ttf", 60)
meta_font = _load_font("DejaVuSans.ttf", 28)
# 좌상단 로고
if logo_path and os.path.exists(logo_path):
try:
logo = Image.open(logo_path).convert("RGBA")
target_h = int((banner_height - 2 * padding) * 1.15)
logo = ImageOps.contain(logo, (target_h, target_h))
logo_x = padding + 40
logo_y = (banner_height - logo.height) // 2
canvas.paste(logo, (logo_x, logo_y), logo)
except Exception:
pass
# 중앙 제목 (가로·세로 중앙 정렬)
x0, y0, x1, y1 = draw.textbbox((0, 0), title, font=title_font)
title_w, title_h = (x1 - x0), (y1 - y0)
title_x = (W - title_w) // 2
title_y = (banner_height - title_h) // 2
draw.text((title_x, title_y), title, fill=(20, 20, 20), font=title_font)
# 우상단 메타 (오른쪽 정렬)
if right_meta_lines:
line_h = meta_font.getbbox("Ag")[3] + 6