-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotter.py
More file actions
2350 lines (2140 loc) · 106 KB
/
Copy pathplotter.py
File metadata and controls
2350 lines (2140 loc) · 106 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
"""
Interactive finite-size-scaling plotter for squeezing-criticality data.
Supports two simulation modes via --mode (default: stats):
stats Auto-discovers data/{rule}_stats_*.jld2. --observable picks the
measured quantity to analyze:
m — magnetization ⟨|m|⟩, χ_m, bind_m, t_auto_m
D — anisotropy ⟨|D|⟩, χ_D, bind_D, t_auto_D
(D = (1/N) Σᵢ σᵢσ_{i+x̂} − σᵢσ_{i+ŷ})
--plot picks which moment: mags, chis, binds, t_autos. Here
`t_auto` is the magnetization autocorrelation time of |obs|
(the exponential decay time of its connected autocorrelation
function, in MC sweeps) — NOT to be confused with `t_rel`,
the first-passage / relaxation time produced by --mode=trel.
trel Auto-discovers data/{rule}_trel_*.jld2 (aligned-against-bias first-
passage / relaxation times). Only --plot=t_rels is meaningful in
this mode; the collapse code path is the same as for `t_autos` in
stats mode (both scale as τ ~ L^z), only the loaded quantity and
axis labels differ. --observable is ignored.
Examples:
python3 plotter.py --rule R --plot binds # Binder of m
python3 plotter.py --rule R --observable D --plot binds # Binder of D
python3 plotter.py --mode=trel --rule=R --plot=t_rels # collapse t_rel(p, L)
python3 plotter.py --mode=trel --rule=R --plot=t_rels --raw # raw t_rel vs p
python3 plotter.py --rule M --plot mags --pc 0.00323
python3 plotter.py --rule R --plot binds --Ls 16 24 32
python3 plotter.py --plot binds --files data/R_stats_L16.jld2 data/R_stats_L24.jld2
"""
import argparse
import glob
import os
import sys
# Helper modules live in ./python/ — add it to sys.path so the bare imports
# below (and the deferred `import collapse_fit as cf` inside fit functions)
# resolve without callers having to set PYTHONPATH.
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
"python"))
import h5py
import numpy as np
# Shim for matplotlib >= 3.9, which removed matplotlib.cbook._Stack that older
# interactive widgets (including ours) depend on. Must run before scaling_plotter
# (and therefore matplotlib.widgets) is imported.
try:
import matplotlib.cbook
if not hasattr(matplotlib.cbook, "_Stack"):
class _Stack(list):
def push(self, item):
self.append(item)
return item
def pop(self):
return super().pop() if self else None
def current(self):
return self[-1] if self else None
def forward(self):
pass
def back(self):
pass
matplotlib.cbook._Stack = _Stack
except Exception:
pass
import matplotlib.cm as _cm
from exponents import get_defaults
from scaling_plotter import scaling_plotter
# Per-rule colormap — matches the convention from ca_plotter.py in the
# MemoryNCA/Ethan repo so cross-paper figures stay visually consistent.
# R3 (self-included variant of R) uses Oranges to match ca_plotter's colour
# for the three-neighbour squeezing variant.
_RULE_CMAP = {"R": _cm.Purples,
"R3": _cm.Oranges,
"M": _cm.Blues,
"F": _cm.Reds}
# Solid per-rule colours and labels matching ca_plotter.py's `get_labels()`,
# used by plot_quench when the loaded files cover multiple distinct rules
# (e.g. comparing magnetization decays across R / F / M / Toom / Ising on the
# same axes — the use case in MemoryNCA/Ethan/ca_plotter.py -plot mt).
def _quench_rule_style(rule_str, threesqz=False):
"""Return (color, label) for a given rule name string. Falls back to a
neutral dark grey when no match is found.
"""
r = (rule_str or "").lower()
if "toom" in r:
return ("#6BF3B3", r"$\mathsf{Toom}$")
if "glauber" in r or "ising" in r:
return ("#D3D3D3", r"$\mathsf{Ising}$")
if "rsqz" in r or r == "r" or "r3" in r:
if threesqz or "r3" in r:
return ("#FFA500", r"$\mathsf{R}_3$")
return ("#9086F8", r"$\mathsf{R}_2$")
if "msqz" in r or r == "m":
return ("#7BC1FC", r"$\mathsf{M}$")
if "fsqz" in r or r == "f":
return ("#FF4B62", r"$\mathsf{F}$")
return ("#4A4A4A", rf"$\mathsf{{{rule_str}}}$")
def _brighten(color, factor=1.2):
"""Brighten (factor>1) or darken (factor<1) a colour by scaling its HLS
lightness. Matches `brighten()` in ca_plotter.py so the dashed fit line
is drawn in the same darker shade of the curve colour.
"""
import colorsys
import matplotlib.colors as mcolors
h, l, s = colorsys.rgb_to_hls(*mcolors.to_rgb(color))
return colorsys.hls_to_rgb(h, min(1.0, l * factor), s)
# Per-rule (β, σ_β, ν, σ_ν) used to convert the fitted log-log slope of m(t)
# into a dynamical exponent z = -β / (ν · slope) in multi-rule mode. β, ν
# values for R₂, F, M come from the joint-fit results reported in the paper
# (numbers in parentheses are 1σ on the last digit). Toom and Glauber/Ising
# use the exact 2D-Ising values β = 1/8, ν = 1 with no uncertainty.
_QUENCH_RULE_EXPONENTS = {
"R": (0.165, 0.005, 0.952, 0.011),
"R3": (0.17, 0.0, 0.95, 0.0 ),
"F": (0.1826, 0.0020, 0.972, 0.016),
"M": (0.227, 0.005, 0.99, 0.04 ),
"Toom": (0.125, 0.0, 1.0, 0.0 ),
"Ising":(0.125, 0.0, 1.0, 0.0 ),
}
def _fmt_value_uncert(value, sigma, sig_sigma=1):
"""Format a measurement as '1.89(6)' — value rounded to the same decimal
as σ, which itself is rounded to `sig_sigma` significant figures; the
parenthesised number is σ expressed in units of the last quoted digit.
Falls back to a plain `%.3g` when σ is zero / non-finite.
"""
import math
if not (np.isfinite(value) and np.isfinite(sigma)) or sigma <= 0:
return f"{value:.3g}"
# decimal place at which σ's first significant digit sits
exp_sigma = math.floor(math.log10(abs(sigma)))
decimals = -(exp_sigma - (sig_sigma - 1)) # = -exp_sigma when sig_sigma=1
rounded_sigma = round(sigma, decimals)
if rounded_sigma == 0:
return f"{value:.3g}"
paren = int(round(rounded_sigma * 10 ** decimals))
val_fmt = f"{{:.{max(0, decimals)}f}}"
return f"{val_fmt.format(round(value, decimals))}({paren})"
def _quench_rule_exponents(rule_str, threesqz=False):
"""Return (β, σ_β, ν, σ_ν) for a given rule name."""
r = (rule_str or "").lower()
if "toom" in r: return _QUENCH_RULE_EXPONENTS["Toom"]
if "glauber" in r or "ising" in r: return _QUENCH_RULE_EXPONENTS["Ising"]
if "rsqz" in r or r == "r" or "r3" in r:
return _QUENCH_RULE_EXPONENTS["R3"] if (threesqz or "r3" in r) else _QUENCH_RULE_EXPONENTS["R"]
if "msqz" in r or r == "m": return _QUENCH_RULE_EXPONENTS["M"]
if "fsqz" in r or r == "f": return _QUENCH_RULE_EXPONENTS["F"]
return (np.nan, np.nan, np.nan, np.nan)
def _decode(x):
"""JLD2 strings come through h5py as bytes; decode to str."""
if isinstance(x, bytes):
return x.decode("utf-8")
if isinstance(x, np.ndarray) and x.dtype.kind in ("O", "S"):
try:
return x.item().decode("utf-8")
except Exception:
return str(x)
return x
def _read_key(f, key):
"""Read a top-level key from a JLD2/HDF5 file, stripping JLD2 metadata wrappers."""
if key not in f:
return None
val = f[key]
if isinstance(val, h5py.Group):
# JLD2 sometimes wraps typed objects in a group
if "data" in val:
return val["data"][()]
return None
return val[()]
def _read_err(f, key, like):
"""Read an error array if present, else an all-NaN array matching `like`."""
val = _read_key(f, key)
if val is None:
return np.full_like(np.asarray(like, dtype=float), np.nan)
return np.asarray(val, dtype=float)
def _nan_like(x):
return np.full_like(np.asarray(x, dtype=float), np.nan)
def _require_key(f, key, path, expected_mode):
"""Read a required key; raise a clear error if it's missing. Helps
diagnose mode/schema mismatches (e.g. loading a trel file as stats)."""
val = _read_key(f, key)
if val is None:
file_mode = _decode(_read_key(f, "mode")) or "?"
raise KeyError(
f"{os.path.basename(path)}: missing required key '{key}' "
f"(expected under mode='{expected_mode}', file has mode='{file_mode}'). "
f"Try --mode={file_mode} to plot this file."
)
return val
def load_stats_file(path, observable="m"):
"""Load a stats JLD2 file and return a dict of the fields for `observable`.
The observable-specific keys (m / D, chi_m / chi_D, ...) are mapped onto a
uniform set of dict keys (m, chi, bind, t_auto, *_err) so that downstream
code doesn't need to know which observable was selected. `t_auto` is the
magnetization autocorrelation time (the exponential decay time of the
connected autocorrelation function of |observable|, in MC sweeps); it is
distinct from `t_rel`, the first-passage / relaxation time produced by
`--mode=trel` and exposed under the dict key `t_rel` by `load_trel_file`.
Legacy compatibility: pre-2026-05 stats files stored this quantity as
`tau_exp_<obs>` on disk. If the new `t_auto_<obs>` key is missing, fall
back to the legacy name so existing data still loads.
"""
with h5py.File(path, "r") as f:
m = np.asarray(_require_key(f, observable, path, "stats"))
chi = np.asarray(_require_key(f, f"chi_{observable}", path, "stats"))
bind = np.asarray(_require_key(f, f"bind_{observable}", path, "stats"))
# Read the autocorrelation time under its current name; fall back to
# the legacy `tau_exp_<obs>` for older files.
t_auto_raw = _read_key(f, f"t_auto_{observable}")
if t_auto_raw is None:
t_auto_raw = _require_key(f, f"tau_exp_{observable}", path, "stats")
t_auto = np.asarray(t_auto_raw)
t_auto_err_raw = _read_key(f, f"t_auto_{observable}_err")
if t_auto_err_raw is None:
t_auto_err_raw = _read_key(f, f"tau_exp_{observable}_err")
t_auto_err = (np.asarray(t_auto_err_raw, dtype=float)
if t_auto_err_raw is not None
else np.full_like(t_auto, np.nan, dtype=float))
ps = np.asarray(_read_key(f, "ps"))
out = {
"rule": _decode(_read_key(f, "rule")),
"L": int(_read_key(f, "L")),
"ps": ps,
"m": m,
"chi": chi,
"bind": bind,
"t_auto": t_auto,
"m_err": _read_err(f, f"{observable}_err", m),
"chi_err": _read_err(f, f"chi_{observable}_err", chi),
"bind_err": _read_err(f, f"bind_{observable}_err", bind),
"t_auto_err": t_auto_err,
# stats mode has no `max_time` / first-passage semantics, so no
# censoring concept — all zeros.
"timeout_frac": np.zeros_like(ps, dtype=float),
"n_trials": 0,
"path": path,
}
return out
def load_trel_file(path):
"""Load a trel JLD2 file. The first-passage time `t_rel` is exposed
under the dict key `t_rel` (and its SEM as `t_rel_err`). It scales as
`t_rel ~ L^z` near criticality with the same form as the autocorrelation
time `t_auto` from stats mode — the scaling code path (`--plot t_rels`
here vs. `--plot t_autos` for stats) handles both with shared math but
distinct axis labels and dict keys.
Fields not measured in trel mode (m, chi, bind) come back as all-NaN
arrays of the right shape.
Also populates `timeout_frac`: the fraction of trials that hit `max_time`
per sweep point. Downstream consumers flag points with `timeout_frac >
CENSORED_FRAC_THRESHOLD` because their `t_rel` is a lower bound, not a
measurement.
Legacy compatibility: pre-2026-05 trel files stored these quantities
under the keys `trel`, `trel_err`, `trel_timeouts`. The loader falls
back to those names when the new `t_rel_*` keys are absent so existing
data still loads.
"""
with h5py.File(path, "r") as f:
ps = np.asarray(_read_key(f, "ps"))
# New on-disk name `t_rel`, falling back to the legacy `trel`.
t_rel_raw = _read_key(f, "t_rel")
if t_rel_raw is None:
t_rel_raw = _require_key(f, "trel", path, "trel")
t_rel = np.asarray(t_rel_raw)
t_rel_err_raw = _read_key(f, "t_rel_err")
if t_rel_err_raw is None:
t_rel_err_raw = _read_key(f, "trel_err")
t_rel_err = (np.asarray(t_rel_err_raw, dtype=float)
if t_rel_err_raw is not None
else _nan_like(t_rel))
timeouts_raw = _read_key(f, "t_rel_timeouts")
if timeouts_raw is None:
timeouts_raw = _read_key(f, "trel_timeouts")
n_trials = _read_key(f, "n_trials")
if timeouts_raw is not None and n_trials is not None and int(n_trials) > 0:
timeout_frac = np.asarray(timeouts_raw, dtype=float) / float(n_trials)
else:
timeout_frac = _nan_like(ps)
out = {
"rule": _decode(_read_key(f, "rule")),
"L": int(_read_key(f, "L")),
"ps": ps,
"m": _nan_like(ps),
"chi": _nan_like(ps),
"bind": _nan_like(ps),
"t_rel": t_rel,
"m_err": _nan_like(ps),
"chi_err": _nan_like(ps),
"bind_err": _nan_like(ps),
"t_rel_err": t_rel_err,
"timeout_frac": timeout_frac,
"n_trials": int(n_trials) if n_trials is not None else 0,
"path": path,
}
return out
# Points with more than this fraction of trials hitting `max_time` have a
# censored τ_rel (lower bound, not a measurement). Flag them visually and
# in stderr.
CENSORED_FRAC_THRESHOLD = 0.10
def _warn_censored(Ls, xs_all, timeout_frac, n_trials=None):
"""Print a stderr warning line for each (L, p) point whose timeout
fraction exceeds `CENSORED_FRAC_THRESHOLD`. Called by the trel plotters
just before drawing."""
if timeout_frac is None:
return
to_frac = np.asarray(timeout_frac)
if to_frac.size == 0 or np.all(to_frac <= CENSORED_FRAC_THRESHOLD):
return
lines = []
for l, L in enumerate(Ls):
if l >= to_frac.shape[0]:
break
xs = np.asarray(xs_all[l])
fs = np.asarray(to_frac[l])
nt = (int(n_trials[l])
if (n_trials is not None
and l < len(n_trials)
and n_trials[l] is not None)
else None)
for k in range(min(xs.size, fs.size)):
if fs[k] > CENSORED_FRAC_THRESHOLD:
if nt:
ttl = int(round(fs[k] * nt))
lines.append(
f" L={int(L)} p={xs[k]:.5g}: "
f"{ttl}/{nt} trials timed out "
f"({100*fs[k]:.0f}% — τ_rel is a lower bound)")
else:
lines.append(
f" L={int(L)} p={xs[k]:.5g}: "
f"{100*fs[k]:.0f}% of trials timed out "
"(τ_rel is a lower bound)")
if lines:
print(f"warning: {len(lines)} point(s) have > "
f"{int(100*CENSORED_FRAC_THRESHOLD)}% trials censored at max_time:",
file=sys.stderr)
for ln in lines:
print(ln, file=sys.stderr)
print(" (these points are drawn as open red ▲ markers.)",
file=sys.stderr)
def discover_files(rule, mode="stats", pattern_dir="data"):
"""Glob data/{rule}_{mode}_*.jld2."""
pat = os.path.join(pattern_dir, f"{rule}_{mode}_*.jld2")
return sorted(glob.glob(pat))
def load_quench_file(path):
"""Load a quench-mode JLD2 file. Returns a dict with:
rule, L, p, T, ts, n_samples,
per-observable trajectory-mean time series ({obs}_t, abs_{obs}_t) +
SEMs ({obs}_t_err, abs_{obs}_t_err), and per-observable time-dependent
Binder cumulants (bind_{obs}_t, bind_{obs}_t_err) when present (older
pre-Binder files won't have these — they come back as NaN).
Also supports the legacy memoryNCA schema (`mt`/`mabst`, no `ts`, no
error keys, no D observable) by detecting the absence of `m_t` and
falling back: ts is fabricated as 1..len(mt), errors come back NaN, and
D-observable keys are filled with NaN.
"""
with h5py.File(path, "r") as f:
legacy = (_read_key(f, "m_t") is None) and (_read_key(f, "mt") is not None)
n_samp = _read_key(f, "n_samples")
if n_samp is None:
n_samp = _read_key(f, "samps") # legacy memoryNCA name
# threesqz flag (legacy memoryNCA sqztest files) distinguishes the
# R_2 (two-neighbour) and R_3 (three-neighbour) variants of the
# squeezing rule, which use different ca_plotter rule colours.
# Absent in the present repo's native quench files; default False.
threesqz_raw = _read_key(f, "threesqz")
threesqz = bool(threesqz_raw) if threesqz_raw is not None else False
out = {
"rule": _decode(_read_key(f, "rule")),
"L": int(_read_key(f, "L")),
"p": float(_read_key(f, "p")),
"T": int(_read_key(f, "T")),
"n_samples": int(n_samp) if n_samp is not None else 0,
"threesqz": threesqz,
"path": path,
"mode_effective": "quench",
}
if legacy:
mt = np.asarray(_require_key(f, "mt", path, "quench"), dtype=float)
mabs = _read_key(f, "mabst")
mabs = np.asarray(mabs, dtype=float) if mabs is not None else np.abs(mt)
ts = _read_key(f, "ts")
out["ts"] = (np.asarray(ts) if ts is not None
else np.arange(1, len(mt) + 1, dtype=int))
out["m_t"] = mt
out["abs_m_t"] = mabs
out["m_t_err"] = np.full(mt.shape, np.nan)
out["abs_m_t_err"] = np.full(mabs.shape, np.nan)
for obs in ("D",):
out[f"{obs}_t"] = np.full(mt.shape, np.nan)
out[f"abs_{obs}_t"] = np.full(mt.shape, np.nan)
out[f"{obs}_t_err"] = np.full(mt.shape, np.nan)
out[f"abs_{obs}_t_err"] = np.full(mt.shape, np.nan)
for obs in ("m", "D"):
out[f"bind_{obs}_t"] = np.full(mt.shape, np.nan)
out[f"bind_{obs}_t_err"] = np.full(mt.shape, np.nan)
return out
out["ts"] = np.asarray(_read_key(f, "ts"))
for obs in ("m", "D"):
out[f"{obs}_t"] = np.asarray(_require_key(f, f"{obs}_t", path, "quench"))
out[f"abs_{obs}_t"] = np.asarray(_require_key(f, f"abs_{obs}_t", path, "quench"))
out[f"{obs}_t_err"] = np.asarray(_require_key(f, f"{obs}_t_err", path, "quench"))
out[f"abs_{obs}_t_err"] = np.asarray(_require_key(f, f"abs_{obs}_t_err", path, "quench"))
# Optional (added 2026-04-27): time-dependent Binder cumulant.
bind_t = _read_key(f, f"bind_{obs}_t")
bind_t_err = _read_key(f, f"bind_{obs}_t_err")
ts = out["ts"]
out[f"bind_{obs}_t"] = (np.asarray(bind_t, dtype=float)
if bind_t is not None
else np.full(ts.shape, np.nan))
out[f"bind_{obs}_t_err"] = (np.asarray(bind_t_err, dtype=float)
if bind_t_err is not None
else np.full(ts.shape, np.nan))
return out
def load_coarsening_file(path):
"""Load a coarsening-mode JLD2 file. Returns a dict with metadata
(rule, L, p, T, ts, n_samples, η) plus `area_t` (mean cluster size in
cells over trials) and `area_t_err` (population std across trials).
"""
with h5py.File(path, "r") as f:
out = {
"rule": _decode(_read_key(f, "rule")),
"L": int(_read_key(f, "L")),
"p": float(_read_key(f, "p")),
"T": int(_read_key(f, "T")),
"ts": np.asarray(_require_key(f, "ts", path, "coarsening")),
"n_samples": int(_read_key(f, "n_samples")),
"data_taking_ratio": int(_read_key(f, "data_taking_ratio") or 1),
"η": float(_read_key(f, "η")),
"init_cond": _decode(_read_key(f, "init_cond")),
"area_t": np.asarray(_require_key(f, "area_t", path, "coarsening"),
dtype=float),
"area_t_err": np.asarray(_require_key(f, "area_t_err", path, "coarsening"),
dtype=float),
"path": path,
"mode_effective": "coarsening",
}
return out
def load_erosion_stats_file(path):
"""Load an erosion_stats-mode JLD2 file. Returns a dict with the
metadata (rule, L, p, domain_size, n_samples, max_time, η, init_cond)
plus the **per-trial vector** `erosion_times` (length n_samples) and
summary scalars `mean_erosion_time`, `std_erosion_time`, `n_timeouts`.
"""
with h5py.File(path, "r") as f:
out = {
"rule": _decode(_read_key(f, "rule")),
"L": int(_read_key(f, "L")),
"p": float(_read_key(f, "p")),
"domain_size": float(_read_key(f, "domain_size")),
"n_samples": int(_read_key(f, "n_samples")),
"max_time": int(_read_key(f, "max_time")),
"η": float(_read_key(f, "η")),
"init_cond": _decode(_read_key(f, "init_cond")),
"erosion_times": np.asarray(_require_key(f, "erosion_times",
path, "erosion_stats"),
dtype=np.int64),
"n_timeouts": int(_read_key(f, "n_timeouts") or 0),
"mean_erosion_time": float(_read_key(f, "mean_erosion_time")),
"std_erosion_time": float(_read_key(f, "std_erosion_time")),
"path": path,
"mode_effective": "erosion_stats",
}
return out
def _compute_theta(ts, ys, b=10):
"""Instantaneous magnetization-decay exponent
θ(t) = log_b(⟨m(t/b)⟩ / ⟨m(t)⟩),
averaged over b consecutive samples to damp sample noise. Matches the
ca_plotter.py estimator and the screenshot convention: θ(t) is
**positive** for a decay, with θ(t) ≈ β/(νz) in the asymptotic regime.
For each k, θ_k = (1/ln b) · ⟨ ln(m[k] / m[k*b + j]) ⟩_{j=0..b-1}, with
m[k] taken as the "early" time and m[k*b + j] as the "late" time a
factor of b later.
Returns `(t_out, θ_out)` with `t_out[k] = ts[k] * b`. Empty arrays are
returned when there are fewer than b+1 input samples.
"""
ts = np.asarray(ts, dtype=float)
ys = np.asarray(ys, dtype=float)
n = len(ts)
# Need at least b+1 points to form one estimate at the earliest time.
if n <= b:
return np.array([]), np.array([])
t_out, theta_out = [], []
log_b = np.log(b)
for k in range(1, n // b): # start at k=1: m0 = ys[k]; need k ≥ 1
base = k * b
if base + b > n:
break
m0 = ys[k]
block = ys[base:base + b]
if m0 <= 0 or np.any(block <= 0):
continue
# Mean over b offsets of log_b(m_early / m_late). For decay this
# is > 0, and asymptotically equals β/(νz).
ratios = np.log(m0 / block) / log_b
theta_k = np.mean(ratios)
t_out.append(ts[k] * b)
theta_out.append(theta_k)
return np.asarray(t_out), np.asarray(theta_out)
def plot_quench(entries, observable, rule, *, use_abs=True,
fit_window=None, beta=None, nu=None,
plot_theta=False, theta_b=10,
title="", cmap=None):
"""Log-log plot of ⟨|x|⟩(t) vs t across L (one curve per size) for
quench-mode data. Fits a least-squares power law on each curve over
`fit_window = (t_lo, t_hi)` (default: middle 50% in log-t) and, given
β and ν, reports z_L = -β / (ν · slope) plus the trajectory-mean z.
With `use_abs=True` (default) the abs form ⟨|x|⟩(t) is plotted — required
for observables that cross zero (D starts at 0, m can sign-flip at late t).
With `use_abs=False` the signed ⟨x⟩(t) is plotted (positive before the
decay hits its finite-size floor).
With `plot_theta=True` the figure switches to the instantaneous decay
exponent θ(t) = d ln ⟨|x|⟩ / d ln t (log-spaced finite-difference with
step `theta_b`), on a semilog-x axis. A clean power-law regime shows up
as a plateau in θ(t). The plateau value is also printed, along with
z_plateau = -β / (ν · θ̄) when β, ν are available.
"""
import matplotlib.pyplot as plt
import matplotlib.cm as cm
# Match ca_plotter.py aesthetics: serif / Computer Modern Roman, larger
# square figure, thin lines with fat markers, no minor ticks.
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Computer Modern Roman'] + plt.rcParams.get(
'font.serif', [])
if cmap is None:
cmap = cm.coolwarm
lw = 1.2
ms = 7
entries = sorted(entries, key=lambda e: e["L"])
y_key = f"abs_{observable}_t" if use_abs else f"{observable}_t"
e_key = f"{y_key}_err"
# Detect multi-rule input (e.g. comparing R / F / M / Toom / Ising on the
# same axes — the use case in ca_plotter.py -plot mt). In that case we
# switch to ca_plotter-style aesthetics: one curve per rule with the
# per-rule colour and label, no black marker edges, fit window
# [1%, 75%] of the index range, and a plain `$m(t)$` y-label.
rules_seen = {(ent.get("rule") or "").strip() for ent in entries}
rule_mode = len(rules_seen) > 1
fig, ax = plt.subplots(figsize=(10, 8))
if not rule_mode:
# Rule-mode keeps minor ticks on so the y-axis log scale renders
# decimal labels (1, .9, .8, …) via ScalarFormatter below.
ax.minorticks_off()
# ------------------------------------------------------------------
# θ(t) branch: plot the instantaneous log-log slope per curve and
# print its mean over the same `fit_window` used for the power-law fit.
if plot_theta:
theta_means = []
# Post-_compute_theta binning width: group this many consecutive
# θ(t) samples and average to damp residual sample noise (a single
# _compute_theta call already averages over `theta_b` offsets but
# one curve per time-step is still jagged for short-T runs).
theta_bin = 10
# X-axis upper limit: the smallest final time across the loaded
# curves, so every rule has data over the full plotted range.
t_maxes = [float(np.asarray(ent["ts"], dtype=float)[-1])
for ent in entries]
x_right = min(t_maxes) if t_maxes else None
for li, ent in enumerate(entries):
L = ent["L"]
ts = np.asarray(ent["ts"], dtype=float)
ys = np.asarray(ent[y_key], dtype=float)
mask = np.isfinite(ys) & (ys > 0) & (ts > 0)
ts_m, ys_m = ts[mask], ys[mask]
if len(ts_m) <= theta_b:
continue
t_th, theta_th = _compute_theta(ts_m, ys_m, b=theta_b)
if t_th.size == 0:
continue
# Bin the (t_th, theta_th) output by `theta_bin` consecutive
# samples, averaging each group. Drops the trailing partial bin
# (so all bins represent the same number of underlying samples).
if theta_bin > 1 and t_th.size >= theta_bin:
nfull = (t_th.size // theta_bin) * theta_bin
t_th = t_th[:nfull].reshape(-1, theta_bin).mean(axis=1)
theta_th = theta_th[:nfull].reshape(-1, theta_bin).mean(axis=1)
if rule_mode:
col, lab = _quench_rule_style(ent.get("rule"),
ent.get("threesqz", False))
mec, line_lw, point_ms = col, 0, ms * 0.75
ent_beta, ent_beta_err, ent_nu, ent_nu_err = \
_quench_rule_exponents(ent.get("rule"),
ent.get("threesqz", False))
else:
col = cmap((li + 1) / max(len(entries), 1))
lab, mec, line_lw, point_ms = rf"${int(L)}$", col, lw, ms
ent_beta, ent_nu = beta, nu
ent_beta_err = ent_nu_err = 0.0
# Plateau θ̄: average of the latter 50% of the binned curve
# within the displayed time window (overrides any explicit
# --fit-window in plot-theta mode, which is fine since fit-window
# was originally only used for the mt-branch power-law fit).
in_window = (t_th <= x_right) if x_right is not None else slice(None)
t_in = t_th[in_window]
theta_in = theta_th[in_window]
if t_in.size >= 2:
half = t_in.size // 2
theta_bar = float(np.mean(theta_in[half:]))
else:
theta_bar = np.nan
# Combine the rule label with the plateau θ̄ to three decimal
# places into a single legend entry (the dashed line itself is
# unlabelled to avoid a duplicate entry).
if rule_mode and np.isfinite(theta_bar):
inner = lab.strip("$")
curve_lab = rf"${inner}\;\;{theta_bar:.3f}$"
else:
curve_lab = lab
ax.plot(t_th, theta_th, c=col, lw=line_lw, marker='o',
ms=point_ms, mew=lw, mec=mec, label=curve_lab,
alpha=0.8 if rule_mode else 0.85)
if np.isfinite(theta_bar):
line_col = _brighten(col, 0.5) if rule_mode else col
ax.axhline(theta_bar, color=line_col, linestyle='--',
linewidth=2 * lw, alpha=0.6)
theta_means.append((L, theta_bar, lab,
ent_beta, ent_beta_err, ent_nu, ent_nu_err))
ax.set_xlabel(r'$t$')
ax.set_ylabel(r'$\theta(t)$')
ax.minorticks_off()
if x_right is not None:
ax.set_xlim(left=0, right=x_right)
else:
ax.set_xlim(left=0)
ax.set_ylim(bottom=0)
if rule_mode:
# Multi-column legend at the bottom-centre so it doesn't
# overlap the rising portions of the θ(t) curves.
ax.legend(loc='lower center', ncols=3, frameon=False)
else:
ax.legend(title=r'$L$', ncols=2)
ax.set_title(title)
fig.tight_layout()
# Per-curve table: plateau mean θ → z = β / (ν · θ̄).
# Propagate σ_β, σ_ν (θ̄ treated as fixed): (σ_z/|z|)² = (σ_β/β)² + (σ_ν/ν)².
print()
if rule_mode:
print(f"{'rule':>12} {'L':>5} {'mean θ':>10} {'z':>14}")
else:
print(f"{'L':>5} {'mean θ':>10} {'z':>10}")
zs = []
for L, th, lab, b_, be_, n_, ne_ in theta_means:
if b_ is not None and n_ is not None and th > 0 and np.isfinite(th):
z_L = b_ / (n_ * th)
if b_ > 0 and n_ > 0:
ze_L = abs(z_L) * np.sqrt((be_ / b_) ** 2 + (ne_ / n_) ** 2)
else:
ze_L = np.nan
else:
z_L, ze_L = float('nan'), float('nan')
zs.append(z_L)
if rule_mode:
z_str = _fmt_value_uncert(z_L, ze_L)
print(f"{lab:>12} {L:>5d} {th:>10.4g} {z_str:>14}")
else:
print(f"{L:>5d} {th:>10.4g} {z_L:>10.4g}")
finite_z = [z for z in zs if np.isfinite(z)]
if finite_z and not rule_mode:
mn = float(np.mean(finite_z))
sd = float(np.std(finite_z, ddof=1)) if len(finite_z) > 1 else 0.0
print(f"\nz = {mn:.4g} ± {sd:.4g} "
f"(mean ± std of β/(ν·θ̄) across {len(finite_z)} L values, "
f"β={beta}, ν={nu})")
plt.show()
return
# ------------------------------------------------------------------
# Default branch: log-log ⟨|x|⟩(t) curves + power-law fit overlay.
z_vals = []
for li, ent in enumerate(entries):
L = ent["L"]
ts = np.asarray(ent["ts"], dtype=float)
ys = np.asarray(ent[y_key], dtype=float)
es = np.asarray(ent[e_key], dtype=float)
# drop points with non-positive y (log-scale) or non-finite values
mask = np.isfinite(ys) & (ys > 0) & (ts > 0)
ts_m, ys_m = ts[mask], ys[mask]
es_m = np.where(np.isfinite(es[mask]) & (es[mask] > 0), es[mask], np.nan)
if rule_mode:
col, lab = _quench_rule_style(ent.get("rule"),
ent.get("threesqz", False))
mec = col
ent_beta, ent_beta_err, ent_nu, ent_nu_err = \
_quench_rule_exponents(ent.get("rule"),
ent.get("threesqz", False))
else:
col = cmap((li + 1) / max(len(entries), 1))
lab = rf"${int(L)}$"
mec = 'k'
ent_beta, ent_nu = beta, nu
ent_beta_err = ent_nu_err = 0.0
# error ribbon: shaded band at ±1 SEM, falling back to no band where
# SEM is NaN (e.g. n_samples=1 run).
if not np.all(np.isnan(es_m)):
ax.fill_between(ts_m, ys_m - es_m, ys_m + es_m,
color=col, alpha=0.25, linewidth=0)
# Rule-mode: smaller markers and no connecting line (the dashed
# power-law fit is the only line drawn). FSS-mode unchanged.
plot_lw = 0 if rule_mode else lw
plot_ms = ms * 0.75 if rule_mode else ms
ax.plot(ts_m, ys_m, c=col, lw=plot_lw, marker='o', ms=plot_ms,
mew=lw, mec=mec,
label=lab, alpha=0.8 if rule_mode else 0.85)
# fit window. In rule-mode we match ca_plotter.py: indices [1%, 75%]
# of the curve. Otherwise (FSS-style single-rule data) keep the
# historical middle-50%-in-log-t window.
if fit_window is None:
if rule_mode:
n = len(ts_m)
i1 = max(1, int(round(0.01 * n)))
i2 = max(i1 + 2, int(round(0.75 * n)))
lo, hi = ts_m[i1], ts_m[min(i2, n - 1)]
else:
log_t = np.log(ts_m)
lo = np.exp(log_t[0] + 0.25 * (log_t[-1] - log_t[0]))
hi = np.exp(log_t[0] + 0.75 * (log_t[-1] - log_t[0]))
else:
lo, hi = fit_window
fit_mask = (ts_m >= lo) & (ts_m <= hi)
if fit_mask.sum() < 2:
continue
# log-log slope via np.polyfit
slope, intercept = np.polyfit(np.log(ts_m[fit_mask]),
np.log(ys_m[fit_mask]), 1)
# z from β, ν, slope: ⟨|x|⟩(t) ∝ t^(-β/(νz)) ⇒ z = -β/(ν·slope).
# Propagate σ_β, σ_ν (slope treated as fixed):
# (σ_z / |z|)² = (σ_β / β)² + (σ_ν / ν)².
if ent_beta is not None and ent_nu is not None \
and np.isfinite(ent_beta) and np.isfinite(ent_nu) \
and slope < 0:
z_L = -ent_beta / (ent_nu * slope)
if ent_beta > 0 and ent_nu > 0:
rel_var = (ent_beta_err / ent_beta) ** 2 \
+ (ent_nu_err / ent_nu) ** 2
z_err = abs(z_L) * np.sqrt(rel_var)
else:
z_err = np.nan
else:
z_L = np.nan
z_err = np.nan
z_vals.append((L, slope, z_L, z_err, lab if rule_mode else None))
if rule_mode:
# ca_plotter style: dashed darker-shade fit line drawn over the
# whole curve from index 5 onward, labelled with the magnetization
# decay exponent (= -slope) to three significant figures.
t_line = ts_m[5:] if len(ts_m) > 5 else ts_m
y_line = np.exp(intercept + slope * np.log(t_line))
ax.plot(t_line, y_line, c=_brighten(col, 0.5),
ls='--', lw=2 * lw, alpha=1.0,
label=r"$%.3g$" % (-slope))
else:
# FSS style: dashed fit line confined to the fit window.
t_line = np.geomspace(ts_m[fit_mask][0], ts_m[fit_mask][-1], 20)
y_line = np.exp(intercept + slope * np.log(t_line))
ax.plot(t_line, y_line, c=col, ls='--', lw=2 * lw, alpha=0.9)
ax.set_xscale('log'); ax.set_yscale('log')
ax.set_xlabel(r'$t$')
if rule_mode:
ax.set_ylabel(r'$m(t)$')
ax.set_ylim(bottom=0.3, top=1.1)
# Render the log-scale y ticks as plain decimals (1, .9, .8, …), the
# same trick ca_plotter uses on its mt plot.
from matplotlib.ticker import ScalarFormatter
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.yaxis.set_minor_formatter(ScalarFormatter())
ax.legend()
else:
if use_abs:
ax.set_ylabel(rf'$\langle | {observable} | (t) \rangle$')
else:
ax.set_ylabel(rf'$\langle {observable}(t) \rangle$')
ax.legend(title=r'$L$', ncols=2)
ax.set_title(title)
fig.tight_layout()
# Per-curve table + summary. In rule-mode the first column is the rule
# label (per-rule β, ν used for z, with σ_z from error propagation);
# otherwise L (with shared β, ν, no σ_z).
print()
if rule_mode:
print(f"{'rule':>12} {'L':>5} {'slope':>10} {'z':>14}")
for L, s, z, ze, lab in z_vals:
z_str = _fmt_value_uncert(z, ze)
print(f"{lab:>12} {L:>5d} {s:>10.4g} {z_str:>14}")
else:
print(f"{'L':>5} {'slope':>10} {'z':>10}")
for L, s, z, _, _ in z_vals:
print(f"{L:>5d} {s:>10.4g} {z:>10.4g}")
finite_z = [z for _, _, z, _, _ in z_vals if np.isfinite(z)]
if finite_z and not rule_mode:
mean = float(np.mean(finite_z))
std = float(np.std(finite_z, ddof=1)) if len(finite_z) > 1 else 0.0
print(f"\nz = {mean:.4g} ± {std:.4g} "
f"(mean ± std across {len(finite_z)} L values, "
f"β={beta}, ν={nu})")
elif not rule_mode and (beta is None or nu is None):
print("\nz not computed — pass --beta and --nu (or their defaults "
"in exponents.py) to infer z from the fitted slope.")
plt.show()
def plot_trel(thermo, pc, title="", raw=False, cmap=None):
"""Direct τ_rel vs (p − pc) plot for trel-mode data.
One curve per system size, log-log axes when `raw=False` (shows power-law
τ_rel ∝ (p − pc)^(−νz)). With `raw=True`, plot τ_rel vs p on semilogy axes
for a sanity check when pc isn't trusted.
"""
import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Computer Modern Roman'] + plt.rcParams.get(
'font.serif', [])
if cmap is None:
cmap = cm.coolwarm
Ls = np.asarray(thermo["Ls"])
xs_all = np.asarray(thermo["xs"]) # (nL, n_ps)
tau = np.asarray(thermo["t_rels"]) # (nL, n_ps), first-passage time
tau_e = np.asarray(thermo["t_rels_err"]) # (nL, n_ps), may be all NaN
to_frac = np.asarray(thermo.get("timeout_frac",
np.zeros_like(tau))) # (nL, n_ps)
_warn_censored(Ls, xs_all, to_frac, thermo.get("n_trials"))
fig, ax = plt.subplots(figsize=(4.5, 3.8))
any_plotted = False
min_p_seen = np.inf
# Pool uncensored (p − pc, τ) across all L for the power-law overlay.
pool_dp, pool_t = [], []
for l, _ in enumerate(Ls):
col = cmap((l + 1) / max(len(Ls), 1))
raw_xs = xs_all[l]
xs = raw_xs if raw else raw_xs - pc
ys = tau[l]
ye = tau_e[l]
cen = to_frac[l] if l < len(to_frac) else np.zeros_like(ys)
# Drop non-positive x (only relevant with `not raw` if some p ≤ pc),
# and non-finite y values.
mask = np.isfinite(ys) & (np.asarray(xs) > 0 if not raw
else np.ones_like(xs, bool))
if raw_xs.size:
min_p_seen = min(min_p_seen, float(raw_xs.min()))
if not np.any(mask):
continue
xs_m, ys_m = xs[mask], ys[mask]
ye_m = ye[mask]
ye_m = None if np.all(np.isnan(ye_m)) else np.where(np.isnan(ye_m), 0.0, ye_m)
# Split into "good" and "censored" (timeout frac > threshold). Censored
# points get an open red-edged marker and a vertical up-arrow to signal
# that τ_rel is a lower bound.
cen_mask = cen[mask] > CENSORED_FRAC_THRESHOLD
good_mask = ~cen_mask
if good_mask.any():
ye_g = None if ye_m is None else ye_m[good_mask]
ax.errorbar(xs_m[good_mask], ys_m[good_mask], yerr=ye_g,
c=col, marker='o', mec='k', mew=0.8, ms=5, ls='-',
lw=1.5, capsize=2, label=None)
if not raw:
pool_dp.extend(xs_m[good_mask].tolist())
pool_t.extend(ys_m[good_mask].tolist())
if cen_mask.any():
ax.errorbar(xs_m[cen_mask], ys_m[cen_mask], yerr=None,
c=col, marker='^', mec='red', mew=1.2, ms=7,
mfc='white', ls='', lw=0,
label=None)
any_plotted = True
if not any_plotted:
plt.close(fig)
raise RuntimeError(
f"plot_trel: no points survived the p > pc filter "
f"(pc = {pc:.5g}, min p in data = {min_p_seen:.5g}). "
"Pass a correct --pc, or use --raw to plot τ_rel vs p directly."
)
# Power-law overlay (log-log axes only): τ = A · (p − pc)^(−a). Two-param
# linear fit of log τ on log(p − pc) over the pooled uncensored points.
fit_label = None
if not raw and len(pool_dp) >= 2:
pool_dp_a = np.asarray(pool_dp)
pool_t_a = np.asarray(pool_t)
slope, intercept = np.polyfit(np.log(pool_dp_a), np.log(pool_t_a), 1)
a_fit = -slope
A_fit = np.exp(intercept)
xs_line = np.geomspace(pool_dp_a.min(), pool_dp_a.max(), 80)
ys_line = A_fit * xs_line ** (-a_fit)
fit_label = rf"$a = {a_fit:.2f}$"
ax.plot(xs_line, ys_line, "k--", lw=1.2, label=fit_label)
print(f"power-law fit τ_mem = A · (p − pc)^(−a) with pc = {pc:.5g}:",
file=sys.stderr)
print(f" a = {a_fit:.3f}, A = {A_fit:.3g}", file=sys.stderr)
ax.set_xscale('log' if not raw else 'linear')
ax.set_yscale('log')
ax.set_xlabel(r'$p - p_c$' if not raw else r'$p$')
ax.set_ylabel(r'$\tau_{\sf mem}$')
if not raw:
ax.set_title((title + r" $|$ " if title else "") +
rf"$p_c = {pc:.5g}$")
else:
ax.set_title(title)
if fit_label is not None:
# Only the fit line goes in the legend, no frame, no title.
ax.legend(frameon=False, fontsize=11)
fig.tight_layout()
plt.show()
def plot_trel_nucleation(thermo, pc, title="", cmap=None, a_fixed=None):
"""Test first-order / nucleation-style scaling
τ_rel ∝ exp( b · (p − pc)^(−a) )
on trel-mode data. This is the natural ansatz if the transition is
nucleation-driven: the activation barrier scales as a power of the
supersaturation, giving an exp-of-power relaxation time.
Two complementary fits are reported:
1. **Linearized fit** (log-log-log): `log log τ = log b − a · log(p − pc)`.