-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoPipeline.py
More file actions
8249 lines (7478 loc) · 386 KB
/
Copy pathAutoPipeline.py
File metadata and controls
8249 lines (7478 loc) · 386 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
# -*- coding: utf-8 -*-
"""
AutoPipeline.py — pyADR Argon Pipeline (full PyQt5 UI)
=========================================================
Native PyQt5 interface matching the HTML design:
- Top navigation: 1.Calculate T0 → 2.Mass Ratio → 3.Age Calc+Datum
- Left sidebar: Return / Save / Linear/Average / Auto Blank / Auto Signal / Manual
- 5 mV-vs-time canvases with 10-cycle toggle buttons
- T0 summary table
- Mass Ratio table
- Age Calc + Datum table + 4 diagram panels
Integration (4 changes in NTNU_DataReduction.py):
1. import AutoPipeline
2. __init__():
self.AutoPipelinePage = AutoPipeline.AutoPipelineWindow()
self.widget.addWidget(self.AutoPipelinePage) # p20
self.AutoPipelinePage.returnBtn.clicked.connect(self.toMain)
3. Connections:
self.HomePage.AP.clicked.connect(self.toAP)
4. New method:
def toAP(self):
self.AutoPipelinePage.set_context(
self.parameters, self.parameters_name,
int(self.parameters[self.parameters_name.index('numCycle')])
)
self.widget.setCurrentIndex(20)
"""
import os, sys, csv, shutil, math, zipfile, json
import warnings
warnings.filterwarnings('ignore', category=UserWarning, module='matplotlib')
import numpy as np
from PyQt5 import QtWidgets, QtCore, QtGui
from scipy.optimize import curve_fit
from scipy.stats import chi2 as _chi2 # v3.9.15: exact MSWD critical value
import Utilities
from Utilities import r2_score # v3.8.81: was sklearn (dropped ~7s cold-start import)
# ── Decay constants (Renne et al. 2010, 2011) ───────────────────────────────
ARGON_37_HALFLIFE_DAYS = 35.011
ARGON_39_HALFLIFE_YEARS = 269.0
LAMBDA_37 = math.log(2) / ARGON_37_HALFLIFE_DAYS # 1/day
LAMBDA_39 = math.log(2) / (ARGON_39_HALFLIFE_YEARS * 365.25) # 1/day
# ⁴⁰K total decay constant for age calculation (1/yr).
# pyADR default 5.49e-10 matches parameters.csv default and what calcAge uses.
# Updated at runtime by AutoPipelineWindow.set_context() from
# parameters['λ for age calculation'], so isochron age in AgeCalcPage stays
# consistent with the main calcAge path.
LAMBDA_K = 5.49e-10
def decay_correct(t0_net, sig, delta_t_days, isotope='37'):
"""Correct an isotope's net T0 for radioactive decay between irradiation
midpoint and analysis time. 37Ar: t½ = 35.011 d; 39Ar: t½ = 269 yr.
Returns (t0_corrected, sig_corrected). sig scales by same factor."""
if delta_t_days <= 0:
return t0_net, sig
lam = LAMBDA_37 if str(isotope) == '37' else LAMBDA_39
factor = math.exp(lam * delta_t_days)
return t0_net * factor, abs(sig) * factor
# ── σ method toggle ─────────────────────────────────────────────────────────
# 'standard' : SE of y-intercept (statistically correct, Li et al. 2019 Eq.1)
# 'calc_t0' : std(|residuals|)/sqrt(n) (matches Calculate T0; underestimates σ)
# v3.8.18: default changed 'standard' → 'calc_t0' per user request — AutoPipeline
# now matches the standalone CalcT0Page (NTNU_DataReduction.py) σ output by
# default. User can still flip to 'standard' via the sidebar σ method dropdown.
SIGMA_METHOD = 'calc_t0'
# ── Δt (days, irradiation midpoint → analysis) ──────────────────────────────
# Set via UI; 0 means no decay correction.
DELTA_T_DAYS = 0.0
def _ratio_sigma(num, snum, den, sden, rho=0.0):
"""σ of ratio R = num/den via quadrature.
(σR/R)² = (σnum/num)² + (σden/den)² - 2·rho·(σnum/num)(σden/den)"""
if abs(num) < 1e-30 or abs(den) < 1e-30:
return 0.0
r = num/den
return abs(r) * math.sqrt((snum/num)**2 + (sden/den)**2
- 2*rho*(snum/num)*(sden/den))
def york_regression(x, sx, y, sy, rho_xy=None, max_iter=50, tol=1e-12):
"""v3.8.5: delegate to Utilities.york_regression (single source of truth).
Kept here as a thin wrapper so existing callers in AutoPipeline work
unchanged."""
return Utilities.york_regression(x, sx, y, sy, rho_xy=rho_xy,
max_iter=max_iter, tol=tol)
# Original local implementation preserved below for reference but no longer
# called — kept temporarily in case Utilities import fails. Will be removed
# in a follow-up cleanup once Utilities.york_regression is verified.
def _york_regression_legacy(x, sx, y, sy, rho_xy=None, max_iter=50, tol=1e-12):
"""LEGACY: pre-v3.8.5 local copy. Use Utilities.york_regression instead."""
x = np.asarray(x, float); y = np.asarray(y, float)
sx = np.asarray(sx, float); sy = np.asarray(sy, float)
n = len(x)
if n < 2: return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
if rho_xy is None: rho_xy = np.zeros(n)
else: rho_xy = np.asarray(rho_xy, float)
# weights
wx = 1.0/(sx**2 + 1e-300)
wy = 1.0/(sy**2 + 1e-300)
# initial slope from OLS
b = np.polyfit(x, y, 1)[0]
for _ in range(max_iter):
alpha = np.sqrt(wx * wy)
W = wx * wy / (wx + b*b * wy - 2*b*rho_xy*alpha + 1e-300)
X_bar = np.sum(W*x) / np.sum(W)
Y_bar = np.sum(W*y) / np.sum(W)
U = x - X_bar
V = y - Y_bar
beta = W * (U/wy + b*V/wx - (b*U + V)*rho_xy/alpha)
num = np.sum(W * beta * V)
den = np.sum(W * beta * U)
if abs(den) < 1e-300:
break
b_new = num/den
if abs(b_new - b) < tol*max(1.0, abs(b)):
b = b_new; break
b = b_new
a = Y_bar - b * X_bar
# σ on slope and intercept
x_adj = X_bar + beta
x_adj_bar = np.sum(W*x_adj)/np.sum(W)
u = x_adj - x_adj_bar
sb2 = 1.0 / np.sum(W*u*u)
sa2 = 1.0/np.sum(W) + x_adj_bar*x_adj_bar*sb2
# v3.8.5 (A3): cov(intercept, slope). Typically negative for inverse
# isochrons (when slope goes up, intercept goes down). Required by σ_F
# propagation in _update_isochron_stats inverse path.
cov_ab = -x_adj_bar * sb2
# MSWD
if n > 2:
chi2 = np.sum(W * (y - b*x - a)**2)
mswd = chi2 / (n - 2)
else:
mswd = 0.0
return (float(b), float(a),
float(np.sqrt(max(sb2, 0))), float(np.sqrt(max(sa2, 0))),
float(mswd), float(cov_ab))
def _sigma_from_fit(residuals, n, popt, pcov, t, method=None):
"""Return σ_T0 according to global SIGMA_METHOD (or override).
'standard': pcov[-1,-1] (SE of intercept, with closed-form fallback).
'calc_t0' : np.std(np.abs(residuals)) / sqrt(n) (Calculate T0 convention)."""
m = method or SIGMA_METHOD
if m == 'calc_t0':
return float(np.std(np.abs(residuals)) / np.sqrt(n)) if n > 0 else 1e-9
# standard SE of intercept
if pcov is not None and pcov.shape[0] > 0 and np.isfinite(pcov[-1, -1]):
return float(np.sqrt(np.abs(pcov[-1, -1])))
# closed-form fallback (Li et al. 2019 Eq. 1)
if n < 3:
return 1e-9
x_bar = float(np.mean(t))
Sxx = float(np.sum((t - x_bar) ** 2))
s = float(np.std(residuals, ddof=max(1, n - len(popt))))
return s * np.sqrt(1.0 / n + x_bar ** 2 / Sxx) if Sxx > 0 else s
# ── Irradiation parameters (hardcoded, same for entire irradiation) ──────────
_PR = {
'PR_39_37ca' : 0.000377631,
'PR_39_37ca_s': 0.0000609,
'PR_36_37ca' : 0.0000346,
'PR_36_37ca_s': 4.97e-7,
'PR_40_39k' : 0.025004,
'PR_40_39k_s': 0.002866,
'PR_38_39k' : 0.0126288,
'PR_38_39k_s': 0.000010529,
'R_40_36a' : 298.56,
'R_40_36a_s' : 0.31,
'R_38_36a' : 0.1885,
'R_38_36a_s' : 0.000347,
'PR_36_38cl' : 0.0,
}
def _propagate(T0, sT0, bT0, bsT0):
"""
Given T0[5] and σ_T0[5] for one signal step, and blank T0[5]/σ[5],
compute component values and their 1-sigma uncertainties.
Returns a dict of (value, sigma, ok) triples.
"""
p = _PR
# net T0 = signal - blank
t = T0 - bT0
st = np.sqrt(sT0**2 + bsT0**2)
# indices: 0=36, 1=37, 2=38, 3=39, 4=40
# ── 36 chain ─────────────────────────────────────────────
Ar36_ca = t[1] * p['PR_36_37ca']
sAr36_ca = Ar36_ca * np.sqrt((st[1]/t[1])**2 + (p['PR_36_37ca_s']/p['PR_36_37ca'])**2) if (t[1]!=0 and p['PR_36_37ca']!=0) else 0
Ar36_air = t[0] - Ar36_ca
sAr36_air= np.sqrt(st[0]**2 + sAr36_ca**2)
# ── 39 chain ─────────────────────────────────────────────
Ar39_ca = t[1] * p['PR_39_37ca']
sAr39_ca = Ar39_ca * np.sqrt((st[1]/t[1])**2 + (p['PR_39_37ca_s']/p['PR_39_37ca'])**2) if (t[1]!=0 and p['PR_39_37ca']!=0) else 0
Ar39_K = t[3] - Ar39_ca
sAr39_K = np.sqrt(st[3]**2 + sAr39_ca**2)
# ── 40 chain ─────────────────────────────────────────────
Ar40_air = Ar36_air * p['R_40_36a']
sAr40_air= Ar40_air * np.sqrt((sAr36_air/Ar36_air)**2 + (p['R_40_36a_s']/p['R_40_36a'])**2) if Ar36_air!=0 else abs(sAr36_air*p['R_40_36a'])
Ar40_K = Ar39_K * p['PR_40_39k']
sAr40_K = Ar40_K * np.sqrt((sAr39_K/Ar39_K)**2 + (p['PR_40_39k_s']/p['PR_40_39k'])**2) if Ar39_K!=0 else abs(sAr39_K*p['PR_40_39k'])
Ar40_r = t[4] - Ar40_air - Ar40_K
sAr40_r = np.sqrt(st[4]**2 + sAr40_air**2 + sAr40_K**2)
Ar40r_pct= Ar40_r / t[4] * 100 if t[4] != 0 else 0
# ── 38 internal consistency check ────────────────────────
Ar38_air_pred = Ar36_air * p['R_38_36a']
Ar38_K_pred = Ar39_K * p['PR_38_39k']
Ar38_cl = t[2] - Ar38_air_pred - Ar38_K_pred
# sigma of 38Ar(cl): all terms quadrature
sAr38_cl = np.sqrt(
st[2]**2 +
(sAr36_air * p['R_38_36a'])**2 +
(sAr39_K * p['PR_38_39k'])**2
)
chi2_38 = (Ar38_cl / sAr38_cl)**2 if sAr38_cl > 0 else 0
sig38_n = Ar38_cl / sAr38_cl if sAr38_cl > 0 else 0 # n-sigma significance
return {
'Ar36_air' : (Ar36_air, sAr36_air, Ar36_air > 0),
'Ar36_ca' : (Ar36_ca, sAr36_ca, True),
'Ar39_K' : (Ar39_K, sAr39_K, Ar39_K > 0),
'Ar39_ca' : (Ar39_ca, sAr39_ca, True),
'Ar40_air' : (Ar40_air, sAr40_air, Ar36_air > 0),
'Ar40_K' : (Ar40_K, sAr40_K, Ar39_K > 0),
'Ar40_r' : (Ar40_r, sAr40_r, Ar40_r > 0),
'Ar40r_pct': (Ar40r_pct, 0, 0 < Ar40r_pct < 100),
'Ar38_cl' : (Ar38_cl, sAr38_cl, True),
'chi2_38' : (chi2_38, 0, chi2_38 < 4), # <4 = within 2σ
'sig38_n' : (sig38_n, 0, abs(sig38_n) < 2),
}
# ── colour palette (Refined Classic, HANDOFF-QSS-spec §1) ───────────────────
# v3.9.12: AR_COLS 還原原版(使用者回饋:diagram 樣式要維持原樣)。
# AR_COLS = matplotlib 圖表線色(mV / T₀ range / degassing 等)+圖表標題;
# ISO = 只給 UI 表格文字上色(Mass Ratio Isotope 欄),不進圖表。
AR_COLS = ['#1a5fb4','#1c7a3a','#8a5a00','#b41a1a','#533ab7']
ISO = {'36':'#2b6cb0', '37':'#2f8f5b', '38':'#c98a1a', '39':'#cc4436', '40':'#6b4fc9'}
AR_NAMES = ['36','37','38','39','40']
BG = '#f5f4f0' # app 背景(暖米)
PNL = '#f0f0f0' # 面板/按鈕面
HDR = '#eeede8' # 表頭 / 未選 tab / chip 底(putty)
WHITE = '#ffffff' # 圖表畫布 / 表格 body / 選中 tab
BRD = '#cccccc' # 標準 1px 邊框
BRD2 = '#bbbbbb' # 表頭格邊框
HAIR = '#dddbd4' # 段落標題細線 / chip 內分隔
TXT = '#222222'
TXT2 = '#444444'
TXT3 = '#888888'
ACCENT = '#1a5fb4' # 主色(navy 藍):主行動、選中、進度
ACCENT_D = '#144a8f' # 主色深:按鈕沉底邊、hover
ACCENT_BG = '#d6e8f7' # 主色淡底:選中 chip / toggle
OK = '#2e7d52'
WARN = '#b45309' # 琥珀;Manual 邊框用 #c0a020
DANGER = '#c0282d' # 負值 / 錯誤紅
DANGER_BG = '#fff0f0'
# legacy 語意底色(既有 caller 仍引用)
BLUE_BG = ACCENT_BG
GRN_BG = '#d0edda'
AMB_BG = '#fdf0d0'
RED_BG = '#fde8e8'
def _sheet():
return f"""
QWidget{{background:{BG};color:{TXT};font-family:Georgia,serif;font-size:11px;}}
QLabel{{background:transparent;}}
/* 標準按鈕 */
QPushButton{{background:{PNL};color:{TXT};border:1px solid {BRD};border-radius:3px;padding:6px 8px;}}
QPushButton:hover{{background:{BG};}}
/* 表格 */
QTableWidget{{gridline-color:{BRD};font-family:'Courier New',monospace;font-size:11px;background:{WHITE};}}
QHeaderView::section{{background:{HDR};border:1px solid {BRD2};padding:4px 7px;font-family:Georgia,serif;font-size:11px;font-weight:normal;color:#333;}}
/* 表單輸入 */
QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox{{background:{WHITE};border:1px solid #cbcbcb;border-radius:3px;padding:3px 5px;font-family:'Courier New',monospace;font-size:11px;color:{TXT};}}
QComboBox::drop-down{{border:none;}}
/* tabs:全域過渡樣式(選中不加粗 — Qt 不重算 tab 寬,粗體會裁字) */
QTabBar::tab{{padding:4px 12px;border:1px solid {BRD};border-bottom:none;background:{HDR};}}
QTabBar::tab:selected{{background:{WHITE};color:{ACCENT};}}
QTabWidget::pane{{border:1px solid {BRD};}}
"""
def _btn_style(bg, col, brd):
return (f'QPushButton{{background:{bg};color:{col};border:1px solid {brd};'
f'border-radius:2px;padding:5px 4px;font-size:10px;font-family:Georgia,serif;}}'
f'QPushButton:hover{{background:{BG};}}')
def _run_btn_style():
"""§3.3 主行動按鈕(top bar 右上 Run):實心 ACCENT + 沉底邊。"""
return (f"QPushButton{{background:{ACCENT};color:#fff;"
f"border:1px solid {ACCENT_D};border-bottom:2px solid {ACCENT_D};"
f"border-radius:6px;padding:9px 22px;font-size:13px;font-weight:bold;}}"
f"QPushButton:hover{{background:{ACCENT_D};}}"
f"QPushButton:disabled{{background:#aaa;border-color:#aaa;}}")
def _sb_btn_style():
"""§4 sidebar 標準按鈕。"""
return (f'QPushButton{{background:{PNL};color:{TXT};border:1px solid {BRD};'
f'border-radius:3px;padding:12px 2px;font-size:12px;'
f'font-family:Georgia,serif;}}'
f'QPushButton:hover{{background:{BG};}}')
def _sb_manual_on_style():
"""§4 Manual 作用中 = 琥珀。"""
return ('QPushButton{background:#fff4d0;color:#8a5a00;'
'border:1.5px solid #c0a020;border-radius:3px;'
'padding:12px 2px;font-size:12px;font-family:Georgia,serif;'
'font-weight:bold;}'
'QPushButton:hover{background:#fff4d0;}')
# §7 參數列按鈕三型:primary(唯一實心 ACCENT)/ outline / ghost
def _primary_btn_style():
return (f'QPushButton{{background:{ACCENT};color:#fff;'
f'border:1px solid {ACCENT_D};border-radius:3px;'
'font-size:11px;font-weight:bold;padding:3px 12px;}'
f'QPushButton:hover{{background:{ACCENT_D};}}')
def _outline_btn_style():
return (f'QPushButton{{background:{WHITE};color:{ACCENT};'
f'border:1px solid {ACCENT};border-radius:3px;'
'font-size:11px;padding:3px 10px;}'
f'QPushButton:hover{{background:{ACCENT_BG};}}')
def _ghost_btn_style():
return (f'QPushButton{{background:{WHITE};color:{TXT2};'
f'border:1px solid {BRD};border-radius:3px;'
'font-size:11px;padding:3px 10px;}'
f'QPushButton:hover{{background:{BG};}}')
# §8 段落標題:Georgia 12px 粗體 + 右側 1px HAIR 延伸線,無副標
_HDR_LBL_SS = ('font-family:Georgia,serif;font-size:12px;font-weight:bold;'
f'color:{TXT2};background:transparent;border:none;')
def _hdr_row(lbl):
"""把既有標題 QLabel 包成「標題 + 右側 HAIR 延伸線」的一列。
傳入 QLabel(text 可之後動態 setText),回傳可 addWidget 的容器。"""
w = QtWidgets.QWidget()
hl = QtWidgets.QHBoxLayout(w)
hl.setContentsMargins(0, 0, 0, 0); hl.setSpacing(8)
ln = QtWidgets.QFrame()
ln.setFixedHeight(1)
ln.setStyleSheet(f'background:{HAIR};border:none;')
hl.addWidget(lbl)
hl.addWidget(ln, 1)
return w
# ── helpers ─────────────────────────────────────────────────────────────────
def _sf(v, d=0.0):
try: return float(v)
except: return d
def _is_neg_num(s):
"""v3.8.64: True if the cell text parses to a negative number.
Tolerates a trailing '%', surrounding whitespace, thousands commas and
a leading '±' (never negative). Non-numeric / blank → False."""
if s is None:
return False
t = str(s).strip().rstrip('%').replace(',', '').strip()
if not t or t in ('-', '—', '±'):
return False
try:
return float(t) < 0
except Exception:
return False
def _mswd_verdict(mswd, df):
"""v3.9.15: (color, label) for an MSWD given its degrees of freedom.
Exact 95% upper bound from MSWD ~ chi2(df)/df (matches PlaneFit3D._mswd_ci),
replacing the Wendt-Carl (1991) normal-approximation threshold used through
v3.8.82 (1 + 2·√(2/df)) — the normal approximation is systematically too
strict at the low df typical of Ar-Ar step-heating (e.g. df=5: 2.26 vs the
exact 2.57). Caller must pass the df matching how its MSWD was computed:
N-1 for plateau (WMA, one free parameter), N-2 for isochron regression
(slope + intercept) — through v3.8.82 this function hardcoded N-2 for
both, silently wrong for plateau callers. Green inside the band, amber up
to 2×, red beyond (excess scatter / disturbed)."""
if mswd is None or df is None or df < 1:
return ('#888888', '')
hi = float(_chi2.ppf(0.975, df) / df)
if mswd <= hi:
return ('#2e7d52', 'OK')
if mswd <= 2.0 * hi:
return ('#a06000', 'high')
return ('#c0282d', 'excess scatter')
def _fe(v):
try: return '{:.6e}'.format(float(v))
except: return '0'
def _norm_date(raw):
try:
p = raw.split('/')
if len(p)==3: return '{}/{:02d}/{:02d}'.format(p[0],int(p[1]),int(p[2]))
except: pass
return raw
# ── dat parser ───────────────────────────────────────────────────────────────
def _extract_dat_date(filepath):
"""Extract analysis date from .dat header.
Looks for 'Project #' line which contains YYYY/M/D, falls back to
line[1] (MM/DD HH:MM) combined with current year. Returns datetime.date
or None."""
from datetime import date as _date
try:
with open(filepath, 'rb') as f:
lines = f.read().decode('latin-1').splitlines()
# Look for "Project #" line (typically has YYYY/M/D)
for ln in lines[:30]:
if 'Project' in ln:
parts = ln.split()
for tok in parts:
if '/' in tok and tok.count('/') == 2:
y, m, d = tok.split('/')
try:
return _date(int(y), int(m), int(d))
except (ValueError, TypeError):
continue
# Fallback: line[1] is "MM/DD HH:MM"
if len(lines) > 1:
t = lines[1].strip().split()[0]
if '/' in t:
m, d = t.split('/')
# default year — try other places in file or use file mtime
try:
import os as _os
mt = _os.path.getmtime(filepath)
yr = _date.fromtimestamp(mt).year
return _date(yr, int(m), int(d))
except Exception:
pass
except Exception:
pass
return None
def compute_delta_t_days(ogd_str, spd_date):
"""Δt = SPD − OGD, both as datetime.date.
ogd_str: YYYYMMDD or YYYY-MM-DD or YYYY/M/D format from params['OG Date'].
Returns int days, or 0 if cannot parse."""
from datetime import date as _date
import re as _re
if spd_date is None or not ogd_str:
return 0
try:
s = _re.sub(r'[-/]', '', str(ogd_str).strip())
if len(s) < 8: return 0
ogd = _date(int(s[0:4]), int(s[4:6]), int(s[6:8]))
d = (spd_date - ogd).days
return max(0, int(d))
except Exception:
return 0
def parse_dat(filepath, numCycle=10):
with open(filepath,'rb') as f: raw=f.read()
lines = raw.decode('latin-1').splitlines()
stl = 0
for i in reversed(range(len(lines))):
if len(lines[i].split())==4: stl=i; break
stl -= (6*numCycle-2)
info = ['','','','','']
try:
if lines[2].strip()=='':
info[0]=lines[17].split()[2]+' '+lines[4].split()[3]
info[1]=lines[18].split()[2]; info[2]=lines[0].split()[1]
info[3]=lines[21].split()[2]; info[4]=lines[23].split()[2]
else:
info[0]=lines[15].split()[2]; info[1]=lines[16].split()[2]
info[2]=lines[0].split()[1]; info[3]=lines[19].split()[2]
info[4]=lines[21].split()[2]
except: pass
v_t = np.zeros((5,numCycle,2))
for i in range(numCycle):
for j in range(5):
parts=lines[stl+6*i+j].split()
v_t[j,i,0]=float(parts[2]); v_t[j,i,1]=float(parts[3])
return v_t, info
# ── best-mask (min exclusions) ───────────────────────────────────────────────
def _combos(n, k, limit=300):
if k>=n: return [list(range(n))]
result=[]
def go(s,c):
if len(c)==k: result.append(list(c)); return
for i in range(s,n):
if len(result)>=limit: return
c.append(i); go(i+1,c); c.pop()
go(0,[]); return result
def best_mask(vt_i, numCycle, blank_t0=None, fit_type=0):
f=Utilities.fit_func_list[fit_type]
bm=np.ones(numCycle); bs=np.inf
for ne in range(7):
nu=numCycle-ne
if nu<4: break
imp=False
for combo in _combos(numCycle,nu):
m=np.zeros(numCycle)
for idx in combo: m[idx]=1
sel=np.where(m==1)[0]; t,v=vt_i[sel,1],vt_i[sel,0]
try:
popt,_=curve_fit(f,t,v); t0=f(0,*popt)
sig=np.std(np.abs(v-f(t,*popt)))/np.sqrt(nu)
except: continue
if blank_t0 is not None and t0<=blank_t0: continue
if sig<bs*0.95: bs=sig; bm=m.copy(); imp=True
if ne>0 and not imp: break
return bm
def calc_t0(vt, mask, numCycle, fit_type=0):
"""Batch T0 fit for all 5 isotopes. σ uses pcov[-1,-1] (see _fit_one)."""
f=Utilities.fit_func_list[fit_type]
T0=np.zeros(5); SIG=np.zeros(5); R=np.zeros(5)
for i in range(5):
sel=np.where(mask[i]==1)[0]; n=len(sel)
if n<2: continue
t,v=vt[i,sel,1],vt[i,sel,0]
try:
popt,pcov=curve_fit(f,t,v)
T0[i]=f(0,*popt)
# σ_T0 = SE of intercept from covariance (not std/√n; see _fit_one)
if pcov is not None and pcov.shape[0] > 0 and np.isfinite(pcov[-1,-1]):
SIG[i] = float(np.sqrt(np.abs(pcov[-1,-1])))
else:
SIG[i] = float(np.std(np.abs(v-f(t,*popt)))/np.sqrt(n))
R[i]=r2_score(v,f(t,*popt))
except: pass
return T0,SIG,R
def write_t0_csv(filepath, info, T0, SIG, R):
os.makedirs(os.path.dirname(filepath), exist_ok=True)
date_str=_norm_date(info[3])
with open(filepath,'w') as f:
f.write("Samp#,Min,T,Date,iradiation PK 90%,Mass,T0,T0_SIGMA,R^2\n")
for i in range(5):
f.write(f"{info[0]},{info[1]},{info[2]},{date_str},{info[4]},Ar{i+36},{T0[i]},{SIG[i]},{R[i]}\n")
# ═══════════════════════════════════════════════════════════
# MvCanvas — one isotope, matplotlib-based, independent refresh
# Row 1: mV vs time (matplotlib → QPixmap)
# Row 2: cycle buttons (4+4+2)
# Row 3: T0 vs 2σ scatter (matplotlib → QPixmap)
# ═══════════════════════════════════════════════════════════
import io as _io
# ═══════════════════════════════════════════════════════════
# Session save / load (.adr file format) v3.8.28
# ═══════════════════════════════════════════════════════════
#
# .adr = zip archive containing the AutoPipeline Calculate-T₀ state:
#
# meta.json schema_version, app_version, fit, manual, nc, cur,
# blank_name, step_names, sinfo, binfo, sigma_method,
# step_dates
# blank_vt.npz five arrays ar36..ar40, each shape (nc, 2) = (v, t)
# blank_mask.npy shape (5, nc), 1=include, 0=exclude per cycle
# sig/<step>/vt.npz per-step signal arrays (same layout as blank)
# sig/<step>/mask.npy per-step mask (5, nc)
#
# Loading restores everything needed to resume from Calculate T₀ without
# re-importing the original .dat files. Downstream pipeline (MassRatio /
# Datum / AgeCalc) is not stored — re-run via the Pipeline button.
SESSION_SCHEMA_VERSION = 1
def save_session_adr(path, state):
"""Write state dict to .adr zip. state keys: meta, bvt, bmask, svt, smask."""
meta = dict(state['meta'])
meta['schema_version'] = SESSION_SCHEMA_VERSION
with zipfile.ZipFile(path, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr('meta.json', json.dumps(meta, indent=2, default=str))
if state.get('bvt') is not None:
buf = _io.BytesIO()
np.savez(buf, **{f'ar{i+36}': state['bvt'][i] for i in range(5)})
zf.writestr('blank_vt.npz', buf.getvalue())
buf = _io.BytesIO()
np.save(buf, np.asarray(state['bmask']))
zf.writestr('blank_mask.npy', buf.getvalue())
for nm, vt in state.get('svt', {}).items():
buf = _io.BytesIO()
np.savez(buf, **{f'ar{i+36}': vt[i] for i in range(5)})
zf.writestr(f'sig/{nm}/vt.npz', buf.getvalue())
buf = _io.BytesIO()
np.save(buf, np.asarray(state['smask'][nm]))
zf.writestr(f'sig/{nm}/mask.npy', buf.getvalue())
def load_session_adr(path):
"""Read .adr zip. Returns dict with meta, bvt, bmask, svt, smask."""
out = {'svt': {}, 'smask': {}, 'bvt': None, 'bmask': None}
with zipfile.ZipFile(path, 'r') as zf:
out['meta'] = json.loads(zf.read('meta.json'))
ver = out['meta'].get('schema_version', 0)
if ver > SESSION_SCHEMA_VERSION:
raise ValueError(
f'Session schema v{ver} newer than supported '
f'v{SESSION_SCHEMA_VERSION}. Upgrade pyADR.')
names = zf.namelist()
if 'blank_vt.npz' in names:
npz = np.load(_io.BytesIO(zf.read('blank_vt.npz')))
out['bvt'] = [npz[f'ar{i+36}'] for i in range(5)]
out['bmask'] = np.load(_io.BytesIO(zf.read('blank_mask.npy')))
for nm in out['meta'].get('step_names', []):
vt_key = f'sig/{nm}/vt.npz'; mk_key = f'sig/{nm}/mask.npy'
if vt_key in names and mk_key in names:
npz = np.load(_io.BytesIO(zf.read(vt_key)))
out['svt'][nm] = [npz[f'ar{i+36}'] for i in range(5)]
out['smask'][nm] = np.load(_io.BytesIO(zf.read(mk_key)))
return out
# ═══════════════════════════════════════════════════════════
# Shared sidebar (v3.8.31) — used by MassRatioPage / AgeCalcPage
# ═══════════════════════════════════════════════════════════
#
# Mirrors CalcT0Page's sidebar style (91×51 buttons, vertical column).
# Subset of Calc-T0 sidebar: Return / Save To / Load Blank / Load Sample
# / Save Session / Open Session. The page-specific 'Save To' handler is
# passed in (MassRatioPage._save vs AgeCalcPage._export).
#
# Load Blank / Load Sample switch back to CalcT0Page (stack index 0) and
# fire the corresponding file dialog. Save/Open Session delegate to
# CalcT0Page's session methods (single source of truth).
def _build_minimal_sidebar(page, save_handler, save_label='Save',
with_closure=False):
"""Return a QWidget sidebar to be placed on the left of MassRatioPage /
AgeCalcPage. `page` is the host widget (used to walk up the parent
chain to find AutoPipelineWindow). `save_handler` is bound at call
time so the right method fires for this page. `with_closure=True`
(AgeCalcPage only) appends the Closure Temperature button below
Parameter (v3.8.95)."""
# v3.9.7 (§4): 寬 114、spacing=3 統一小縫隙;按鈕棄 91×51 固定尺寸,
# 改 _sb_btn_style()(padding 12px 2px / 3px 圓角 / 12px 字)填滿欄寬。
sb = QtWidgets.QWidget()
sb.setFixedWidth(114)
sbl = QtWidgets.QVBoxLayout(sb)
sbl.setContentsMargins(2, 4, 2, 4); sbl.setSpacing(3)
def _sb_btn(txt):
b = QtWidgets.QPushButton(txt)
b.setStyleSheet(_sb_btn_style())
return b
def _find_window():
p = page.parent()
while p is not None and not hasattr(p, 't0Page'):
p = p.parent()
return p
btnReturn = _sb_btn('Return')
def _on_return():
# v3.8.42: Return now goes ONE PAGE BACK in the pipeline stack
# (Mass Ratio → Calculate T₀, Age Calc → Mass Ratio), not all the
# way to pyADR Home. CalcT0Page's own sidebar Return (idx=0)
# still goes home — that's wired separately in t0Page.returnBtn.
win = _find_window()
if win is None or not hasattr(win, 'stack'):
return
cur_idx = win.stack.currentIndex()
if cur_idx > 0:
target = cur_idx - 1
# Prefer _go() so pipeline strip + next button update too
if hasattr(win, '_go'):
win._go(target)
else:
win.stack.setCurrentIndex(target)
else:
# Fallback (shouldn't happen — this helper isn't used on
# CalcT0Page): go home via t0Page.returnBtn
t0 = getattr(win, 't0Page', None)
if t0 is not None and hasattr(t0, 'returnBtn'):
t0.returnBtn.click()
btnReturn.clicked.connect(_on_return)
btnSave = _sb_btn(save_label)
btnSave.clicked.connect(save_handler)
# v3.8.41: removed Load Blank / Load Sample from MassRatio/AgeCalc
# sidebar per user request — loading raw .dat only makes sense on the
# Calculate T₀ page (where it actually shows the mV chart). User can
# still trigger them from CalcT0Page's own sidebar (those stay).
btnSaveSess = _sb_btn('Save Session')
def _on_save_session():
win = _find_window()
if win is not None and hasattr(win, 't0Page'):
win.t0Page._save_session()
btnSaveSess.clicked.connect(_on_save_session)
btnOpenSess = _sb_btn('Open Session')
def _on_open_session():
win = _find_window()
if win is not None and hasattr(win, 't0Page'):
win.t0Page._open_session()
btnOpenSess.clicked.connect(_on_open_session)
# v3.8.85: Parameter button → main program's Parameter Settings page.
# Exposed on the page; NTNU_DataReduction wires the click (like returnBtn).
btnParam = _sb_btn('Parameter')
page.paramBtn = btnParam
# v3.8.95: Closure Temperature calculator (Dodson 1973, Schaen et al.
# 2021 Table 5) below Parameter — AgeCalcPage (AgeCalc+Datum) only.
btnClosure = None
if with_closure:
btnClosure = _sb_btn('Closure\nTemp')
def _on_closure():
win = _find_window()
if win is not None and hasattr(win, '_show_closure_temp'):
win._show_closure_temp()
return
try:
import ClosureTemperature
dlg = ClosureTemperature.ClosureTempDialog(page)
dlg.exec_()
except Exception as e:
QtWidgets.QMessageBox.warning(
page, 'Closure Temperature',
f'Closure-temperature tool unavailable: {e}')
btnClosure.clicked.connect(_on_closure)
page.closureBtn = btnClosure
# v3.9.10: 組間大間隙取消(使用者回饋),統一 spacing=3 緊排
btns = [btnReturn, btnSave, btnOpenSess, btnSaveSess, btnParam]
if btnClosure is not None:
btns.append(btnClosure)
for b in btns:
sbl.addWidget(b)
sbl.addStretch()
return sb
import matplotlib as _mpl
_mpl.use('Agg')
import matplotlib.pyplot as _plt
import matplotlib.ticker as _ticker
# Interactive scatter canvas uses Qt5Agg backend in a separate figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as _FigCanvas
import matplotlib.figure as _mfig
def _fit_one_linear_fast(vt_i, mask):
"""v3.8.27: closed-form linear fit y=a·t+b. Matches scipy.curve_fit on
`Utilities.linear` to machine precision (both reduce to OLS), but skips
scipy.optimize.leastsq's setup overhead → ~50–100× faster.
Returns (t0=b, sig, r2, popt=[a,b]).
"""
sel = np.where(mask == 1)[0]
n = len(sel)
if n < 2:
return 0.0, 1e-9, 0.0, None
t = vt_i[sel, 1]; v = vt_i[sel, 0]
n_f = float(n)
sum_t = t.sum(); sum_v = v.sum()
sum_tt = (t*t).sum(); sum_tv = (t*v).sum()
denom = n_f * sum_tt - sum_t * sum_t
if abs(denom) < 1e-30:
return 0.0, 1e-9, 0.0, None
a = (n_f * sum_tv - sum_t * sum_v) / denom
b = (sum_v - a * sum_t) / n_f
residuals = v - (a*t + b)
# σ via SIGMA_METHOD — replicates _sigma_from_fit exactly
if SIGMA_METHOD == 'calc_t0':
sig = float(np.std(np.abs(residuals)) / np.sqrt(n_f))
else:
# standard SE of intercept (closed-form, no pcov needed):
# σ²(b) = σ²_res * (1/n + t̄²/Sxx)
if n > 2:
sigma2_res = (residuals*residuals).sum() / (n - 2)
mean_t = sum_t / n_f
Sxx = sum_tt - sum_t * sum_t / n_f
if Sxx > 1e-30:
sig = float(np.sqrt(sigma2_res * (1.0/n_f + mean_t*mean_t/Sxx)))
else:
sig = float(np.sqrt(max(sigma2_res / n_f, 1e-30)))
else:
sig = 1e-9
# r²
ss_res = (residuals*residuals).sum()
v_mean = sum_v / n_f
ss_tot = ((v - v_mean)**2).sum()
r2 = float(1.0 - ss_res/ss_tot) if ss_tot > 1e-30 else 0.0
return float(b), sig, r2, np.array([a, b])
def _fit_one_average_fast(vt_i, mask):
"""v3.8.27: closed-form average fit y=a (constant). Matches curve_fit on
`Utilities.average` exactly."""
sel = np.where(mask == 1)[0]
n = len(sel)
if n < 1:
return 0.0, 1e-9, 0.0, None
v = vt_i[sel, 0]
n_f = float(n)
a = float(v.mean())
residuals = v - a
if SIGMA_METHOD == 'calc_t0':
sig = float(np.std(np.abs(residuals)) / np.sqrt(n_f))
else:
if n > 1:
sigma2_res = (residuals*residuals).sum() / (n - 1)
sig = float(np.sqrt(sigma2_res / n_f))
else:
sig = 1e-9
return a, sig, 0.0, np.array([a])
def _fit_one(f, vt_i, mask):
"""Returns (t0, sig, r2, popt) or (0,1e-9,0,None).
v3.8.27: linear/average get closed-form fast path (50–100× faster than
curve_fit), other fit types fall back to scipy.curve_fit. The fast paths
are bit-identical to curve_fit results (both are OLS for these forms).
σ_T0 BUG FIX (2026-05):
Earlier this returned `sig = std(residuals)/√n`, which is the standard
error of the MEAN, not of the y-INTERCEPT. For step-heating data with
cycle times t ∈ [320..600] s, the intercept extrapolated to t=0 has a
much larger uncertainty (typically ~10× of std/√n) because of the
lever-arm from t̄ to 0.
Fixed: σ_T0 is now `sqrt(pcov[-1,-1])` — the SE of the y-intercept from
the regression covariance matrix (matches `_fit_with_errors`'s
`sig_model`, Li et al. 2019 Eq. 1). For linear y=a·t+b and constant
y=b fit funcs in `fit_func_list`, the intercept is the LAST parameter
of popt; hence pcov[-1,-1] is its variance.
"""
# v3.8.27 fast-path dispatch
if f is Utilities.linear:
return _fit_one_linear_fast(vt_i, mask)
if f is Utilities.average:
return _fit_one_average_fast(vt_i, mask)
sel = np.where(mask == 1)[0]
n = len(sel)
if n < 2:
return 0.0, 1e-9, 0.0, None
t, v = vt_i[sel, 1], vt_i[sel, 0]
try:
popt, pcov = curve_fit(f, t, v)
t0 = f(0, *popt)
residuals = v - f(t, *popt)
# σ via global SIGMA_METHOD toggle
sig = _sigma_from_fit(residuals, n, popt, pcov, t)
r2 = r2_score(v, f(t, *popt))
return t0, sig, r2, popt
except Exception:
return 0.0, 1e-9, 0.0, None
def _fit_with_errors(f, vt_i, mask):
"""Returns (t0, sig_a, sig_m, r2, popt).
Two σ slots kept for back-compat with existing scoring code, BUT both
now respect the global SIGMA_METHOD toggle:
sig_a = σ via std(|residuals|)/√n (Calculate T0 convention)
sig_m = σ via pcov[-1,-1] (statistically correct SE of intercept)
Down-stream scoring uses `sig_a + sig_m`. To avoid double-counting the
"wrong" σ, when SIGMA_METHOD == 'standard' both slots return the same
standard-SE value; when 'calc_t0' both return std(|r|)/√n. This makes
`sig_a + sig_m == 2·σ_selected`, a constant scale on the score that
doesn't affect ranking.
"""
sel = np.where(mask == 1)[0]
n = len(sel)
if n < 2:
return 0.0, 1e-9, 1e-9, 0.0, None
t, v = vt_i[sel, 1], vt_i[sel, 0]
try:
popt, pcov = curve_fit(f, t, v)
t0 = f(0, *popt)
residuals = v - f(t, *popt)
sig = _sigma_from_fit(residuals, n, popt, pcov, t)
# both slots = selected σ → score uses 2·σ, ranking preserved
r2 = r2_score(v, f(t, *popt))
return t0, sig, sig, r2, popt
except Exception:
return 0.0, 1e-9, 1e-9, 0.0, None
def _both_sigmas(f, vt_i, mask):
"""Compute BOTH σ formulas for the same fit. Useful for side-by-side reporting.
Returns (t0, sig_calc_t0, sig_standard, r2, popt)."""
sel = np.where(mask == 1)[0]
n = len(sel)
if n < 2:
return 0.0, 1e-9, 1e-9, 0.0, None
t, v = vt_i[sel, 1], vt_i[sel, 0]
try:
popt, pcov = curve_fit(f, t, v)
t0 = f(0, *popt)
residuals = v - f(t, *popt)
sig_calc_t0 = _sigma_from_fit(residuals, n, popt, pcov, t, method='calc_t0')
sig_standard = _sigma_from_fit(residuals, n, popt, pcov, t, method='standard')
r2 = r2_score(v, f(t, *popt))
return t0, sig_calc_t0, sig_standard, r2, popt
except Exception:
return 0.0, 1e-9, 1e-9, 0.0, None
def _all_combos_cached(n, min_use=4, max_excl=6, limit=200):
"""All (mask, n_used) combos with n_used >= min_use."""
results = []
def go(start, cur, remaining):
results.append(np.array(cur + [1]*remaining, dtype=float))
if remaining == 0:
return
for excl_from in range(start, n):
if n - excl_from - 1 < (min_use - len(cur) - remaining + 1):
break
new = cur + [1]*(excl_from - start) + [0]
rem = n - excl_from - 1
if len(new) + rem >= min_use and len(results) < limit:
pass
# simpler: enumerate all combos of size k for k = n down to min_use
results.clear()
for k in range(n, min_use - 1, -1):
for combo in _iter_combos(n, k, limit - len(results)):
m = np.zeros(n)
for idx in combo:
m[idx] = 1
results.append(m)
if len(results) >= limit:
return results
return results
def _iter_combos(n, k, limit=200):
"""Generate k-combinations from n elements, up to limit.
Optimized iterative version (V3.4.1) using index-based approach.
Avoids deep recursion and excessive list copying.
Time: O(C(n,k) x k) worst case, but early-exits on limit.
~50-70% faster than original recursive version.
"""
result = []
if k <= 0 or k > n:
return result
indices = list(range(k))
while indices[0] < n - k + 1:
result.append(indices[:]) # Shallow copy (k elements only)
if len(result) >= limit:
return result
# Next combination
i = k - 1
while i >= 0 and indices[i] == n - k + i:
i -= 1
if i < 0:
break
indices[i] += 1
for j in range(i + 1, k):
indices[j] = indices[j - 1] + 1
return result
# ═══════════════════════════════════════════════════════════
# Bi-directional Strategy Core Functions
# ═══════════════════════════════════════════════════════════
# Strategy parameters (can be tuned)
STRAT_ALPHA = 0.3 # n weight: small n → larger score penalty
STRAT_BETA = 0.5 # cycle spread penalty strength (only for n≤5)
SPREAD_MIN_SPAN = {4: 5, 5: 6} # minimum required span for n=4, n=5
def _n_weight(n, n_max=10, n_min=4):
"""Weight function: penalize small n heavily.
Returns 0 for n_max, 1 for n_min.
Exponential growth makes small-n combinations clearly worse.
"""
# Linear in [0, 1]
x = (n_max - n) / (n_max - n_min)
# Exponential: n=10 → 0, n=9 → 0.28, n=7 → 1.0, n=4 → 4.0
return (np.exp(2 * x) - 1) / (np.exp(2) - 1) * 4
def _cycle_spread_penalty(mask, n_total=10):
"""Penalize 'clustered' cycle selection for n=4, n=5.