-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqcode_example_v6_enhanced.py
More file actions
3167 lines (2663 loc) · 153 KB
/
qcode_example_v6_enhanced.py
File metadata and controls
3167 lines (2663 loc) · 153 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
"""
QCoDeS Lab Tools - SQUID CPR Analysis Script - Refactored Version
===================================================================
This script implements a staged fitting approach for SQUID CPR analysis.
The workflow includes:
1. Defining a modular SQUIDAnalyzer class for core physics and fitting.
2. Defining helper functions for data loading, preprocessing, visualization, and interpretation.
3. Executing the analysis workflow in a clear, step-by-step main block:
a. Loading a specific QCoDeS dataset.
b. Preprocessing data: unit conversion and centering the magnetic field.
c. Extracting critical current vs. magnetic field (CPR) data.
d. Running a staged analysis:
i. Pre-fitting with a simple sine model.
ii. Fitting with a single-transparency model.
iii.Fitting with a dual-transparency model.
e. Visualizing the results with comprehensive plots, including a dV/dI heatmap.
f. Interpreting and printing the final physical parameters.
"""
import os
import json
from pathlib import Path
import qcodes as qc
from qcodes.dataset.data_set import DataSet
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
from scipy.signal import find_peaks, detrend
import holoviews as hv
from holoviews import opts
import panel as pn
from scipy.interpolate import griddata
import scipy.constants as sc
from scipy.fft import fft, fftfreq
from lmfit import minimize, Parameters, report_fit, Model
from lmfit.model import ModelResult
from typing import Dict, Tuple, Optional, Any, List
import itertools
from rich.progress import track, Progress
from joblib import Parallel, delayed
from matplotlib import lines
import time
import psutil # For system resource monitoring
import argparse
# Import qcodes_optimized for enhanced parameter table
# from qcodes_optimized import ParameterTableBuilder
# --- MCMC functionality removed ---
# JAX and BlackJAX setup has been removed to simplify the codebase
# MCMC sampling capabilities have been disabled
def parse_run_id(run_id_str: str) -> list:
"""
Parse RUN_ID parameter. Supports single ID (e.g., "500") or range (e.g., "500-511").
Returns a list of integers.
"""
if '-' in run_id_str:
start, end = map(int, run_id_str.split('-'))
return list(range(start, end + 1))
else:
return [int(run_id_str)]
def setup_output_directories(base_dir: Path, run_ids: list) -> dict:
"""
Set up output directories based on RUN_ID configuration.
Returns a dictionary with output paths for different file types.
"""
if len(run_ids) == 1:
# Single RUN_ID: fit_500
output_base = base_dir / f"fit_{run_ids[0]}"
else:
# Multiple RUN_IDs: fit_500_511
output_base = base_dir / f"fit_{run_ids[0]}_{run_ids[-1]}"
# Create subdirectories
subdirs = {
'plot': output_base / 'plot',
'csv': output_base / 'csv',
'json': output_base / 'json',
'html': output_base / 'html'
}
for subdir in subdirs.values():
subdir.mkdir(parents=True, exist_ok=True)
return {
'base': output_base,
'plot': subdirs['plot'],
'csv': subdirs['csv'],
'json': subdirs['json'],
'html': subdirs['html']
}
# --- 1. SQUID Analyzer Class ---
class SQUIDAnalyzer:
"""
Encapsulates the physical models and fitting procedures for SQUID CPR analysis.
"""
def __init__(self):
self.PHI0 = sc.h / (2 * sc.e)
self.scaling = {
'current_factor': 1.0, 'field_factor': 1.0, 'area_factor': 1e12,
'current_unit': 'μA', 'field_unit': 'μT', 'area_unit': 'μm²',
'original_current_unit': 'μA', 'original_field_unit': 'μT', 'original_area_unit': 'm²'
}
self.results = {} # Store fitting results
self.detrend_info = {} # Store detrend information
# --- Physical Models ---
@staticmethod
def _cpr_single_junction(phi: np.ndarray, Ic: float, T: float) -> np.ndarray:
"""Current-phase relation for a single Josephson junction."""
denominator = np.sqrt(1 - T * np.sin(phi / 2)**2)
return Ic * np.sin(phi) / np.where(denominator < 1e-10, 1e-10, denominator)
def _flux_phase(self, B_centered_uT: np.ndarray, B_0_uT: float, A_eff_um2: float) -> np.ndarray:
"""Calculates the magnetic flux phase."""
B_T = (B_centered_uT - B_0_uT) * 1e-6
A_eff_m2 = A_eff_um2 / self.scaling['area_factor']
return 2 * np.pi * A_eff_m2 * B_T / self.PHI0
def pre_fit_model(self, B_centered_uT, Ic0, r, A_eff_um2, B_0_uT, Ic1, **kwargs):
"""Simple sine model: Ic = Ic0 + r * φ + Ic1 * sin(φ) where φ = 2π * A_eff * (B - B_0) / PHI0."""
flux_phase = self._flux_phase(B_centered_uT, B_0_uT, A_eff_um2)
return Ic0 + r * flux_phase + Ic1 * np.sin(flux_phase)
def single_junction_model(self, B_centered_uT, Ic0, r, A_eff_um2, B_0_uT, Ic1, **kwargs):
"""Simple sine model: Ic = Ic0 + r * φ + Ic1 * sin(φ) (same as pre_fit_model)."""
flux_phase = self._flux_phase(B_centered_uT, B_0_uT, A_eff_um2)
return Ic0 + r * flux_phase + Ic1 * np.sin(flux_phase)
def single_T_model(self, B_centered_uT, Ic0, r, A_eff_um2, B_0_uT, Ic1, **kwargs):
"""Simple sine model: Ic = Ic0 + r * φ + Ic1 * sin(φ) (same as pre_fit_model)."""
flux_phase = self._flux_phase(B_centered_uT, B_0_uT, A_eff_um2)
return Ic0 + r * flux_phase + Ic1 * np.sin(flux_phase)
def dual_T_model(self, B_centered_uT, Ic0, r, A_eff_um2, B_0_uT, Ic1, **kwargs):
"""Simple sine model: Ic = Ic0 + r * φ + Ic1 * sin(φ) (same as pre_fit_model)."""
flux_phase = self._flux_phase(B_centered_uT, B_0_uT, A_eff_um2)
return Ic0 + r * flux_phase + Ic1 * np.sin(flux_phase)
# --- JAX methods removed ---
# JAX-compatible methods have been removed since MCMC functionality was disabled
@staticmethod
def _set_param_bounds(params, name, center_val, perc_bounds):
"""Helper to set parameter bounds based on a center value and percentage."""
delta = abs(center_val * perc_bounds)
params[name].set(min=center_val - delta, max=center_val + delta)
@staticmethod
def _set_ic_param_bounds(params, name, center_val, current_type, branch):
"""
Set bounds for Ic parameters based on current_type to enforce physical constraints.
For Ic+ current_type: min=0 (positive currents)
For Ic- current_type: max=0 (negative currents)
For Ic+ w/ Ic- current_type: branch-specific bounds (pos uses Ic+ rules, neg uses Ic- rules)
For mixed types: use percentage-based bounds
"""
if current_type == "Ic+":
# Positive currents only
params[name].set(min=0 + 1e-9, max=center_val * 2.0)
elif current_type == "Ic-":
# Negative currents only
params[name].set(min=center_val * 2.0, max=0 - 1e-9)
elif current_type == "Ic+ w/ Ic-":
# Branch-specific bounds for mixed current type
if branch == 'pos':
# Positive branch uses Ic+ rules
params[name].set(min=0 + 1e-9, max=center_val * 2.0)
elif branch == 'neg':
# Negative branch uses Ic- rules
params[name].set(min=center_val * 2.0, max=0 - 1e-9)
else:
# Fallback to percentage bounds
delta = abs(center_val * 0.5)
params[name].set(min=center_val - delta + 1e-9, max=center_val + delta - 1e-9)
else:
# Mixed or unknown type - use percentage bounds
delta = abs(center_val * 0.5)
params[name].set(min=center_val - delta + 1e-9, max=center_val + delta - 1e-9)
def reconstruct_original_data_and_fit(self, x_data: np.ndarray, y_data_detrended: np.ndarray,
x_fine: np.ndarray, branch: str, fit_stage: str):
"""
Reconstruct original data and fit curves when detrend was applied.
Parameters:
- x_data: B field coordinates (μT)
- y_data_detrended: Current data after detrend was applied
- x_fine: Fine B field array for smooth curve plotting
- branch: Branch name ('pos' or 'neg')
- fit_stage: Fitting stage ('pre_fit', 'single_T', 'dual_T')
Returns:
- x_plot: X coordinates for plotting
- y_plot: Y data with trend added back for plotting
- fit_curve: Fit curve with trend added back
"""
if not hasattr(self, 'detrend_info') or not self.detrend_info.get('detrend_applied', False):
# No detrend was applied, return data as is
# Need to get fit curve from results
from typing import Dict, Any
if hasattr(self, 'results'):
fit_result = self.results.get(f'{fit_stage}_{branch}', None)
if fit_result is not None:
if fit_stage == 'pre_fit':
fit_curve = self.pre_fit_model(x_fine, **fit_result.params.valuesdict())
elif fit_stage == 'single_T':
fit_curve = self.single_T_model(x_fine, **fit_result.params.valuesdict())
elif fit_stage == 'dual_T':
fit_curve = self.dual_T_model(x_fine, **fit_result.params.valuesdict())
else:
fit_curve = np.zeros_like(x_fine)
else:
fit_curve = np.zeros_like(x_fine)
else:
fit_curve = np.zeros_like(x_fine)
return x_data, y_data_detrended, fit_curve
# Detrend was applied, reconstruct original data
if branch not in self.detrend_info:
# No detrend info for this branch
return x_data, y_data_detrended, np.zeros_like(x_fine)
trend_slope = self.detrend_info[branch]['slope']
trend_intercept = self.detrend_info[branch]['intercept']
# Reconstruct original data by adding trend back
y_original = y_data_detrended + trend_slope * x_data + trend_intercept
# Get fit curve on detrended data
if hasattr(self, 'results'):
fit_result = self.results.get(f'{fit_stage}_{branch}', None)
if fit_result is not None:
if fit_stage == 'pre_fit':
fit_curve_detrended = self.pre_fit_model(x_fine, **fit_result.params.valuesdict())
elif fit_stage == 'single_T':
fit_curve_detrended = self.single_T_model(x_fine, **fit_result.params.valuesdict())
elif fit_stage == 'dual_T':
fit_curve_detrended = self.dual_T_model(x_fine, **fit_result.params.valuesdict())
else:
fit_curve_detrended = np.zeros_like(x_fine)
# Add trend back to fit curve for visualization
fit_curve_original = fit_curve_detrended + trend_slope * x_fine + trend_intercept
else:
fit_curve_original = np.zeros_like(x_fine)
else:
fit_curve_original = np.zeros_like(x_fine)
return x_data, y_original, fit_curve_original
# --- Fitting Execution ---
def _run_fit(self, model_func, params, x_data, y_data, method='least_squares', fit_kws=None):
"""
Generic fitting function using lmfit.Model.
Uses 'soft_l1' loss for robustness against outliers by default when using least_squares.
"""
model = Model(model_func, independent_vars=['B_centered_uT'])
if fit_kws is None:
fit_kws = {}
# Set default loss function for least-squares methods
if 'loss' not in fit_kws and method == 'least_squares':
fit_kws['loss'] = 'soft_l1'
result = model.fit(y_data, params, B_centered_uT=x_data, method=method, fit_kws=fit_kws)
return result
def _run_robust_fit_stage2(self, pre_fit_vals: Parameters, x_clean: np.ndarray, y_clean: np.ndarray, branch: str, current_type: str) -> ModelResult:
"""
Performs a robust fit for Stage 2 by trying multiple initial values and fitting methods.
Now fits for the ratio of Ic2/Ic1.
Uses joblib for parallel processing.
"""
print("\n[Stage 2] Starting robust fit for Single-Transparency Model...")
print(" Model: Ic = Ic0 + r * φ + Ic1 * sin(φ)")
print(" where φ = 2π * A_eff * (B - B_0) / PHI0")
# Check if Ic1 is effectively zero (no modulation detected)
if abs(pre_fit_vals['Ic1'].value) < 1e-10:
print(f" Warning: No modulation detected in {branch} branch (Ic1 ≈ 0). Skipping Stage 2 fit.")
return None
methods_to_try = ['least_squares', 'nelder', 'lbfgsb']
t1_guesses = [0.5]
phi_21_guesses = np.linspace(-np.pi, np.pi, 24, endpoint=False).tolist()
best_result = None
min_chi_sq = np.inf
# --- Base parameters ---
base_params = Parameters()
# Freeze parameters from Stage 1
base_params.add('Ic0', value=pre_fit_vals['Ic0'].value, vary=False)
base_params.add('r', value=pre_fit_vals['r'].value, vary=False)
base_params.add('B_0_uT', value=pre_fit_vals['B_0_uT'].value, vary=False)
base_params.add('A_eff_um2', value=pre_fit_vals['A_eff_um2'].value, vary=False)
# Sine parameter from Stage 1 (will be varied in the final refinement step)
base_params.add('Ic1', value=pre_fit_vals['Ic1'].value, vary=False)
# ---
search_space = list(itertools.product(methods_to_try, t1_guesses, phi_21_guesses))
print(f"Starting parallel grid search over {len(search_space)} combinations for {branch} branch...")
def fit_worker(method, t1_init, phi_21_init):
current_params = base_params.copy()
current_params.add('T1', value=t1_init, min=0.25, max=0.75)
current_params.add('phi_21', value=phi_21_init, min=-np.pi, max=np.pi)
# Skip additional parameters since we now use simplified CPR model
# All stages use the same basic model: Ic = Ic0 + r * CPR
try:
# First pass with frozen global parameters
result = self._run_fit(self.single_T_model, current_params, x_clean, y_clean, method=method)
if result.success:
return result
except Exception:
return None
return None
results = Parallel(n_jobs=-1)(delayed(fit_worker)(m, t1, p21) for m, t1, p21 in track(search_space, description="Fitting..."))
# Filter out None results and find the best one
successful_results = [res for res in results if res is not None]
if not successful_results:
print(f" Warning: Stage 2 robust fitting failed to find any valid result for {branch} branch.")
return None
best_result = min(successful_results, key=lambda r: r.chisqr)
min_chi_sq = best_result.chisqr
print("\nRobust fit for Stage 2 complete.")
if best_result is None:
print(f" Warning: Stage 2 robust fitting failed to find any valid result for {branch} branch.")
return None
# --- Second pass: Refine the best fit by unfreezing global parameters ---
print("Refining best Stage 2 fit with global parameters (A_eff, B_0, Ic0) varying...")
final_params = best_result.params.copy()
# Unfreeze and set bounds for global parameters
final_params['Ic0'].set(vary=True)
self._set_ic_param_bounds(final_params, 'Ic0', pre_fit_vals['Ic0'].value, current_type, branch)
# Unfreeze r parameter
final_params['r'].set(vary=True, min=-10000, max=10000)
final_params['B_0_uT'].set(vary=True)
self._set_param_bounds(final_params, 'B_0_uT', pre_fit_vals['B_0_uT'].value, 0.05)
final_params['A_eff_um2'].set(vary=True)
self._set_param_bounds(final_params, 'A_eff_um2', pre_fit_vals['A_eff_um2'].value, 0.05)
# Also unfreeze Ic1 for final refinement with current_type-aware bounds
final_params['Ic1'].set(vary=True)
self._set_ic_param_bounds(final_params, 'Ic1', pre_fit_vals['Ic1'].value, current_type, branch)
final_result = self._run_fit(self.single_T_model, final_params, x_clean, y_clean, method='least_squares')
return final_result
# --- MCMC functionality removed ---
# _run_blackjax_and_bands method has been removed
# --- MCMC functionality removed ---
# _run_emcee_and_bands method has been removed
# --- MCMC functionality removed ---
# _run_emcee_and_bands method has been removed
def get_junction_components(self, fit_params: Dict[str, float], x_fine: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
Extract individual junction currents from dual-T model fit parameters.
Returns (I1, I2) where I1 and I2 are the currents through each junction.
"""
# Calculate flux phase
flux_phase = self._flux_phase(x_fine, fit_params['B_0_uT'], fit_params['A_eff_um2'])
# Calculate sine component (simple model)
I_sine = fit_params['Ic1'] * np.sin(flux_phase)
# Return same component twice for compatibility (all stages use same model now)
return I_sine, I_sine
def detect_linear_trend(self, branch_data, field_data):
"""檢測數據中的線性趨勢強度"""
if len(branch_data) < 10 or len(field_data) < 10:
return 0, 0, False
# 計算線性擬合
valid_mask = ~np.isnan(branch_data) & ~np.isnan(field_data)
if np.sum(valid_mask) < 10:
return 0, 0, False
slope, intercept = np.polyfit(field_data[valid_mask], branch_data[valid_mask], 1)
# 計算線性趨勢的強度 vs SQUID 振蕩振幅
data_range = np.ptp(branch_data[valid_mask])
oscillation_amplitude = np.std(branch_data[valid_mask])
linear_trend_strength = abs(slope) * np.ptp(field_data[valid_mask])
# 判斷是否需要 detrend(線性趨勢 > 振蕩振幅的 30%)
needs_detrend = linear_trend_strength > 0.3 * oscillation_amplitude
return slope, linear_trend_strength, needs_detrend
def analyze_data_quality(self, ds_cpr):
"""分析數據質量並提供建議"""
recommendations = []
# 檢查 positive branch
if 'crit_current_pos' in ds_cpr:
y_pos = ds_cpr['crit_current_pos'].values
x_data = ds_cpr.coords['B_y_centered_μT'].values
valid_mask = np.isfinite(y_pos) & np.isfinite(x_data)
if np.sum(valid_mask) > 10:
slope_pos, trend_strength_pos, needs_detrend_pos = self.detect_linear_trend(
y_pos[valid_mask], x_data[valid_mask]
)
if needs_detrend_pos:
recommendations.append({
'branch': 'positive',
'slope': slope_pos,
'trend_strength': trend_strength_pos,
'message': f'檢測到強線性趨勢 (斜率: {slope_pos:.3f} μA/μT),建議使用 --use-detrend 選項獲得更好的擬合結果'
})
# 檢查 negative branch
if 'crit_current_neg' in ds_cpr:
y_neg = ds_cpr['crit_current_neg'].values
x_data = ds_cpr.coords['B_y_centered_μT'].values
valid_mask = np.isfinite(y_neg) & np.isfinite(x_data)
if np.sum(valid_mask) > 10:
slope_neg, trend_strength_neg, needs_detrend_neg = self.detect_linear_trend(
y_neg[valid_mask], x_data[valid_mask]
)
if needs_detrend_neg:
recommendations.append({
'branch': 'negative',
'slope': slope_neg,
'trend_strength': trend_strength_neg,
'message': f'檢測到強線性趨勢 (斜率: {slope_neg:.3f} μA/μT),建議使用 --use-detrend 選項獲得更好的擬合結果'
})
return recommendations
def print_data_quality_analysis(self, recommendations):
"""輸出數據質量分析結果"""
if recommendations:
print("\n" + "="*60)
print("📊 數據質量分析 & 建議")
print("="*60)
for rec in recommendations:
print(f"⚠️ {rec['branch'].upper()} BRANCH: {rec['message']}")
print("\n💡 使用 detrend 的優勢:")
print(" • 移除測量系統的線性漂移")
print(" • 突出 SQUID 干涉振蕩信號")
print(" • 提高擬合穩定性和物理合理性")
print(" • 減少參數間的相互干擾")
print("="*60 + "\n")
else:
print("✅ 數據質量良好,無明顯線性趨勢\n")
def estimate_oscillation_parameters(self, branch_data, field_data):
"""智能估計振蕩參數,用於改善非 detrend 模式的初始化"""
if len(branch_data) < 20 or len(field_data) < 20:
return None
valid_mask = ~np.isnan(branch_data) & ~np.isnan(field_data)
if np.sum(valid_mask) < 20:
return None
y_clean = branch_data[valid_mask]
x_clean = field_data[valid_mask]
# 臨時線性去趨勢用於振蕩參數估計
from scipy.signal import detrend
y_detrended = detrend(y_clean)
# 估計振蕩振幅 (使用標準差的 2.5 倍作為峰峰值估計)
oscillation_amplitude = np.std(y_detrended) * 2.5
# 使用 FFT 估計主頻率和相位
try:
fft_vals = np.fft.fft(y_detrended)
freqs = np.fft.fftfreq(len(y_detrended), np.mean(np.diff(x_clean)))
# 找到主頻率 (忽略 DC 成分)
valid_freq_mask = freqs > 0
if np.any(valid_freq_mask):
main_freq_idx = np.argmax(np.abs(fft_vals[valid_freq_mask]))
main_freq = freqs[valid_freq_mask][main_freq_idx]
# 從主頻率估計 A_eff (基於 φ = 2π * A_eff * (B - B_0) / PHI0)
PHI0 = sc.h / (2 * sc.e) * 1e6 # Flux quantum in μT⋅μm²
estimated_A_eff = abs(main_freq) * PHI0 / (2 * np.pi) if main_freq != 0 else 350
estimated_A_eff = np.clip(estimated_A_eff, 250, 500) # 物理合理範圍
else:
estimated_A_eff = 350 # 默認值
except:
estimated_A_eff = 350 # 發生錯誤時的默認值
return {
'ic1_estimate': oscillation_amplitude,
'a_eff_estimate': estimated_A_eff,
'data_std': np.std(y_detrended)
}
def analyze(self, ds_cpr: xr.Dataset, output_dir: Path, current_type: str = "Ic+ w/ Ic-") -> Dict[str, Any]:
"""
Performs the full staged fitting procedure for both positive and negative branches.
current_type: "Ic+", "Ic+ w/ Ic-", or "Ic- w/ Ir+"
"""
results = {}
# 1. 分析數據質量
quality_recommendations = self.analyze_data_quality(ds_cpr)
self.print_data_quality_analysis(quality_recommendations)
# Determine which branches to process based on current_type
if current_type == "Ic+":
branches_to_process = ['pos']
elif current_type == "Ic+ w/ Ic-":
branches_to_process = ['pos', 'neg']
elif current_type == "Ic- w/ Ir+":
branches_to_process = ['neg'] # Assuming neg corresponds to Ic-
else:
branches_to_process = ['pos', 'neg'] # Default fallback
for branch in branches_to_process:
print(f"\n--- Analyzing Branch: Ic{'+' if branch == 'pos' else '-'} ---")
y_data = ds_cpr[f'crit_current_{branch}'].values
x_data = ds_cpr.coords['B_y_centered_μT'].values
mask = np.isfinite(y_data) & np.isfinite(x_data)
x_clean, y_clean = x_data[mask], y_data[mask]
# Check if we have any valid data points
if len(x_clean) == 0:
print(f" Warning: No valid data points found for {branch} branch. Skipping analysis.")
results[f'pre_fit_{branch}'] = None
results[f'single_junction_fit_{branch}'] = None
results[f'single_T_fit_{branch}'] = None
results[f'dual_T_fit_{branch}'] = None
continue
# Stage 1: Pre-fitting with simple sine model
print("\n[Stage 1] Pre-fitting with simple sine model...")
print(" Model: Ic = Ic0 + r * φ + Ic1 * sin(φ)")
print(" where φ = 2π * A_eff * (B - B_0) / PHI0")
# 智能參數估計 (特別針對非 detrend 模式的改善)
data_range = float(np.max(y_clean) - np.min(y_clean))
is_detrended = data_range < 20.0
has_strong_trend = len(quality_recommendations) > 0
smart_params = None
if not is_detrended and has_strong_trend:
# 對原始數據使用智能參數估計
smart_params = self.estimate_oscillation_parameters(y_clean, x_clean)
if smart_params:
print(f"🧠 智能參數估計: Ic1≈{smart_params['ic1_estimate']:.2f}μA, A_eff≈{smart_params['a_eff_estimate']:.0f}μm²")
pre_fit_params = Parameters()
mean_ic, std_ic = np.mean(y_clean), np.std(y_clean)
# Set Ic0 with current_type-aware bounds
pre_fit_params.add('Ic0', value=mean_ic)
self._set_ic_param_bounds(pre_fit_params, 'Ic0', mean_ic, current_type, branch)
# Add r parameter (CPR scaling factor) - improved initialization
# Estimate linear trend from data
if len(x_clean) > 2:
linear_slope, _ = np.polyfit(x_clean, y_clean, 1)
r_initial = linear_slope * 100 # Scale factor for μT to μA conversion
r_initial = np.clip(r_initial, -1.0, 1.0) # Keep within reasonable bounds
else:
r_initial = 0.1 # Conservative default
pre_fit_params.add('r', value=r_initial, min=-2.0, max=2.0) # 允許更大的線性響應範圍
# Set Ic1 with adaptive estimation based on data characteristics
std_ic = float(np.std(y_clean)) # 數據標準差(總是正值)
peak_to_peak = float(np.max(y_clean) - np.min(y_clean)) # 峰谷差值
# 根据分支类型和数据特征设定 Ic1 参数
if (current_type == 'Ic+') or (current_type == 'Ic+ w/ Ic-' and branch == 'pos'):
if is_detrended:
# 去趨勢數據:使用更大的比例
ic1_value = 0.6 * peak_to_peak
ic1_min = 0.2 * peak_to_peak
ic1_max = 1.2 * peak_to_peak
else:
# 原始數據:使用智能估計或保守設定
if smart_params and smart_params['ic1_estimate'] > 0:
# 使用智能估計,設定合理範圍防止過度壓縮
ic1_value = smart_params['ic1_estimate']
ic1_min = smart_params['ic1_estimate'] * 0.7 # 防止被壓縮到過小
ic1_max = smart_params['ic1_estimate'] * 1.5
print(f" 📌 使用智能 Ic1 估計: {ic1_value:.2f}μA (範圍: {ic1_min:.2f}-{ic1_max:.2f})")
else:
# 備用設定:更積極的初始值
ic1_value = max(0.15 * peak_to_peak, 2.5 * std_ic) # 更大的初始估計
ic1_min = max(0.05 * peak_to_peak, 0.8 * std_ic) # 設定合理下界
ic1_max = 0.4 * peak_to_peak
print(f" 📌 使用備用 Ic1 設定: {ic1_value:.2f}μA (範圍: {ic1_min:.2f}-{ic1_max:.2f})")
elif (current_type == 'Ic-') or (current_type == 'Ic+ w/ Ic-' and branch == 'neg'):
# 負分支:使用負值
ic1_value = -2.0 * std_ic
ic1_min = -5.0 * std_ic
ic1_max = -0.5 * std_ic
else:
# 備用邏輯
ic1_value = 2.0 * std_ic
ic1_min = 0.5 * std_ic
ic1_max = 5.0 * std_ic
pre_fit_params.add('Ic1', value=ic1_value, min=ic1_min, max=ic1_max)
# Physical parameters for magnetic field to phase conversion
# 根據數據特徵和智能估計調整 A_eff 參數
if is_detrended:
# 去趨勢數據:使用優化過的設置
a_eff_value, a_eff_min, a_eff_max = 330, 300, 400
else:
# 原始數據:使用智能估計或合理設定
if smart_params and 250 <= smart_params['a_eff_estimate'] <= 500:
# 使用智能估計
a_eff_value = smart_params['a_eff_estimate']
a_eff_min = max(280, a_eff_value - 50)
a_eff_max = min(450, a_eff_value + 50)
print(f" 📌 使用智能 A_eff 估計: {a_eff_value:.0f}μm² (範圍: {a_eff_min:.0f}-{a_eff_max:.0f})")
else:
# 備用設定:基於成功 detrend 結果的經驗值
a_eff_value, a_eff_min, a_eff_max = 340, 300, 420
print(f" 📌 使用經驗 A_eff 設定: {a_eff_value:.0f}μm² (範圍: {a_eff_min:.0f}-{a_eff_max:.0f})")
pre_fit_params.add('A_eff_um2', value=a_eff_value, min=a_eff_min, max=a_eff_max)
# B_0 參數設置,根據數據特徵和物理合理性調整
b_range = float(np.max(x_clean) - np.min(x_clean))
if is_detrended:
# 去趨勢數據:使用用戶判斷的 -1μT 附近
b0_initial = -1.0
b0_range = min(b_range * 0.15, 8.0)
b0_min, b0_max = b0_initial - b0_range, b0_initial + b0_range
else:
# 原始數據:基於成功 detrend 結果,使用更聚焦的範圍
if has_strong_trend:
# 有強線性趨勢時,使用接近 detrend 成功結果的設定
b0_initial = -1.2 # 稍微偏移以適應原始數據
b0_min, b0_max = -3.5, 0.5 # 更聚焦的範圍,基於 detrend 結果 -0.88μT
print(f" 📌 針對強線性趨勢優化 B_0: {b0_initial:.1f}μT (範圍: {b0_min:.1f}-{b0_max:.1f})")
else:
# 無強線性趨勢時使用標準設定
b0_initial = -1.0
b0_range = min(b_range * 0.2, 12.0)
b0_min, b0_max = -b0_range, b0_range
pre_fit_params.add('B_0_uT', value=b0_initial, min=b0_min, max=b0_max)
pre_fit_result = self._run_fit(self.pre_fit_model, pre_fit_params, x_clean, y_clean)
pre_fit_vals = pre_fit_result.params
print("Pre-fit results:")
report_fit(pre_fit_result)
results[f'pre_fit_{branch}'] = pre_fit_result
# Stage 1.2: Single Harmonic Transparency Model Fit
# Check if Ic1 is effectively zero (no modulation detected)
if abs(pre_fit_vals['Ic1'].value) < 1e-10:
print(f" Warning: No modulation detected in {branch} branch (Ic1 ≈ 0). Skipping single junction fit.")
results[f'single_junction_fit_{branch}'] = None
results[f'single_T_fit_{branch}'] = None
results[f'dual_T_fit_{branch}'] = None
# Skip to next stage or return early
continue
single_junction_params = Parameters()
# Use pre-fit results as initial values with current_type-aware bounds
single_junction_params.add('Ic0', value=pre_fit_vals['Ic0'].value)
self._set_ic_param_bounds(single_junction_params, 'Ic0', pre_fit_vals['Ic0'].value, current_type, branch)
# Add r parameter from pre-fit results (CPR scaling factor)
single_junction_params.add('r', value=pre_fit_vals['r'].value, min=-2.0, max=2.0)
# Physical parameters for magnetic field to phase conversion
# 根據 pre-fit 結果和數據特徵設置範圍
a_eff_value = pre_fit_vals['A_eff_um2'].value
if a_eff_value < 350: # 去趨勢數據的情況
single_junction_params.add('A_eff_um2', value=a_eff_value, min=300, max=450)
else: # 原始數據的情況
single_junction_params.add('A_eff_um2', value=a_eff_value, min=300, max=500)
# 動態設置 B_0 範圍基於數據特徵
b_range = float(np.max(x_clean) - np.min(x_clean))
b0_range = min(b_range * 0.2, 10.0)
single_junction_params.add('B_0_uT', value=pre_fit_vals['B_0_uT'].value, min=-b0_range, max=b0_range)
# Sine modulation parameter from pre-fit results
single_junction_params.add('Ic1', value=pre_fit_vals['Ic1'].value)
self._set_ic_param_bounds(single_junction_params, 'Ic1', pre_fit_vals['Ic1'].value, current_type, branch)
single_junction_result = self._run_fit(self.single_junction_model, single_junction_params, x_clean, y_clean)
print("Single junction fit results:")
report_fit(single_junction_result)
results[f'single_junction_fit_{branch}'] = single_junction_result
# after pre_fit_result
x_fine = np.linspace(x_clean.min(), x_clean.max(), 600)
# MCMC functionality removed - skipping MCMC sampling
# Stage 2: Single-T Model Robust Fit
single_T_result = self._run_robust_fit_stage2(pre_fit_vals, x_clean, y_clean, branch, current_type)
if single_T_result is None:
print(f" Warning: Single-T fit failed for {branch} branch. Skipping dual-T fit.")
results[f'single_T_fit_{branch}'] = None
results[f'dual_T_fit_{branch}'] = None
continue
print("\nBest Single-T fit results from robust search:")
report_fit(single_T_result)
results[f'single_T_fit_{branch}'] = single_T_result
# MCMC functionality removed - skipping MCMC sampling
# Stage 3: Dual-T Model Fit
print("\n[Stage 3] Fitting with Dual-Transparency Model...")
print(" Model: Ic = Ic0 + r * φ + Ic1 * sin(φ)")
if single_T_result is None:
print(f" Warning: Single-T fit failed for {branch} branch. Skipping dual-T fit.")
results[f'dual_T_fit_{branch}'] = None
continue
# Temporarily skip Stage 3 due to parameter compatibility issues
print(" Warning: Stage 3 temporarily disabled for simplified CPR model.")
results[f'dual_T_fit_{branch}'] = single_T_result # Use Stage 2 result as fallback
continue
# --- First pass: Freeze global parameters to stabilize fit ---
print(" [Stage 3a] Freezing global parameters to fit T1, T2, Ic ratios...")
dual_T_params_pass1 = Parameters()
p2_vals = single_T_result.params
# Freeze global parameters from Stage 2 results
dual_T_params_pass1.add('Ic0', value=p2_vals['Ic0'].value, vary=False)
dual_T_params_pass1.add('r', value=p2_vals['r'].value, vary=False)
dual_T_params_pass1.add('B_0_uT', value=p2_vals['B_0_uT'].value, vary=False)
dual_T_params_pass1.add('A_eff_um2', value=p2_vals['A_eff_um2'].value, vary=False)
# Freeze CPR parameters from Stage 2 results
dual_T_params_pass1.add('Ic_cpr', value=p2_vals['Ic_cpr'].value, vary=False)
dual_T_params_pass1.add('T_cpr', value=p2_vals['T_cpr'].value, vary=False)
result_pass1 = self._run_fit(self.dual_T_model, dual_T_params_pass1, x_clean, y_clean)
print(" Fit results after Pass 1 (frozen globals):")
report_fit(result_pass1)
# --- Second pass: Unfreeze global parameters for final refinement ---
print("\n [Stage 3b] Unfreezing global parameters for final refinement...")
dual_T_params_pass2 = result_pass1.params.copy()
# Unfreeze and set bounds for global parameters
dual_T_params_pass2['Ic0'].set(vary=True)
self._set_ic_param_bounds(dual_T_params_pass2, 'Ic0', p2_vals['Ic0'].value, current_type, branch)
# Unfreeze r parameter (CPR scaling factor)
dual_T_params_pass2['r'].set(vary=True, min=-10.0, max=10.0)
dual_T_params_pass2['B_0_uT'].set(vary=True)
self._set_param_bounds(dual_T_params_pass2, 'B_0_uT', p2_vals['B_0_uT'].value, 0.1)
dual_T_params_pass2['A_eff_um2'].set(vary=True)
self._set_param_bounds(dual_T_params_pass2, 'A_eff_um2', p2_vals['A_eff_um2'].value, 0.1)
# Unfreeze CPR parameters
dual_T_params_pass2['Ic_cpr'].set(vary=True)
self._set_ic_param_bounds(dual_T_params_pass2, 'Ic_cpr', p2_vals['Ic_cpr'].value, current_type, branch)
dual_T_params_pass2['T_cpr'].set(vary=True, min=0.1, max=0.9)
dual_T_result = self._run_fit(self.dual_T_model, dual_T_params_pass2, x_clean, y_clean)
print("\nFinal Dual-T fit results after refinement:")
report_fit(dual_T_result)
results[f'dual_T_fit_{branch}'] = dual_T_result
# MCMC functionality removed - skipping MCMC sampling and benchmarks
return results
# --- 2. Helper Functions ---
def load_squid_analyzer(script_path: str) -> type:
"""Loads the SQUIDAnalyzer class. In this standalone script, it just returns the class."""
return SQUIDAnalyzer
def df_print_sci(df: pd.DataFrame, digits: int = 3):
"""Prints a DataFrame with scientific notation."""
print(df.to_string(
formatters={
col: (lambda x: f"{x:.{digits}e}")
for col, dtype in df.dtypes.items()
if pd.api.types.is_float_dtype(dtype)
}
))
def get_branches_for_current_type(current_type: str) -> List[str]:
"""根據 current_type 確定需要處理的分支"""
branch_map = {
"Ic+": ['pos'],
"Ic+ w/ Ic-": ['pos', 'neg'],
"Ic- w/ Ir+": ['neg'],
"Ic-": ['neg']
}
return branch_map.get(current_type, ['pos', 'neg'])
def should_extract_branch(branch: str, current_type: str) -> bool:
"""判斷是否應該提取特定分支的資料"""
required_branches = get_branches_for_current_type(current_type)
return branch in required_branches
def prepare_cpr_data_from_qcodes(ds: DataSet, df_raw: pd.DataFrame, current_type: str = "Ic+ w/ Ic-", use_detrend: bool = False) -> Tuple[xr.Dataset, pd.DataFrame]:
"""Extracts CPR data (Ic vs. B) from raw IV curve data with current_type awareness."""
print(f"\nExtracting CPR data for {current_type}...")
# 根據 current_type 決定要提取的分支
branches_to_extract = get_branches_for_current_type(current_type)
# 初始化對應的分支列表
crit_currents = {}
for branch in ['pos', 'neg']:
if should_extract_branch(branch, current_type):
crit_currents[f'crit_current_{branch}'] = []
else:
# 對於不需要的分支,建立空列表以維持資料結構一致性
crit_currents[f'crit_current_{branch}'] = []
unique_B = df_raw['y_field_centered_µT'].unique()
for B in unique_B:
mask = (df_raw['y_field_centered_µT'] == B)
i_vals = df_raw.loc[mask, 'appl_current_µA'].values
v_vals = df_raw.loc[mask, 'meas_voltage_µV'].values
sort_idx = np.argsort(i_vals)
i_sorted, v_sorted = i_vals[sort_idx], v_vals[sort_idx]
if len(i_sorted) > 1:
di = np.diff(i_sorted)
dvdi = np.abs(np.diff(v_sorted) / np.where(di == 0, 1e-9, di))
i_mid = (i_sorted[:-1] + i_sorted[1:]) / 2
# 處理所有分支,但只對需要提取的分支進行實際計算
for branch in ['pos', 'neg']:
if should_extract_branch(branch, current_type):
if branch == 'pos':
pos_mask = i_mid > 0
if np.any(pos_mask):
pos_peaks, _ = find_peaks(dvdi[pos_mask], height=np.max(dvdi[pos_mask]) * 0.5)
if len(pos_peaks) > 0:
crit_currents['crit_current_pos'].append(i_mid[pos_mask][pos_peaks[0]])
else:
# 如果沒有找到峰值,嘗試降低閾值
pos_peaks_relaxed, _ = find_peaks(dvdi[pos_mask], height=np.max(dvdi[pos_mask]) * 0.3)
if len(pos_peaks_relaxed) > 0:
crit_currents['crit_current_pos'].append(i_mid[pos_mask][pos_peaks_relaxed[0]])
print(f" Debug: Found peak with relaxed threshold at B={B:.1f}µT, Ic={i_mid[pos_mask][pos_peaks_relaxed[0]]:.3f}µA")
else:
crit_currents['crit_current_pos'].append(np.nan)
print(f" Debug: No peaks found in positive branch at B={B:.1f}µT")
else:
crit_currents['crit_current_pos'].append(np.nan)
print(f" Debug: No positive current data at B={B:.1f}µT")
elif branch == 'neg':
neg_mask = i_mid < 0
if np.any(neg_mask):
neg_peaks, _ = find_peaks(dvdi[neg_mask], height=np.max(dvdi[neg_mask]) * 0.5)
crit_currents['crit_current_neg'].append(
i_mid[neg_mask][neg_peaks[-1]] if len(neg_peaks) > 0 else np.nan
)
else:
crit_currents['crit_current_neg'].append(np.nan)
else:
# 對於不需要提取的分支,加入 NaN 以維持陣列長度一致性
crit_currents[f'crit_current_{branch}'].append(np.nan)
else:
# 對於所有分支,加入 NaN(因為沒有足夠的資料點)
for branch in ['pos', 'neg']:
crit_currents[f'crit_current_{branch}'].append(np.nan)
# 建構 DataFrame,根據 current_type 決定如何處理 NaN 值
df_data = {'B_y_centered_μT': unique_B}
# 確保所有分支陣列長度一致,如果長度不一致則用 NaN 填充
max_length = len(unique_B)
for branch_key, values in crit_currents.items():
if len(values) < max_length:
# 用 NaN 填充到相同長度
values.extend([np.nan] * (max_length - len(values)))
elif len(values) > max_length:
# 如果長度超過,截斷到正確長度
values = values[:max_length]
df_data[branch_key] = values
# 建立初始 DataFrame
cpr_df_full = pd.DataFrame(df_data)
# 根據 current_type 決定如何過濾資料
if current_type == "Ic+":
# 只保留正分支有有效值的行
cpr_df = cpr_df_full.dropna(subset=['crit_current_pos']).sort_values('B_y_centered_μT')
elif current_type == "Ic-":
# 只保留負分支有有效值的行
cpr_df = cpr_df_full.dropna(subset=['crit_current_neg']).sort_values('B_y_centered_μT')
else:
# 雙分支型別:保留任一分支有有效值的行
cpr_df = cpr_df_full.dropna(how='all', subset=['crit_current_pos', 'crit_current_neg']).sort_values('B_y_centered_μT')
# Apply detrend if requested
detrend_info = {}
if use_detrend and len(cpr_df) > 2: # Need at least 3 points for detrend
print(f"Applying linear detrend to CPR data...")
# Store original data for comparison
original_pos = cpr_df['crit_current_pos'].copy() if 'crit_current_pos' in cpr_df.columns else None
original_neg = cpr_df['crit_current_neg'].copy() if 'crit_current_neg' in cpr_df.columns else None
# Apply detrend to each branch and save trend information
for branch in ['pos', 'neg']:
col_name = f'crit_current_{branch}'
if col_name in cpr_df.columns:
# Get valid (non-NaN) data points
valid_mask = cpr_df[col_name].notna()
if valid_mask.sum() > 2: # Need at least 3 valid points
valid_data = cpr_df.loc[valid_mask, col_name].values
valid_B = cpr_df.loc[valid_mask, 'B_y_centered_μT'].values
# Apply detrend and calculate the removed trend
detrended_data = detrend(valid_data, type='linear')
removed_trend = valid_data - detrended_data
# Fit a line to the removed trend to get slope and intercept
trend_slope, trend_intercept = np.polyfit(valid_B, removed_trend, 1)
# Store trend information
detrend_info[branch] = {
'slope': trend_slope,
'intercept': trend_intercept,
'original_data': original_pos if branch == 'pos' else original_neg,
'valid_mask': valid_mask.copy(),
'B_field': valid_B.copy()
}
# Update the DataFrame with detrended data
cpr_df.loc[valid_mask, col_name] = detrended_data
# Calculate and report detrend statistics
original_std = np.std(valid_data)
detrended_std = np.std(detrended_data)
trend_removed = original_std - detrended_std
print(f" {branch} branch: Original std = {original_std:.3f} μA, "
f"Detrended std = {detrended_std:.3f} μA, "
f"Trend removed = {trend_removed:.3f} μA")
print(f" Removed trend: slope = {trend_slope:.6f} μA/μT, intercept = {trend_intercept:.3f} μA")
else:
print(f" Warning: Not enough valid data points in {branch} branch for detrend")
# 建立 xarray Dataset
ds_cpr = xr.Dataset.from_dataframe(cpr_df.set_index('B_y_centered_μT'))
ds_cpr.attrs['run_id'] = ds.run_id
ds_cpr.attrs['current_type'] = current_type
ds_cpr.attrs['use_detrend'] = use_detrend
# Store detrend information if detrend was applied
if use_detrend and detrend_info:
ds_cpr.attrs['detrend_info'] = detrend_info
print(f"Detrend information stored for branches: {list(detrend_info.keys())}")
print(f"Extracted {len(cpr_df)} valid CPR data points for {current_type}")
print(f"Branches processed: {branches_to_extract}")
print(f"Data shape - B_field: {len(unique_B)}, Pos branch: {len(crit_currents['crit_current_pos'])}, Neg branch: {len(crit_currents['crit_current_neg'])}")