File size: 4,543 Bytes
12c1d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import argparse
import csv
import math
from pathlib import Path
import numpy as np


def read_probe_u(path: Path):
    rows = []
    with path.open() as f:
        for line in f:
            s = line.strip()
            if not s or s.startswith('#'):
                continue
            parts = s.split('(')
            try:
                t = float(parts[0].strip())
            except ValueError:
                continue
            ux = []
            uy = []
            for p in parts[1:]:
                vals = p.rstrip(')').strip().split()
                if len(vals) >= 2:
                    ux.append(float(vals[0]))
                    uy.append(float(vals[1]))
            if len(ux) >= 2:
                rows.append((t, ux, uy))
    if not rows:
        raise RuntimeError(f'no probe rows in {path}')
    t = np.array([r[0] for r in rows], dtype=float)
    ux = np.array([r[1] for r in rows], dtype=float)
    uy = np.array([r[2] for r in rows], dtype=float)
    return t, ux, uy


def classify_case(case: Path):
    probe_candidates = sorted(case.glob('postProcessing/wakeProbes/*/U'))
    if not probe_candidates:
        probe_candidates = sorted(case.glob('processor0/postProcessing/wakeProbes/*/U'))
    if not probe_candidates:
        return {'case': case.name, 'status': 'missing_probe'}
    t, ux_all, uy_all = read_probe_u(probe_candidates[0])
    if len(t) < 16:
        return {'case': case.name, 'status': 'too_few_points', 'n': len(t)}
    half = len(t) // 2
    # Probe 1 is report's primary classifier: x=8, y=2.
    probe_index = 1 if ux_all.shape[1] > 1 else 0
    t_tail = t[half:]
    ux = ux_all[half:, probe_index]
    coeff = np.polyfit(t_tail, ux, 1)
    detrended = ux - np.polyval(coeff, t_tail)
    sigma = float(np.std(detrended))
    dt = float(np.median(np.diff(t))) if len(t) > 1 else math.nan
    peak_st = math.nan
    peak_amp = 0.0
    sig = 0.0
    if len(detrended) > 8 and np.isfinite(dt) and dt > 0:
        fft = np.abs(np.fft.rfft(detrended))
        freqs = np.fft.rfftfreq(len(detrended), dt)
        band = (freqs >= 0.05) & (freqs <= 0.30)
        if np.any(band):
            band_fft = fft[band]
            band_freq = freqs[band]
            idx = int(np.argmax(band_fft))
            peak_amp = float(band_fft[idx] / len(detrended))
            peak_st = float(band_freq[idx])
            mean_amp = float(np.mean(band_fft) / len(detrended))
            sig = peak_amp / mean_amp if mean_amp > 0 else 0.0
    seg_n = 4
    seg_size = max(1, len(ux) // seg_n)
    seg_stds = []
    for s in range(seg_n):
        seg = ux[s*seg_size:(s+1)*seg_size]
        st = t_tail[s*seg_size:(s+1)*seg_size]
        if len(seg) < 3:
            seg_stds.append(float('nan'))
        else:
            c = np.polyfit(st, seg, 1)
            seg_stds.append(float(np.std(seg - np.polyval(c, st))))
    if sigma < 1e-6:
        regime = 'STEADY'
    elif peak_amp > 1e-3 and sig > 10:
        regime = 'PERIODIC'
    elif peak_amp > 1e-4 and sig > 5:
        regime = 'HOPF_NEAR_ONSET'
    elif np.isfinite(seg_stds[0]) and seg_stds[-1] > seg_stds[0] * 1.5:
        regime = 'GROWING_INSTABILITY'
    else:
        regime = 'STEADY_OR_TRANSITIONAL'
    last_time = float(t[-1])
    return {
        'case': case.name,
        'status': 'ok',
        'n': len(t),
        'last_probe_time': last_time,
        'ux_tail_mean': float(np.mean(ux)),
        'sigma_detrend': sigma,
        'peak_St': peak_st,
        'fft_significance': sig,
        'seg_std_0': seg_stds[0],
        'seg_std_3': seg_stds[-1],
        'regime': regime,
        'probe_file': str(probe_candidates[0]),
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('run_root', type=Path)
    args = ap.parse_args()
    cases = sorted([p for p in args.run_root.glob('Re*') if p.is_dir()], key=lambda p: float(p.name[2:]))
    rows = [classify_case(c) for c in cases]
    out = args.run_root / 'probe_regime_summary.csv'
    fields = ['case','status','n','last_probe_time','ux_tail_mean','sigma_detrend','peak_St','fft_significance','seg_std_0','seg_std_3','regime','probe_file']
    with out.open('w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)
    print(out)
    for r in rows:
        print(f"{r.get('case')}: {r.get('regime', r.get('status'))} sigma={r.get('sigma_detrend','NA')} St={r.get('peak_St','NA')} sig={r.get('fft_significance','NA')}")

if __name__ == '__main__':
    main()