-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmooth_windowing_abc.py
More file actions
2456 lines (2185 loc) · 106 KB
/
Copy pathsmooth_windowing_abc.py
File metadata and controls
2456 lines (2185 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
# -*- coding: utf-8 -*-
"""
Smooth Windowing via C-infinity Bump Functions for Pseudo-Spectral Quantum Dynamics.
Companion code for:
D. Ariza-Ruiz, "Parameter-Free Absorbing Boundaries for Pseudo-Spectral
Quantum Dynamics via C-infinity Windowing",
Computer Physics Communications (2026).
Theoretical foundation:
P. Bergold & C. Lasser, "Fourier Series Windowed by a Bump Function",
J. Fourier Anal. Appl. 26 (2020) 65.
https://doi.org/10.1007/s00041-020-09773-3
This script runs thirteen numerical experiments and generates publication-
quality figures (300 dpi PNG/PDF) plus summary tables printed to stdout:
Experiment 1 -- Gibbs suppression & L2 convergence (standard / Hann / C-inf)
Experiment 2 -- Schrodinger wave packet absorption (standard vs. windowed)
Experiment 3 -- Convergence vs. plateau parameter rho
Experiment 4 -- Window regularity comparison (Hann / Tukey / C-inf bump)
Experiment 5 -- Complex absorbing potential (CAP) parameter sweep (preview)
Experiment 6 -- CAP robustness across momenta
Experiment 7 -- Hamiltonian vs. multiplicative CAP (reproduces tab:cap_sweep)
Experiment 8 -- Manolopoulos transmission-free CAP benchmark (rem:cap_scope)
Experiment 9 -- Temporal convergence study with plateau-restricted norm
(reproduces tab:temporal_convergence and
eqs. norm_powerlaw and spurious_density_scaling)
Experiment 10 -- Gaussian barrier scattering (above-barrier & tunneling,
with large-domain reference for the tunneling regime)
Experiment 11 -- 1D PML with Crank-Nicolson finite differences
(reproduces tab:pml_comparison)
Experiment 12 -- Comprehensive tunneling & strong-barrier scattering campaign
(reproduces tab:scatt-summary and figures 9, 10, 11):
dense 2D (eta, V0) map, long-time propagation, barrier-shape
universality (Gaussian/sech^2/rect), eta-saturation,
dt-anomaly diagnosis (Strang vs. Yoshida 4th-order),
fixed window-period prescription, reference convergence
Experiment 13 -- Multiple-reflection benchmark (C-inf windowing vs PML
in confined-scattering regime with machine-precision
reference solution)
Usage:
python smooth_windowing_abc.py
Author: David Ariza-Ruiz
Faculty of Engineering, Science and Technology
Valencian International University (VIU), Spain
david.ariza@professor.universidadviu.com
License: MIT (see LICENSE)
"""
from __future__ import annotations
import time as timer
import math
import numpy as np
def _erf_scalar(x):
"""Wrapper for math.erf that works with scalars."""
return math.erf(x)
# Vectorized erf using math.erf (no scipy needed)
erf = np.vectorize(_erf_scalar, otypes=[float])
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
# =============================================================================
# 0. GLOBAL SETTINGS
# =============================================================================
plt.rcParams.update({
'font.size': 12,
'axes.labelsize': 13,
'axes.titlesize': 13,
'legend.fontsize': 10,
'xtick.labelsize': 11,
'ytick.labelsize': 11,
'figure.dpi': 150,
'savefig.dpi': 300,
'savefig.bbox': 'tight',
'text.usetex': False, # Set True if LaTeX is installed
'font.family': 'serif',
})
OUTPUT_DIR = "." # Change to a subfolder if desired
# =============================================================================
# 1. CORE MATHEMATICAL FUNCTIONS
# =============================================================================
def standard_bump_function(t: np.ndarray) -> np.ndarray:
"""Degenerate C-infinity bump on [-1, 1], normalized to peak value 1.
phi(t) = exp(-1 / (1 - t^2)) / exp(-1), |t| < 1; 0 otherwise.
Corresponds to the rho = 0 (no plateau) case.
"""
result = np.zeros_like(t, dtype=float)
mask = np.abs(t) < 1.0
t_interior = t[mask]
result[mask] = np.exp(-1.0 / (1.0 - t_interior**2))
peak = np.exp(-1.0) # max at t=0
return result / peak
def plateau_bump_function(t: np.ndarray, rho: float) -> np.ndarray:
"""Non-degenerate C-infinity bump with plateau on [-rho, rho], support [-1, 1].
Implements Bergold & Lasser Eq. (4.1) with lambda = 1.
Parameters
----------
t : ndarray
Evaluation points.
rho : float
Half-width of the plateau region, 0 <= rho < 1.
Returns
-------
ndarray
Window values in [0, 1].
"""
result = np.zeros_like(t, dtype=float)
at = np.abs(t)
# Region 1: plateau
mask_plateau = at <= rho
result[mask_plateau] = 1.0
# Region 2: transition
mask_trans = (at > rho) & (at < 1.0)
a = at[mask_trans]
# Bergold & Lasser Eq. (4.1):
# w(x) = 1 / (exp(1/(lambda-|x|) + 1/(rho-|x|)) + 1)
exponent = 1.0 / (1.0 - a) + 1.0 / (rho - a)
with np.errstate(over='ignore'):
result[mask_trans] = 1.0 / (np.exp(exponent) + 1.0)
# Region 3: outside support -> already 0
return result
def absorbing_boundary_window(
x: np.ndarray, L: float, width_fraction: float = 0.15
) -> np.ndarray:
"""C-infinity absorbing boundary window on [-L, L].
Implements the Bergold & Lasser Eq. (4.1) smooth bump w_{rho, lambda}
with lambda = L and rho = (1 - eta) * L:
W(x) = 1 / (exp(1/(L - |x|) + 1/(rho - |x|)) + 1)
for rho < |x| < L, with W = 1 on |x| <= rho and W = 0 for |x| >= L.
This is the *sigmoidal-logistic* profile whose convergence properties
are analyzed in Theorems 3.3 and 4.6 of [Bergold & Lasser, 2020].
Parameters
----------
x : ndarray
Spatial grid points.
L : float
Half-width of the computational domain (= lambda).
width_fraction : float
Fraction eta of each half-domain used for absorption (default 0.15).
Returns
-------
ndarray
Window values in [0, 1].
"""
eta = width_fraction
rho = (1.0 - eta) * L
ax = np.abs(x)
result = np.ones_like(ax, dtype=float)
# Transition region: rho < |x| < L
mask_trans = (ax > rho) & (ax < L)
a = ax[mask_trans]
# Bergold & Lasser Eq. (4.1): w(x) = 1 / (exp(1/(lambda-|x|) + 1/(rho-|x|)) + 1)
# Note: rho - a < 0 in the transition region, so the second term is negative.
exponent = 1.0 / (L - a) + 1.0 / (rho - a)
with np.errstate(over='ignore'):
result[mask_trans] = 1.0 / (np.exp(exponent) + 1.0)
# Outside support: |x| >= L
result[ax >= L] = 0.0
return result
def fourier_truncation(signal: np.ndarray, num_coefs: int) -> np.ndarray:
"""Truncate the DFT of *signal* to the lowest *num_coefs* modes (symmetric)."""
coeffs = np.fft.fft(signal)
truncated = np.zeros_like(coeffs)
truncated[:num_coefs] = coeffs[:num_coefs]
truncated[-num_coefs:] = coeffs[-num_coefs:]
return np.real(np.fft.ifft(truncated))
def _tridiag_solve(a: np.ndarray, b: np.ndarray, c: np.ndarray,
d: np.ndarray) -> np.ndarray:
"""Thomas algorithm for a tridiagonal system (complex-valued, dependency-free).
Solves a[i] x[i-1] + b[i] x[i] + c[i] x[i+1] = d[i] with a[0] = c[-1] = 0.
Parameters
----------
a, b, c : ndarray (complex, length n)
Sub-, main-, and super-diagonals (a[0] and c[-1] unused).
d : ndarray (complex, length n)
Right-hand side.
"""
n = len(d)
cp = np.empty(n, dtype=c.dtype)
dp = np.empty(n, dtype=d.dtype)
cp[0] = c[0] / b[0]
dp[0] = d[0] / b[0]
for i in range(1, n):
m = b[i] - a[i] * cp[i-1]
cp[i] = c[i] / m if i < n - 1 else 0.0
dp[i] = (d[i] - a[i] * dp[i-1]) / m
x = np.empty(n, dtype=d.dtype)
x[-1] = dp[-1]
for i in range(n - 2, -1, -1):
x[i] = dp[i] - cp[i] * x[i+1]
return x
def pml_cn_fd_run(sigma_max: float, N_grid: int, dt_step: float,
L: float = 10.0, rho: float = 8.5, p_exp: int = 2,
T_final: float = 0.9, x0: float = -5.0,
p0: float = 15.0, sigma0: float = 1.0) -> dict:
"""Run one PML + Crank-Nicolson second-order FD simulation.
Integrates the complex-stretched Schrodinger equation
i d_t psi = -0.5 * (1/s) d_x [ (1/s) d_x psi ],
s(x) = 1 + i*sigma(x),
sigma(x) = sigma_max * ((|x|-rho)/(L-rho))^p_exp for |x|>rho.
Dirichlet boundary conditions psi(-L) = psi(L) = 0. Uses a uniform grid
of (N_grid + 1) points with second-order centred finite differences and
Crank-Nicolson time stepping. Returns a dict with the spurious density in
x < 0, the plateau norm on |x| <= rho, and the total L2 norm at T_final.
"""
# Grid including both Dirichlet endpoints
x_full = np.linspace(-L, L, N_grid + 1)
h = x_full[1] - x_full[0]
# Interior unknowns j = 1..N_grid-1
n_int = N_grid - 1
x_int = x_full[1:N_grid]
# Half-grid points x_{j+1/2}, j = 0..N_grid-1
x_half = x_full[:-1] + h / 2.0
ax_half = np.abs(x_half)
sig_half = np.where(ax_half > rho,
sigma_max * ((ax_half - rho) / (L - rho))**p_exp,
0.0)
inv_s_half = 1.0 / (1.0 + 1j * sig_half)
# sigma at interior grid points
ax_int = np.abs(x_int)
sig_int = np.where(ax_int > rho,
sigma_max * ((ax_int - rho) / (L - rho))**p_exp,
0.0)
inv_s_int = 1.0 / (1.0 + 1j * sig_int)
sm = inv_s_half[:-1] # s_{j-1/2}^{-1} (k=0..n_int-1)
sp = inv_s_half[1:] # s_{j+1/2}^{-1}
pref = inv_s_int / h**2
coef_left = pref * sm
coef_right = pref * sp
coef_diag = -pref * (sm + sp)
# Crank-Nicolson: d_t u = (i/2) L_op u
# (I - (i*dt/4) L_op) u^{n+1} = (I + (i*dt/4) L_op) u^n
theta = 1j * dt_step / 4.0
a_L = -theta * coef_left
b_L = 1.0 - theta * coef_diag
c_L = -theta * coef_right
a_R = theta * coef_left
b_R = 1.0 + theta * coef_diag
c_R = theta * coef_right
# Initial Gaussian wave packet, L2-normalized on the full grid (trapezoidal)
psi_full = np.exp(-(x_full - x0)**2 / (2.0 * sigma0**2)) * np.exp(1j * p0 * x_full)
psi_full /= np.sqrt(np.sum(np.abs(psi_full)**2) * h)
psi_full[0] = 0.0
psi_full[-1] = 0.0
u = psi_full[1:N_grid].astype(np.complex128)
M_steps = int(round(T_final / dt_step))
for _ in range(M_steps):
d_rhs = b_R * u
d_rhs[1:] += a_R[1:] * u[:-1]
d_rhs[:-1] += c_R[:-1] * u[1:]
u = _tridiag_solve(a_L.copy(), b_L.copy(), c_L.copy(), d_rhs)
psi_final = np.zeros(N_grid + 1, dtype=np.complex128)
psi_final[1:N_grid] = u
dens = np.abs(psi_final)**2
return {
'spur_density': float(np.sum(dens[x_full < 0.0]) * h),
'plateau_norm': float(np.sum(dens[np.abs(x_full) <= rho]) * h),
'total_norm': float(np.sum(dens) * h),
'M_steps': M_steps,
}
# =============================================================================
# 2. EXPERIMENTS
# =============================================================================
if __name__ == "__main__":
# =========================================================================
# EXPERIMENT 1: GIBBS PHENOMENON & L2 CONVERGENCE (degenerate bump, rho=0)
# =========================================================================
print("=" * 72)
print("EXPERIMENT 1: Convergence Analysis (degenerate bump, rho=0)")
print("=" * 72)
N_grid = 20000
lam_1 = 1.0 # Half-domain for Experiment 1
x_1D = np.linspace(-lam_1, lam_1, N_grid, endpoint=False)
dx_1 = 2.0 * lam_1 / N_grid # Grid spacing (matches Eq. (16))
f_x = x_1D.copy() # Test function f(x) = x
bump_degen = plateau_bump_function(x_1D, 0.0) # B&L Eq. 4.1 with rho=0
f_windowed = f_x * bump_degen
# numpy can track errors reliably until the float64 floor (~2e-16);
# the extended high-precision data is produced separately in 80-digit
# arithmetic and loaded from convergence_extended.csv.
N_max = 160
coef_range = np.arange(1, N_max + 1)
err_std = np.zeros(N_max)
err_win = np.zeros(N_max)
err_hann = np.zeros(N_max)
# Hann window on [-1, 1] for convergence comparison
hann_1D = np.zeros_like(x_1D)
mask_hann_1D = np.abs(x_1D) < 1.0
hann_1D[mask_hann_1D] = 0.5 * (1.0 + np.cos(np.pi * np.abs(x_1D[mask_hann_1D])))
f_hann = f_x * hann_1D
for i, n in enumerate(coef_range):
approx_s = fourier_truncation(f_x, n)
approx_w = fourier_truncation(f_windowed, n)
approx_h = fourier_truncation(f_hann, n)
# L2 error using the discrete L2 norm: sqrt(sum |f - S_n f|^2 * dx)
# This matches Eq. (16) of the manuscript.
err_std[i] = np.sqrt(np.sum(np.abs(f_x - approx_s)**2) * dx_1)
err_win[i] = np.sqrt(np.sum(np.abs(f_windowed - approx_w)**2) * dx_1)
err_hann[i] = np.sqrt(np.sum(np.abs(f_hann - approx_h)**2) * dx_1)
# ---- Load extended high-precision convergence data if available ----
import csv as csv_module
extended_csv = f'{OUTPUT_DIR}/convergence_extended.csv'
extended_available = False
try:
with open(extended_csv, 'r') as fcsv:
reader = csv_module.DictReader(fcsv)
mp_n, mp_cinf, mp_hann, mp_std = [], [], [], []
for row in reader:
mp_n.append(int(row['n']))
val = float(row['eps_cinf']) if row['eps_cinf'] != '0' else 0.0
mp_cinf.append(val if val > 0 else np.nan)
mp_hann.append(float(row['eps_hann']))
mp_std.append(float(row['eps_std']))
mp_n = np.array(mp_n)
mp_cinf = np.array(mp_cinf)
mp_hann = np.array(mp_hann)
mp_std = np.array(mp_std)
N_FOURIER_EXT = len(mp_n)
extended_available = True
print(f" -> Loaded extended convergence data: n = 1 … {N_FOURIER_EXT}")
except FileNotFoundError:
print(f" -> Extended CSV not found ({extended_csv}); using numpy data only")
# ---- Figure 1: Convergence plot ----
fig1, ax1 = plt.subplots(figsize=(10, 7))
if extended_available:
# Use extended high-precision data for the full range
ax1.semilogy(mp_n, mp_std, 'r-', linewidth=1.0, alpha=0.8,
label='Standard truncation (no window)')
ax1.semilogy(mp_n, mp_hann, '-', color='#ff7f0e', linewidth=1.0, alpha=0.8,
label=r'Hann window ($C^1$, algebraic $\mathcal{O}(n^{-2})$)')
ax1.semilogy(mp_n, mp_cinf, 'b-', linewidth=1.5,
label=r'$C^\infty$ bump (super-algebraic)')
plot_range = mp_n
ref_cinf = mp_cinf
else:
ax1.semilogy(coef_range, err_std, 'r.-', markersize=5, linewidth=1.2,
label='Standard truncation (no window)')
ax1.semilogy(coef_range, err_hann, 's-', color='#ff7f0e', markersize=4, linewidth=1.2,
label=r'Hann window ($C^1$, algebraic $\mathcal{O}(n^{-2})$)')
ax1.semilogy(coef_range, err_win, 'b.-', markersize=5, linewidth=1.2,
label=r'$C^\infty$ bump (super-algebraic)')
plot_range = coef_range
ref_cinf = err_win
# Algebraic reference lines anchored at n=5
n_ref = 5
ref_value = ref_cinf[n_ref - 1]
for s, ls in [(4, ':'), (8, '--'), (16, '-.')]:
ref_line = ref_value * (n_ref / plot_range)**s
ax1.semilogy(plot_range, ref_line, color='gray', linestyle=ls, alpha=0.3,
linewidth=0.7, label=f'$O(n^{{-{s}}})$ reference')
# Machine epsilon floor
ax1.axhline(y=2.2e-16, color='red', linestyle=':', alpha=0.5, linewidth=0.8)
ax1.text(plot_range[-1] * 0.6, 5e-16, r'float64 floor',
color='red', fontsize=9, alpha=0.7)
ax1.set_xlabel('Number of Fourier coefficients ($n$)')
ax1.set_ylabel(r'$L^2$ error $\varepsilon_n$ (log scale)')
ax1.set_title(r'Convergence analysis: $f(x) = x$ on $[-1,\,1]$, '
f'$N_{{\\mathrm{{grid}}}} = {N_grid}$')
ax1.legend(loc='upper right', fontsize=9)
ax1.grid(True, which="both", ls="--", alpha=0.3)
ax1.set_xlim(1, plot_range[-1])
fig1.tight_layout()
fig1.savefig(f'{OUTPUT_DIR}/figure_2.pdf')
print(f" -> Saved figure_2.pdf")
# ---- Figure 1b: Effective exponent α_eff ----
if extended_available:
# Compute α_eff from extended high-precision data for the full range
alpha_eff_values = []
alpha_eff_hann_vals = []
n_values_alpha = []
max_n_alpha = N_FOURIER_EXT // 2
for n in range(3, max_n_alpha + 1):
idx_n = n - 1
idx_2n = 2 * n - 1
if idx_2n < N_FOURIER_EXT and mp_cinf[idx_2n] > 0 and mp_cinf[idx_n] > 0:
alpha_w = -np.log(mp_cinf[idx_2n] / mp_cinf[idx_n]) / np.log(2.0)
alpha_h = -np.log(mp_hann[idx_2n] / mp_hann[idx_n]) / np.log(2.0)
alpha_eff_values.append(alpha_w)
alpha_eff_hann_vals.append(alpha_h)
n_values_alpha.append(n)
else:
alpha_eff_values = []
alpha_eff_hann_vals = []
n_values_alpha = []
for n in range(3, 81):
if 2*n <= N_max:
alpha_w = -np.log(err_win[2*n - 1] / err_win[n - 1]) / np.log(2.0)
alpha_h = -np.log(err_hann[2*n - 1] / err_hann[n - 1]) / np.log(2.0)
alpha_eff_values.append(alpha_w)
alpha_eff_hann_vals.append(alpha_h)
n_values_alpha.append(n)
n_alpha = np.array(n_values_alpha)
a_cinf = np.array(alpha_eff_values)
a_hann = np.array(alpha_eff_hann_vals)
fig1b, (ax1b_L, ax1b_R) = plt.subplots(1, 2, figsize=(12, 5),
gridspec_kw={'width_ratios': [1, 1.3]})
# -- Left panel: detail view n = 3 … 20, LINEAR x-axis --
mask_L = n_alpha <= 20
ax1b_L.plot(n_alpha[mask_L], a_cinf[mask_L], 'b.-', markersize=5, linewidth=0.8,
label=r'$C^\infty$ bump')
ax1b_L.plot(n_alpha[mask_L], a_hann[mask_L], 's-', color='#ff7f0e',
markersize=4, linewidth=0.8, label=r'Hann window ($C^1$)')
ax1b_L.set_xlabel('$n$')
ax1b_L.set_ylabel(r'$\alpha_{\rm eff}(n \to 2n)$')
ax1b_L.set_title(r'Detail: $n \leq 20$')
ax1b_L.set_xlim(3, 20)
ax1b_L.set_xticks(range(3, 21, 1))
ax1b_L.grid(True, which='both', ls='--', alpha=0.3)
ax1b_L.legend(fontsize=9, loc='upper left')
# -- Right panel: full range, LOG x-axis --
ax1b_R.semilogx(n_alpha, a_cinf, 'b-', linewidth=0.7,
label=r'$C^\infty$ bump')
ax1b_R.semilogx(n_alpha, a_hann, '-', color='#ff7f0e',
linewidth=0.8, label=r'Hann window ($C^1$)')
ax1b_R.set_xlabel('$n$ (log scale)')
ax1b_R.set_ylabel(r'$\alpha_{\rm eff}(n \to 2n)$')
ax1b_R.set_title(r'Full range: $n = 3 \ldots 2000$')
ax1b_R.grid(True, which='both', ls='--', alpha=0.3)
ax1b_R.legend(fontsize=9, loc='upper left')
fig1b.tight_layout()
fig1b.savefig(f'{OUTPUT_DIR}/figure_3.pdf')
print(f" -> Saved figure_3.pdf")
# Print key values
print(f" Standard error at n=80: {err_std[79]:.4e}")
print(f" Hann error at n=80: {err_hann[79]:.4e}")
print(f" C^inf error at n=80: {err_win[79]:.4e}")
print(f" Standard error at n=160: {err_std[-1]:.4e}")
print(f" Hann error at n=160: {err_hann[-1]:.4e}")
print(f" C^inf error at n=160: {err_win[-1]:.4e}")
print(f" Improvement C^inf vs Std at n=80: {err_std[79]/err_win[79]:.0f}x")
print(f" Improvement C^inf vs Hann at n=80: {err_hann[79]/err_win[79]:.0f}x")
print(f" Improvement C^inf vs Std at n=160: {err_std[-1]/err_win[-1]:.0f}x")
print(f" Improvement C^inf vs Hann at n=160: {err_hann[-1]/err_win[-1]:.0f}x")
# Effective exponent by doubling (wide-ratio estimator)
print(" Effective exponent alpha_eff (C^inf bump, wide-ratio doubling):")
for n1, n2 in [(5, 10), (10, 20), (15, 30), (20, 40), (25, 50), (30, 60), (40, 80), (50, 100), (60, 120), (80, 160)]:
alpha_eff = -np.log(err_win[n2 - 1] / err_win[n1 - 1]) / np.log(2)
print(f" alpha_eff({n1} -> {n2}) = {alpha_eff:.2f}")
# Point-to-point exponent (staircase analysis, cf. Remark in paper)
print(" Point-to-point alpha_loc (staircase structure diagnostic):")
print(f" {'n':>4s} {'alpha_loc':>10s} {'eps_n':>12s}")
for n in range(5, 160):
alpha_loc = -np.log(err_win[n] / err_win[n - 1]) / np.log((n + 1) / n)
if n in [10, 17, 20, 30, 34, 44, 50, 63, 68] or alpha_loc < 0.5 or alpha_loc > 10:
print(f" {n:4d} {alpha_loc:10.2f} {err_win[n - 1]:12.4e} {'<-- plateau' if alpha_loc < 1 else ('<-- peak' if alpha_loc > 10 else '')}")
# --- Additional test functions (universality verification, cf. Section 4.2) ---
print(" Additional test functions (C^inf degenerate bump, n=80):")
additional_tests = {
'Gaussian exp(-x^2)': np.exp(-x_1D**2),
'sin(5*pi*x)': np.sin(5.0 * np.pi * x_1D),
'Runge 1/(1+25x^2)': 1.0 / (1.0 + 25.0 * x_1D**2),
}
for name, f_test in additional_tests.items():
fw_test = f_test * bump_degen
approx_test_80 = fourier_truncation(fw_test, 80)
approx_test_160 = fourier_truncation(fw_test, 160)
eps_test_80 = np.sqrt(np.sum(np.abs(fw_test - approx_test_80)**2) * dx_1)
eps_test_160 = np.sqrt(np.sum(np.abs(fw_test - approx_test_160)**2) * dx_1)
print(f" {name:25s}: eps_80 = {eps_test_80:.2e}, eps_160 = {eps_test_160:.2e}")
# ---- Figure 0: Gibbs suppression visualization (Section 4.1) ----
n_gibbs = 20 # Moderate n to make Gibbs oscillations clearly visible
approx_std_gibbs = fourier_truncation(f_x, n_gibbs)
approx_win_gibbs = fourier_truncation(f_windowed, n_gibbs)
fig0, (ax0a, ax0b) = plt.subplots(1, 2, figsize=(12, 5), sharey=True)
# Left panel: standard truncation (with Gibbs)
ax0a.plot(x_1D, f_x, 'k-', linewidth=1.5, label=r'$f(x) = x$')
ax0a.plot(x_1D, approx_std_gibbs, 'r-', linewidth=1.2,
label=rf'$S_{{{n_gibbs}}} f(x)$ (standard)')
ax0a.set_xlabel('$x$')
ax0a.set_ylabel('Function value')
ax0a.set_title(rf'Standard truncation ($n = {n_gibbs}$)')
ax0a.legend(loc='upper left')
ax0a.grid(True, ls='--', alpha=0.4)
ax0a.set_xlim(-1.05, 1.05)
# Right panel: windowed truncation (no Gibbs)
ax0b.plot(x_1D, f_windowed, 'k--', linewidth=1.5,
label=r'$f_w(x) = f(x)\,\varphi(x)$')
ax0b.plot(x_1D, approx_win_gibbs, 'b-', linewidth=1.2,
label=rf'$S_{{{n_gibbs}}} f_w(x)$ ($C^\infty$ window)')
ax0b.set_xlabel('$x$')
ax0b.set_title(rf'$C^\infty$-windowed truncation ($n = {n_gibbs}$)')
ax0b.legend(loc='upper left')
ax0b.grid(True, ls='--', alpha=0.4)
ax0b.set_xlim(-1.05, 1.05)
fig0.tight_layout()
fig0.savefig(f'{OUTPUT_DIR}/figure_1.pdf')
print(f" -> Saved figure_1.pdf")
# =========================================================================
# EXPERIMENT 2: SCHRODINGER EQUATION (WAVE PACKET ABSORPTION)
# =========================================================================
print()
print("=" * 72)
print("EXPERIMENT 2: Schrodinger Wave Packet Dynamics")
print("=" * 72)
L = 10.0
N = 1024
x = np.linspace(-L, L, N, endpoint=False)
dx = x[1] - x[0]
k = np.fft.fftfreq(N, d=dx) * 2 * np.pi
dt = 0.005
steps = 180
T_final = dt * steps
# Initial Gaussian wave packet
x0, p0, sigma = -5.0, 15.0, 1.0
psi_0 = np.exp(-(x - x0)**2 / (2 * sigma**2)) * np.exp(1j * p0 * x)
psi_0 /= np.sqrt(np.sum(np.abs(psi_0)**2 * dx))
# Kinetic propagator
T_evol = np.exp(-1j * (k**2) / 2 * dt)
# Absorbing window
eta = 0.15
window = absorbing_boundary_window(x, L, width_fraction=eta)
rho_boundary = (1.0 - eta) * L
# Time evolution -- track norm at every step
psi_std = psi_0.copy()
psi_win = psi_0.copy()
norm_std_history = np.zeros(steps + 1)
norm_win_history = np.zeros(steps + 1)
norm_std_history[0] = np.sum(np.abs(psi_0)**2) * dx
norm_win_history[0] = norm_std_history[0]
t_start = timer.perf_counter()
for step in range(steps):
# Standard method
psi_std = np.fft.ifft(np.fft.fft(psi_std) * T_evol)
# Windowed method
psi_win = np.fft.ifft(np.fft.fft(psi_win) * T_evol)
psi_win = psi_win * window
norm_std_history[step + 1] = np.sum(np.abs(psi_std)**2) * dx
norm_win_history[step + 1] = np.sum(np.abs(psi_win)**2) * dx
t_elapsed = timer.perf_counter() - t_start
print(f" Domain: [-{L}, {L}], N={N}, dx={dx:.6f}")
print(f" dt={dt}, steps={steps}, T_final={T_final:.3f}")
print(f" Initial: x0={x0}, p0={p0}, sigma={sigma}")
print(f" Group velocity: v_g = {p0}, expected center at T: {x0 + p0*T_final:.1f}")
print(f" Absorbing layer: eta={eta}, plateau=[-{rho_boundary}, {rho_boundary}]")
print(f" Elapsed wall time: {t_elapsed:.3f} s")
# Quantitative diagnostics
norm_final_std = norm_std_history[-1]
norm_final_win = norm_win_history[-1]
left_density_std = np.sum(np.abs(psi_std[x < 0])**2) * dx
left_density_win = np.sum(np.abs(psi_win[x < 0])**2) * dx
peak_std = np.max(np.abs(psi_std)**2)
peak_win = np.max(np.abs(psi_win)**2)
peak_pos_std = x[np.argmax(np.abs(psi_std)**2)]
peak_pos_win = x[np.argmax(np.abs(psi_win)**2)]
print(f" Norm (standard): {norm_final_std:.6f}")
print(f" Norm (windowed): {norm_final_win:.6f} (absorbed {(1-norm_final_win)*100:.1f}%)")
print(f" Density in x<0 (standard): {left_density_std:.4e}")
print(f" Density in x<0 (windowed): {left_density_win:.2e}")
print(f" Suppression ratio: {left_density_std / (left_density_win + 1e-30):.2e}")
print(f" Peak |psi|^2 (std): {peak_std:.4f} at x={peak_pos_std:.2f}")
print(f" Peak |psi|^2 (win): {peak_win:.4f} at x={peak_pos_win:.2f}")
# Conditional observable: <x>_rho
rho_obs = rho_boundary
mask_rho = np.abs(x) <= rho_obs
psi_rho = psi_win[mask_rho]
x_rho = x[mask_rho]
norm_rho = np.sum(np.abs(psi_rho)**2) * dx
if norm_rho > 1e-10:
x_mean_rho = np.sum(x_rho * np.abs(psi_rho)**2) * dx / norm_rho
else:
x_mean_rho = 0.0
x_c_analytical = x0 + p0 * T_final
print(f" Conditional observable <x>_rho (|x|<={rho_obs:.2f}): {x_mean_rho:.4f}")
print(f" Analytical x_c(T) = x0 + p0*T: {x_c_analytical:.4f}")
# ---- Probability budget verification ----
# Verifies that the discrepancy P_out(T) - (1 - ||psi^M||^2) is accounted
# for by the transition-layer norm, closing the probability budget exactly.
sigma_T = sigma * np.sqrt(1.0 + T_final**2 / sigma**4)
x_c_T = x0 + p0 * T_final
# Note: sigma_T is the width parameter of psi, not the std dev of |psi|^2.
# Since |psi|^2 ~ exp(-(x-xc)^2 / sigma_T^2), its variance is sigma_T^2/2,
# and the erf denominator sigma_x*sqrt(2) = (sigma_T/sqrt(2))*sqrt(2) = sigma_T.
P_in_exact = 0.5 * (erf((rho_boundary - x_c_T) / sigma_T)
- erf((-rho_boundary - x_c_T) / sigma_T))
P_out_exact = 1.0 - P_in_exact
P_domain_L = 0.5 * (erf((L - x_c_T) / sigma_T)
- erf((-L - x_c_T) / sigma_T))
P_trans_exact = P_domain_L - P_in_exact
mask_transition = (np.abs(x) > rho_boundary) & (np.abs(x) < L)
norm_transition = np.sum(np.abs(psi_win[mask_transition])**2) * dx
absorbed_frac = 1.0 - norm_final_win
discrepancy_22 = P_out_exact - absorbed_frac
print()
print(" Probability budget verification:")
print(f" P_out(T) exact = {P_out_exact:.6f}")
print(f" Absorbed = 1 - ||psi^M||^2 = {absorbed_frac:.6f}")
print(f" Discrepancy P_out - absorbed = {discrepancy_22:.6f}")
print(f" Transition-layer norm = {norm_transition:.6f}")
print(f" Plateau norm = {norm_rho:.6f}")
print(f" Budget: absorbed + trans + plateau = {absorbed_frac + norm_transition + norm_rho:.6f}")
print(f" P_trans exact (unwindowed) = {P_trans_exact:.6f}")
print(f" Attenuation ratio (trans/exact) = {norm_transition/P_trans_exact:.4f}")
# Spatial convergence study with varying N (from 256 to 4096)
print(" Spatial convergence study (fixed p0=15.0):")
print(f" {'N':>6s} {'Final norm':>12s} {'Density x<0':>14s}")
print(" " + "-" * 36)
for N_test in [256, 512, 1024, 2048, 4096]:
x_test = np.linspace(-L, L, N_test, endpoint=False)
dx_test = x_test[1] - x_test[0]
k_test = np.fft.fftfreq(N_test, d=dx_test) * 2 * np.pi
T_evol_test = np.exp(-1j * (k_test**2) / 2 * dt)
win_test = absorbing_boundary_window(x_test, L, width_fraction=eta)
psi_test = np.exp(-(x_test - x0)**2 / (2 * sigma**2)) * np.exp(1j * p0 * x_test)
psi_test /= np.sqrt(np.sum(np.abs(psi_test)**2 * dx_test))
for step in range(steps):
psi_test = np.fft.ifft(np.fft.fft(psi_test) * T_evol_test)
psi_test = psi_test * win_test
norm_test = np.sum(np.abs(psi_test)**2) * dx_test
left_test = np.sum(np.abs(psi_test[x_test < 0])**2) * dx_test
print(f" {N_test:6d} {norm_test:12.4f} {left_test:14.2e}")
# Additional spatial convergence with higher momentum (p0 = 25)
print(" Spatial convergence with p0 = 25 (higher momentum):")
p0_high = 25.0
psi_0_high = np.exp(-(x - x0)**2 / (2 * sigma**2)) * np.exp(1j * p0_high * x)
psi_0_high /= np.sqrt(np.sum(np.abs(psi_0_high)**2 * dx))
T_final_high = 0.9
steps_high = int(round(T_final_high / dt))
print(f" {'N':>6s} {'Final norm':>12s} {'Density x<0':>14s}")
print(" " + "-" * 36)
for N_test in [256, 512, 1024, 2048, 4096]:
x_test = np.linspace(-L, L, N_test, endpoint=False)
dx_test = x_test[1] - x_test[0]
k_test = np.fft.fftfreq(N_test, d=dx_test) * 2 * np.pi
T_evol_test = np.exp(-1j * (k_test**2) / 2 * dt)
win_test = absorbing_boundary_window(x_test, L, width_fraction=eta)
psi_test = np.exp(-(x_test - x0)**2 / (2 * sigma**2)) * np.exp(1j * p0_high * x_test)
psi_test /= np.sqrt(np.sum(np.abs(psi_test)**2 * dx_test))
for step in range(steps_high):
psi_test = np.fft.ifft(np.fft.fft(psi_test) * T_evol_test)
psi_test = psi_test * win_test
norm_test = np.sum(np.abs(psi_test)**2) * dx_test
left_test = np.sum(np.abs(psi_test[x_test < 0])**2) * dx_test
print(f" {N_test:6d} {norm_test:12.4f} {left_test:14.2e}")
# High-momentum spatial convergence table (Table 2 format)
print(" High-momentum (p0=25) spatial convergence table:")
print(f" {'N':>6s} {'Final norm':>12s} {'Density x<0':>14s} {'Convergence':>14s}")
print(" " + "-" * 50)
prev_left = None
for N_test in [256, 512, 1024, 2048, 4096]:
x_test = np.linspace(-L, L, N_test, endpoint=False)
dx_test = x_test[1] - x_test[0]
k_test = np.fft.fftfreq(N_test, d=dx_test) * 2 * np.pi
T_evol_test = np.exp(-1j * (k_test**2) / 2 * dt)
win_test = absorbing_boundary_window(x_test, L, width_fraction=eta)
psi_test = np.exp(-(x_test - x0)**2 / (2 * sigma**2)) * np.exp(1j * p0_high * x_test)
psi_test /= np.sqrt(np.sum(np.abs(psi_test)**2 * dx_test))
for step in range(steps_high):
psi_test = np.fft.ifft(np.fft.fft(psi_test) * T_evol_test)
psi_test = psi_test * win_test
norm_test = np.sum(np.abs(psi_test)**2) * dx_test
left_test = np.sum(np.abs(psi_test[x_test < 0])**2) * dx_test
if prev_left is not None and left_test > 1e-15:
ratio_str = f"{prev_left / left_test:.1f}x"
else:
ratio_str = "---"
print(f" {N_test:6d} {norm_test:12.4f} {left_test:14.2e} {ratio_str:>14s}")
prev_left = left_test
# ---- Error floor decomposition (Remark in paper) ----
print()
print(" Error floor decomposition (eta=0.15, p0=15, T=0.9):")
sigma_T = sigma * np.sqrt(1 + (T_final / sigma**2)**2)
x_center = x0 + p0 * T_final
z_erfc = x_center / sigma_T
P_tail = 0.5 * math.erfc(z_erfc)
eps_dp = np.finfo(float).eps
roundoff = N * steps * eps_dp**2
print(f" Gaussian tail P(x<0) = erfc({z_erfc:.2f})/2 = {P_tail:.2e}")
print(f" Round-off bound N*M*eps^2 = {roundoff:.2e}")
print(f" Measured floor = {left_density_win:.2e}")
print(f" => Floor dominated by accumulated discrete Fourier leakage")
print()
print(" eta-sweep (sensitivity analysis, Table eta_sensitivity):")
print(f" {'eta':>6s} {'rho':>6s} {'density x<0':>14s} {'norm':>8s} {'suppression':>14s}")
print(" " + "-" * 60)
left_ref = np.sum(np.abs(psi_std[x < 0])**2) * dx
for eta_diag in [0.05, 0.08, 0.10, 0.12, 0.15, 0.18, 0.20, 0.25, 0.30]:
win_diag = absorbing_boundary_window(x, L, width_fraction=eta_diag)
psi_diag = np.exp(-(x - x0)**2 / (2 * sigma**2)) * np.exp(1j * p0 * x)
psi_diag /= np.sqrt(np.sum(np.abs(psi_diag)**2) * dx)
for step in range(steps):
psi_diag = np.fft.ifft(np.fft.fft(psi_diag) * T_evol)
psi_diag = psi_diag * win_diag
norm_diag = np.sum(np.abs(psi_diag)**2) * dx
left_diag = np.sum(np.abs(psi_diag[x < 0])**2) * dx
rho_diag = (1.0 - eta_diag) * L
supp = left_ref / left_diag if left_diag > 0 else float('inf')
print(f" {eta_diag:6.2f} {rho_diag:6.1f} {left_diag:14.3e} {norm_diag:8.4f} {supp:14.2e}")
# ---- Figure 2: Schrodinger comparison ----
fig2, (ax2a, ax2b) = plt.subplots(1, 2, figsize=(13, 5.5), sharey=True)
ax2a.plot(x, np.abs(psi_0)**2, 'k--', alpha=0.5, linewidth=1, label=r'$|\psi(x,0)|^2$')
ax2a.plot(x, np.abs(psi_std)**2, 'r-', linewidth=1.8, label=r'$|\psi(x,T)|^2$ (standard FFT)')
ax2a.set_title('Standard FFT: wrap-around error')
ax2a.set_xlabel('$x$')
ax2a.set_ylabel(r'Probability density $|\psi|^2$')
ax2a.legend(loc='upper left')
ax2a.grid(True, alpha=0.3)
ax2b.plot(x, np.abs(psi_0)**2, 'k--', alpha=0.5, linewidth=1, label=r'$|\psi(x,0)|^2$')
ax2b.plot(x, np.abs(psi_win)**2, 'b-', linewidth=1.8, label=r'$|\psi(x,T)|^2$ (windowed)')
ax2b.plot(x, window, 'g:', linewidth=1.5, alpha=0.7, label=r'$\mathcal{W}(x)$ absorbing window')
ax2b.axvline(rho_boundary, color='gray', ls='--', alpha=0.4, linewidth=0.8)
ax2b.axvline(-rho_boundary, color='gray', ls='--', alpha=0.4, linewidth=0.8)
ax2b.set_title(r'Proposed: $C^\infty$ windowed FFT')
ax2b.set_xlabel('$x$')
ax2b.legend(loc='upper left')
ax2b.grid(True, alpha=0.3)
fig2.suptitle(
rf'Free-particle TDSE on $[-{L:.0f},\,{L:.0f}]$, $N={N}$, '
rf'$T={T_final}$, $\eta={eta}$',
fontsize=14, y=1.02)
fig2.tight_layout()
fig2.savefig(f'{OUTPUT_DIR}/figure_4.pdf')
print(f" -> Saved figure_4.pdf")
# ---- Figure 3: Norm evolution over time with analytical reference ----
time_axis = np.linspace(0, T_final, steps + 1)
# Compute analytical P_in(t)
time_analytical = np.linspace(0, T_final, 500)
P_in_analytical = np.zeros_like(time_analytical)
for i, t in enumerate(time_analytical):
sigma_t = sigma * np.sqrt(1.0 + (t**2) / (sigma**4))
x_c_t = x0 + p0 * t
erf_plus = erf((rho_boundary - x_c_t) / sigma_t)
erf_minus = erf((-rho_boundary - x_c_t) / sigma_t)
P_in_analytical[i] = 0.5 * (erf_plus - erf_minus)
fig3, ax3 = plt.subplots(figsize=(8, 5))
ax3.plot(time_axis, norm_std_history, 'r-', linewidth=1.5,
label='Standard FFT (norm conserved — includes wrap-around)')
ax3.plot(time_axis, norm_win_history, 'b-', linewidth=1.5,
label=r'$C^\infty$-windowed (norm decreases — physical absorption)')
ax3.plot(time_analytical, P_in_analytical, 'g--', linewidth=1.5,
label='Analytical: probability within plateau')
ax3.axhline(1.0, color='gray', ls=':', alpha=0.5)
ax3.set_xlabel('Time $t$')
ax3.set_ylabel(r'$\|\psi(t)\|^2$')
ax3.set_title('Norm evolution: unitarity vs. physical absorption')
ax3.legend()
ax3.set_ylim(0.0, 1.1)
ax3.grid(True, alpha=0.3)
fig3.tight_layout()
fig3.savefig(f'{OUTPUT_DIR}/figure_5.pdf')
print(f" -> Saved figure_5.pdf")
# =========================================================================
# EXPERIMENT 3: CONVERGENCE WITH PLATEAU BUMP (varying rho/lambda)
# -- Quantifies the effect of the plateau parameter on L2 error
# -- Aligns with Bergold & Lasser Theorem 4.6 (Lipschitz constant bound)
# =========================================================================
print()
print("=" * 72)
print("EXPERIMENT 3: Convergence with plateau bump — varying rho")
print("=" * 72)
N_grid_3 = 2000
lam_3 = 1.0 # Half-domain for Experiment 3
x_3 = np.linspace(-lam_3, lam_3, N_grid_3, endpoint=False)
dx_3 = 2.0 * lam_3 / N_grid_3 # Grid spacing
f_3 = x_3.copy() # Same test function f(x) = x
N_max_3 = 80
coef_range_3 = np.arange(1, N_max_3 + 1)
# Finer rho sweep (MODIFIED)
rho_values = [0.0, 0.30, 0.50, 0.60, 0.70, 0.85]
colors_rho = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#d62728']
labels_rho = [
r'$\rho = 0.00$ (degenerate)',
r'$\rho = 0.30$',
r'$\rho = 0.50$',
r'$\rho = 0.60$',
r'$\rho = 0.70$',
r'$\rho = 0.85$',
]
errors_by_rho = {}
plateau_errors_by_rho = {} # Full arrays for plotting
plateau_errors = {} # Scalar (n=80) for backward compat
for rho_val in rho_values:
w = plateau_bump_function(x_3, rho_val)
fw = f_3 * w
errs = np.zeros(N_max_3)
for i, n in enumerate(coef_range_3):
approx = fourier_truncation(fw, n)
errs[i] = np.sqrt(np.sum(np.abs(fw - approx)**2) * dx_3)
errors_by_rho[rho_val] = errs
print(f" rho={rho_val:.2f}: error at n=80 = {errs[-1]:.4e}")
# Compute plateau-restricted error for non-zero rho
if rho_val > 0:
mask_plat = np.abs(x_3) <= rho_val
errs_plat = np.zeros(N_max_3)
for i, n in enumerate(coef_range_3):
approx = fourier_truncation(fw, n)
# On the plateau f_w = f since w=1, so measure |f - approx|
errs_plat[i] = np.sqrt(np.sum(np.abs(f_3[mask_plat] - approx[mask_plat])**2) * dx_3)
plateau_errors_by_rho[rho_val] = errs_plat
plateau_errors[rho_val] = errs_plat[-1]
print(f" -> plateau error at n=80 = {errs_plat[-1]:.4e}")
# Also include the unwindowed (standard) case for reference
errs_unwound = np.zeros(N_max_3)
for i, n in enumerate(coef_range_3):
approx = fourier_truncation(f_3, n)
errs_unwound[i] = np.sqrt(np.sum(np.abs(f_3 - approx)**2) * dx_3)
# ---- Figure 4: Convergence vs rho (finer sweep) ----
fig4, ax4 = plt.subplots(figsize=(9, 6))
ax4.semilogy(coef_range_3, errs_unwound, 'k--', linewidth=1.0, alpha=0.6,
label='No window (algebraic)')
for rho_val, color, lbl in zip(rho_values, colors_rho, labels_rho):
ax4.semilogy(coef_range_3, errors_by_rho[rho_val], '.-', color=color,
markersize=3, linewidth=1.2, label=lbl)
# Overlay plateau-restricted error as dashed line (for rho > 0)
if rho_val in plateau_errors_by_rho:
ax4.semilogy(coef_range_3, plateau_errors_by_rho[rho_val], '--',
color=color, linewidth=1.0, alpha=0.7)
# Add a manual legend entry for dashed = plateau-restricted
from matplotlib.lines import Line2D
legend_elements = ax4.get_legend_handles_labels()
ax4.plot([], [], '--', color='gray', linewidth=1.0, alpha=0.7,
label=r'Plateau-restricted $\varepsilon_n^{\mathrm{plat}}$')
ax4.set_xlabel('Number of Fourier coefficients ($n$)')
ax4.set_ylabel(r'$L^2$ error $\varepsilon_n$ (log scale)')
ax4.set_title(r'Effect of plateau parameter $\rho$ on convergence rate')
ax4.legend(fontsize=8)
ax4.grid(True, which="both", ls="--", alpha=0.4)
fig4.tight_layout()
fig4.savefig(f'{OUTPUT_DIR}/figure_6.pdf')
print(f" -> Saved figure_6.pdf")
# =========================================================================
# EXPERIMENT 4: WINDOW COMPARISON (Hann vs Tukey vs C^inf bump)
# -- Compares different window regularities on the Schrodinger problem
# =========================================================================
print()
print("=" * 72)
print("EXPERIMENT 4: Window comparison (Hann / Tukey / C^inf bump)")
print("=" * 72)
def hann_window(x: np.ndarray, L: float) -> np.ndarray:
"""Hann window on [-L, L] -- degenerate C1-bump (rho = 0)."""
xi = np.abs(x / L)
w = np.zeros_like(xi)
mask = xi < 1.0
w[mask] = 0.5 * (1.0 + np.cos(np.pi * xi[mask]))
return w
def tukey_window(x: np.ndarray, L: float, alpha: float = 0.3) -> np.ndarray:
"""Tukey window on [-L, L] -- non-degenerate C1-bump, plateau rho = (1-alpha)*L."""
xi = np.abs(x / L)
w = np.ones_like(xi)
mask = xi > (1.0 - alpha)
z = (xi[mask] - (1.0 - alpha)) / alpha
w[mask] = 0.5 * (1.0 + np.cos(np.pi * z))
w[xi >= 1.0] = 0.0
return w
windows = {
'Hann ($C^1$, degenerate)': hann_window(x, L),
'Tukey ($C^1$, $\\alpha=0.3$)': tukey_window(x, L, alpha=0.3),
r'$C^\infty$ bump ($\eta=0.15$)': absorbing_boundary_window(x, L, width_fraction=0.15),
}
window_colors = ['#ff7f0e', '#2ca02c', '#1f77b4']
# Run Schrodinger simulation for each window
results_windows = {}
for (name, w), color in zip(windows.items(), window_colors):
psi = psi_0.copy()
norms = np.zeros(steps + 1)
norms[0] = np.sum(np.abs(psi)**2) * dx
for step in range(steps):
psi = np.fft.ifft(np.fft.fft(psi) * T_evol)
psi = psi * w
norms[step + 1] = np.sum(np.abs(psi)**2) * dx
left_dens = np.sum(np.abs(psi[x < 0])**2) * dx
results_windows[name] = {
'psi_final': psi,
'norms': norms,
'left_density': left_dens,
'color': color,
}
print(f" {name}:")
print(f" Final norm = {norms[-1]:.6f}, density x<0 = {left_dens:.2e}")
# ---- Figure 5: Window comparison ----
fig5 = plt.figure(figsize=(14, 10))
gs = GridSpec(2, 2, figure=fig5, hspace=0.35, wspace=0.30)
# Panel (a): Window profiles
ax5a = fig5.add_subplot(gs[0, 0])