-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBallooning.jl
More file actions
1269 lines (1084 loc) · 46.7 KB
/
Copy pathBallooning.jl
File metadata and controls
1269 lines (1084 loc) · 46.7 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
# ======================================================================
# Main Driver for Ballooning Stability Analysis
# Computes ballooning stability criterion over all flux surfaces
# ======================================================================
const BALLOONING_THETA_MAX_CAP = 16.5
const BALLOONING_THETA_SCALE_MULTIPLIER = 10.0
const MATCHING_POINT = 1e-3
# Default ψ_N window for the α-boundary scan drivers: ballooning boundaries matter in the
# mid-radius and pedestal; the packed axis and far-edge surfaces only add scan cost.
const BALLOONING_SCAN_PSI_WINDOW = (0.1, 0.99)
# Effective window [0.1, min(0.99, ψ_edge)]; the grid never extends past psihigh/psi_edge.
_in_ballooning_scan_window(psi::Float64, psi_edge::Float64) =
BALLOONING_SCAN_PSI_WINDOW[1] <= psi <= min(BALLOONING_SCAN_PSI_WINDOW[2], psi_edge)
"""
compute_ballooning_stability!(locstab_fs, plasma_eq)
Main driver routine for local high-n stability analysis. Iterates over all
magnetic flux surfaces, prepares ballooning coefficients, stores `det(d0bar)`
as the local `Di` diagnostic, and optionally integrates the ballooning equation
to compute Delta Prime.
## Arguments
- `locstab_fs::Matrix{Float64}`: Local stability matrix to store results (modified in place).
- `plasma_eq::Equilibrium.PlasmaEquilibrium`: Plasma equilibrium data.
- `verbose::Bool`: Print progress messages.
This function modifies `locstab_fs` in place with:
- Column 1: `det(d0bar) * ψ` (Mercier interchange `D_I`)
- Column 2: resistive interchange `D_R * ψ`, using `det(d0bar)` for `D_I`
and the surface-average route for `H` (see [`resistive_interchange_h`](@ref))
- Column 4: Delta Prime (Δ')
"""
function compute_ballooning_stability!(
locstab_fs::Matrix{Float64},
plasma_eq::Equilibrium.PlasmaEquilibrium;
theta_k::Float64=0.0,
compute_delta_prime::Bool=true,
verbose::Bool=false
)
if verbose
println("Evaluating local high-n ballooning stability...")
end
num_psi = length(plasma_eq.profiles.xs)
# Parallelism is governed by the Julia thread count (`julia -t N`); with one thread this runs serially.
# All data is thread-local, so no locks are needed. The `:greedy` scheduling strategy
# outperforms `:static` and `:dynamic` for this workload in testing.
Threads.@threads :greedy for flux_surface_index in 1:num_psi
psi = plasma_eq.profiles.xs[flux_surface_index]
coeff_data = prepare_ballooning_coefficients(flux_surface_index, plasma_eq; theta_k=theta_k)
h = resistive_interchange_h(flux_surface_index, plasma_eq)
locstab_fs[flux_surface_index, 1] = coeff_data.di * psi
# Keep D_R tied to the reported D_I. The surface-average route provides H.
locstab_fs[flux_surface_index, 2] = (coeff_data.di + (h - 0.5)^2) * psi
if compute_delta_prime && plasma_eq.profiles.xs[flux_surface_index] <= 1.0
result = integrate_ballooning_ode(
coeff_data.ode_coefficient_spline;
theta_k=theta_k
)
locstab_fs[flux_surface_index, 4] = result.value
end
end
if verbose
println("Ballooning analysis complete.")
end
end
"""
compute_local_stability(plasma_eq; verbose=false) -> CubicSeriesInterpolant
Local stability profile spline over `plasma_eq.profiles.xs`, with the columns filled by
[`compute_ballooning_stability!`](@ref): 1 = `D_I·ψ`, 2 = `D_R·ψ`, 4 = ballooning `Δ'`.
"""
function compute_local_stability(plasma_eq::Equilibrium.PlasmaEquilibrium; verbose::Bool=false)
xs = plasma_eq.profiles.xs
locstab_fs = zeros(Float64, length(xs), 5)
compute_ballooning_stability!(locstab_fs, plasma_eq; verbose=verbose)
return cubic_interp(xs, Series(locstab_fs); extrap=ExtendExtrap())
end
"""
resistive_interchange_h(flux_surface_index, plasma_eq)
Resistive interchange helper for `D_R = D_I + (H - 1/2)²` at a single
flux surface [Glasser-Greene-Johnson; Glasser Phys. Plasmas 23, 112506
(2016)]. The intermediate `H` is formed from flux-surface averages of the
field and metric quantities.
The main local-stability scan takes `D_I` from the `det(d0bar)` calculation
reported as `LocalStability/di`, then combines it with this surface-average `H` to
form `LocalStability/dr`. This avoids recomputing a separate surface-average `D_I`
inside the `D_R` path.
"""
function resistive_interchange_h(flux_surface_index::Int, plasma_eq::Equilibrium.PlasmaEquilibrium)
profiles = plasma_eq.profiles
ntheta = length(plasma_eq.rzphi_ys)
ff_fs = zeros(ntheta, 3)
psi = profiles.xs[flux_surface_index]
twopif = profiles.F_spline.y[flux_surface_index]
p1 = profiles.P_deriv(psi)
v1 = profiles.dVdpsi_spline.y[flux_surface_index]
q = profiles.q_spline.y[flux_surface_index]
q1 = profiles.q_deriv(psi)
chi1 = 2π * plasma_eq.psio
for itheta in 1:ntheta
theta = plasma_eq.rzphi_ys[itheta]
f1 = plasma_eq.rzphi_rsquared.nodal_derivs.partials[1, flux_surface_index, itheta]
f2 = plasma_eq.rzphi_offset.nodal_derivs.partials[1, flux_surface_index, itheta]
jac = plasma_eq.rzphi_jac.nodal_derivs.partials[1, flux_surface_index, itheta]
fy1 = plasma_eq.rzphi_rsquared.nodal_derivs.partials[3, flux_surface_index, itheta]
fy2 = plasma_eq.rzphi_offset.nodal_derivs.partials[3, flux_surface_index, itheta]
fy3 = plasma_eq.rzphi_nu.nodal_derivs.partials[3, flux_surface_index, itheta]
rfac = sqrt(f1)
eta = 2π * (theta + f2)
r = plasma_eq.ro + rfac * cos(eta)
v21 = fy1 / (2.0 * rfac * jac)
v22 = (1.0 + fy2) * 2π * rfac / jac
v23 = fy3 * r / jac
v33 = 2π * r / jac
bsq = chi1^2 * (v21^2 + v22^2 + (v23 + q * v33)^2)
dpsisq = (2π * r)^2 * (v21^2 + v22^2)
ff_fs[itheta, 1] = bsq / dpsisq
ff_fs[itheta, 2] = 1.0 / dpsisq
ff_fs[itheta, 3] = bsq
@views ff_fs[itheta, :] .*= jac / v1
end
avg = FastInterpolations.integrate(cubic_interp(plasma_eq.rzphi_ys, Series(ff_fs); bc=PeriodicBC()))
return twopif * p1 * v1 / (q1 * chi1^3) * (avg[2] - avg[1] / avg[3])
end
function _collect_surface_response_background(
flux_surface_index::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium,
theta_grid::AbstractVector{<:Real}
)::NamedTuple
profiles = plasma_eq.profiles
theta_vals = Float64.(theta_grid)
ntheta = length(theta_vals)
psi0 = profiles.xs[flux_surface_index]
q0 = Float64(profiles.q_spline.y[flux_surface_index])
q0prime = Float64(profiles.q_deriv(psi0))
p0prime = Float64(profiles.P_deriv(psi0))
two_pi_f0 = Float64(profiles.F_spline.y[flux_surface_index])
chi_prime0 = Float64(2pi * plasma_eq.psio)
f0 = zeros(ntheta, 4)
fx0 = zeros(ntheta, 4)
fy0 = zeros(ntheta, 4)
fxy0 = zeros(ntheta, 4)
rho0 = zeros(ntheta)
eta0 = zeros(ntheta)
r0 = zeros(ntheta)
gradpsi_sq0 = zeros(ntheta)
h_theta0 = zeros(ntheta)
C_theta = zeros(ntheta)
Iper0 = zeros(ntheta)
kappas0 = zeros(ntheta)
bsq0 = zeros(ntheta)
jac0 = zeros(ntheta)
bdot_theta_phi0 = zeros(ntheta)
v0 = zeros(ntheta, 3, 3)
v_zeta_psi0 = zeros(ntheta, 3)
v_psi_theta0 = zeros(ntheta, 3)
rz = (
plasma_eq.rzphi_rsquared,
plasma_eq.rzphi_offset,
plasma_eq.rzphi_nu,
plasma_eq.rzphi_jac
)
for i in eachindex(theta_vals)
theta = theta_vals[i]
f = ntuple(k -> rz[k].nodal_derivs.partials[1, flux_surface_index, i], 4)
fx = ntuple(k -> rz[k].nodal_derivs.partials[2, flux_surface_index, i], 4)
fy = ntuple(k -> rz[k].nodal_derivs.partials[3, flux_surface_index, i], 4)
fxy = ntuple(k -> rz[k].nodal_derivs.partials[4, flux_surface_index, i], 4)
rho = sqrt(f[1])
eta = 2pi * (theta + f[2])
ceta = cos(eta)
seta = sin(eta)
r = plasma_eq.ro + rho * ceta
jac = f[4]
rho_psi = fx[1] / (2 * rho)
rho_theta = fy[1] / (2 * rho)
rho_psitheta = fxy[1] / (2 * rho) - fx[1] * fy[1] / (4 * f[1] * rho)
eta_psi = 2pi * fx[2]
eta_theta = 2pi * (1 + fy[2])
eta_psitheta = 2pi * fxy[2]
Rpsi = rho_psi * ceta - rho * seta * eta_psi
Rtheta = rho_theta * ceta - rho * seta * eta_theta
Zpsi = rho_psi * seta + rho * ceta * eta_psi
Ztheta = rho_theta * seta + rho * ceta * eta_theta
Rpsitheta =
rho_psitheta * ceta -
rho_psi * seta * eta_theta -
rho_theta * seta * eta_psi -
rho * ceta * eta_psi * eta_theta -
rho * seta * eta_psitheta
Zpsitheta =
rho_psitheta * seta +
rho_psi * ceta * eta_theta +
rho_theta * ceta * eta_psi -
rho * seta * eta_psi * eta_theta +
rho * ceta * eta_psitheta
v = zeros(3, 3)
v[1, 1] = fx[1] / (2 * rho * jac)
v[1, 2] = fx[2] * 2pi * rho / jac
v[1, 3] = fx[3] * r / jac
v[2, 1] = fy[1] / (2 * rho * jac)
v[2, 2] = (1 + fy[2]) * 2pi * rho / jac
v[2, 3] = fy[3] * r / jac
v[3, 3] = 2pi * r / jac
w = zeros(3, 3)
w[1, 1] = (1 + fy[2]) * (2pi)^2 * rho * r / jac
w[1, 2] = -fy[1] * pi * r / (rho * jac)
w[2, 1] = -fx[2] * (2pi)^2 * r * rho / jac
w[2, 2] = fx[1] * pi * r / (rho * jac)
w[3, 1] = (fx[2] * fy[3] - fx[3] * (1 + fy[2])) * 2pi * r * rho / jac
w[3, 2] = (fx[3] * fy[1] - fx[1] * fy[3]) * r / (2 * rho * jac)
w[3, 3] = 1 / (2pi * r)
grad_psi = Vector(@view w[1, :])
grad_theta = Vector(@view w[2, :])
grad_zeta = Vector(@view w[3, :])
v_theta_zeta = Vector(@view v[1, :])
v_zeta_psi = Vector(@view v[2, :])
v_psi_theta = Vector(@view v[3, :])
B_vec = (v_zeta_psi + q0 .* v_psi_theta) * chi_prime0
bsq = dot(B_vec, B_vec)
gradpsi_sq = dot(grad_psi, grad_psi)
f0[i, :] .= f
fx0[i, :] .= fx
fy0[i, :] .= fy
fxy0[i, :] .= fxy
rho0[i] = rho
eta0[i] = eta
r0[i] = r
gradpsi_sq0[i] = gradpsi_sq
h_theta0[i] = fy[3] / (2pi)
C_theta[i] = (Rpsitheta * Ztheta - Rtheta * Zpsitheta) / (Rpsi * Ztheta - Rtheta * Zpsi)
Iper0[i] = dot(q0 .* grad_theta .- grad_zeta, grad_psi) / gradpsi_sq
bsq0[i] = bsq
jac0[i] = jac
bdot_theta_phi0[i] = dot(B_vec, v_theta_zeta)
v0[i, :, :] .= v
v_zeta_psi0[i, :] .= v_zeta_psi
v_psi_theta0[i, :] .= v_psi_theta
end
dbsq_dtheta = _periodic_fft_lowpass_derivative(bsq0, theta_vals; nkeep=16)
dinvbsq_dtheta = .-dbsq_dtheta ./ (bsq0 .^ 2)
kappas0 .= -dinvbsq_dtheta .* two_pi_f0 ./ (2 .* jac0)
int_fs = hcat(1 ./ gradpsi_sq0, r0 .* r0 ./ gradpsi_sq0)
@views int_fs[end, :] .= int_fs[1, :]
int_vals = FastInterpolations.integrate(cubic_interp(theta_vals, Series(int_fs); bc=PeriodicBC()))
I0 = Float64(int_vals[1])
IR = Float64(int_vals[2])
Delta_tilde = Float64(I0 * two_pi_f0^2 + chi_prime0^2)
return (
theta_grid=theta_vals,
q0=q0,
q0prime=q0prime,
p0prime=p0prime,
two_pi_f0=two_pi_f0,
chi_prime0=chi_prime0,
r0=r0,
rho0=rho0,
eta0=eta0,
f0=f0,
fx0=fx0,
fy0=fy0,
fxy0=fxy0,
gradpsi_sq0=gradpsi_sq0,
h_theta0=h_theta0,
C_theta=C_theta,
Iper0=Iper0,
bsq0=bsq0,
jac0=jac0,
bdot_theta_phi0=bdot_theta_phi0,
v0=v0,
v_zeta_psi0=v_zeta_psi0,
v_psi_theta0=v_psi_theta0,
kappas0=kappas0,
I0=I0,
IR=IR,
Delta_tilde=Delta_tilde
)
end
function _periodic_fft_lowpass_derivative(
vals::AbstractVector{<:Real},
xs::AbstractVector{<:Real};
nkeep::Int=32
)
nfull = length(vals)
n = nfull - 1
if n < 2
throw(ArgumentError("Need at least 3 periodic samples for FFT derivative"))
end
period = Float64(xs[end] - xs[1])
if !(period > 0.0)
throw(ArgumentError("Periodic grid must span a positive interval"))
end
coeffs = FFTW.fft(ComplexF64.(vals[1:n]))
deriv_coeffs = zeros(ComplexF64, n)
maxmode = min(nkeep, fld(n, 2))
@inbounds for j in 1:n
mode = j <= div(n, 2) + 1 ? j - 1 : j - 1 - n
if abs(mode) <= maxmode
deriv_coeffs[j] = (im * 2pi * mode / period) * coeffs[j]
end
end
deriv = real.(FFTW.ifft(deriv_coeffs))
return vcat(deriv, deriv[1])
end
function _calculate_i_per_perturbed(
bg::NamedTuple,
theta_grid::AbstractVector,
corr_qprime::Float64,
corr_pprime::Float64;
theta_k::Float64=0.0
)
H = bg.q0 .+ bg.h_theta0
A = 4pi^2 .* bg.r0 .* bg.r0 ./ (bg.chi_prime0^2 .* bg.gradpsi_sq0)
B = bg.two_pi_f0^2 ./ (bg.chi_prime0^2 .* bg.gradpsi_sq0)
weight_fs = hcat(H .* A, H .* B)
@views weight_fs[end, :] .= weight_fs[1, :]
weight_int = FastInterpolations.integrate(cubic_interp(theta_grid, Series(weight_fs); bc=PeriodicBC()))
Abar_w = weight_int[1] / bg.q0
Bbar_w = weight_int[2] / bg.q0
denom = 1.0 + Bbar_w
AperP = H .* ((A .- Abar_w) .- (Abar_w / denom) .* (B .- Bbar_w))
Aperq = bg.h_theta0 ./ bg.q0 .+ (H ./ bg.q0) .* ((B .- Bbar_w) ./ denom)
dI_dtheta = AperP .* corr_pprime .+ Aperq .* corr_qprime
dI_dtheta_periodic = Vector{Float64}(dI_dtheta)
dI_dtheta_periodic[end] = dI_dtheta_periodic[1]
i_per_primitive = vec(FastInterpolations.cumulative_integrate(cubic_interp(theta_grid, dI_dtheta_periodic; bc=PeriodicBC())))
i_per_spl = cubic_interp(Float64.(theta_grid), i_per_primitive; bc=CubicFit())
theta_min = theta_grid[1]
theta_period = theta_grid[end] - theta_min
theta_k_wrapped = mod(theta_k - theta_min, theta_period) + theta_min
i_per_theta_k = i_per_spl(theta_k_wrapped)
i_per_perturbed = copy(i_per_primitive .- i_per_theta_k)
return i_per_perturbed
end
function _ballooning_theta_scale(
periodic::AbstractVector,
peculiar_1st::AbstractVector,
peculiar_2nd::AbstractVector;
fallback::Float64=BALLOONING_THETA_MAX_CAP
)
theta_scale = 0.0
for idx in eachindex(periodic, peculiar_1st, peculiar_2nd)
a0 = periodic[idx]
a1 = peculiar_1st[idx]
a2 = peculiar_2nd[idx]
if Base.isfinite(a0) && Base.isfinite(a1) && Base.isfinite(a2) && Base.abs(a2) > Base.eps(Float64)
c = a0 - a1^2 / (4.0 * a2)
local_scale = Base.sqrt(Base.abs(c / a2))
Base.isfinite(local_scale) && (theta_scale = Base.max(theta_scale, local_scale))
end
end
return theta_scale > 0.0 ? theta_scale : fallback
end
function prepare_ballooning_coefficients(
flux_surface_index::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium;
corr_qprime::Float64=0.0,
corr_pprime::Float64=0.0,
theta_k::Float64=0.0
)
mtheta = length(plasma_eq.rzphi_ys) - 1
theta_grid = Vector(plasma_eq.rzphi_ys)
bg = _collect_surface_response_background(flux_surface_index, plasma_eq, theta_grid)
theta_min = theta_grid[1]
theta_period = theta_grid[end] - theta_min
theta_k_wrapped = mod(theta_k - theta_min, theta_period) + theta_min
theta_k_reference = Float64(theta_k)
i_per0_periodic = Vector{Float64}(bg.Iper0)
i_per0_periodic[end] = i_per0_periodic[1]
i_per0_spl = cubic_interp(theta_grid, i_per0_periodic; bc=PeriodicBC())
i_per0_theta_k = i_per0_spl(theta_k_wrapped)
i_per0_theta_ref = i_per0_spl(theta_min)
i_per0_thetak_shift = i_per0_theta_k - i_per0_theta_ref
i_per0_shifted = bg.Iper0 .- i_per0_theta_k
two_pi_f = bg.two_pi_f0
pressure_gradient = bg.p0prime
q = bg.q0
q_derivative = bg.q0prime
chi_prime = bg.chi_prime0
bsq = bg.bsq0
jac_arr_loop1 = bg.jac0
jac_psi_loop1 = zeros(mtheta + 1)
bsq_psi_loop1 = zeros(mtheta + 1)
bdot_theta_phi_loop1 = bg.bdot_theta_phi0
for itheta in 0:mtheta
idx = itheta + 1
jac_psi_loop1[idx] = bg.fx0[idx, 4]
drfac_dp = bg.fx0[idx, 1] / (2 * bg.rho0[idx])
eta_dp = 2pi * bg.fx0[idx, 2]
dr_dp = drfac_dp * cos(bg.eta0[idx]) - bg.rho0[idx] * sin(bg.eta0[idx]) * eta_dp
dv21_dp =
(bg.fxy0[idx, 1] / (2 * bg.rho0[idx]) - bg.fx0[idx, 1] * bg.fy0[idx, 1] / (4 * bg.f0[idx, 1] * bg.rho0[idx])) / bg.jac0[idx] -
bg.v0[idx, 2, 1] * jac_psi_loop1[idx] / bg.jac0[idx]
dv22_dp = (bg.fxy0[idx, 2] * 2pi * bg.rho0[idx] + (1 + bg.fy0[idx, 2]) * 2pi * drfac_dp) / bg.jac0[idx] - bg.v0[idx, 2, 2] * jac_psi_loop1[idx] / bg.jac0[idx]
dv23_dp = (bg.fxy0[idx, 3] * bg.r0[idx] + bg.fy0[idx, 3] * dr_dp) / bg.jac0[idx] - bg.v0[idx, 2, 3] * jac_psi_loop1[idx] / bg.jac0[idx]
dv33_dp = (2pi * dr_dp) / bg.jac0[idx] - bg.v0[idx, 3, 3] * jac_psi_loop1[idx] / bg.jac0[idx]
grad_theta_dp = [dv21_dp, dv22_dp, dv23_dp]
grad_zeta_dp = [0.0, 0.0, dv33_dp]
dbase_dp = grad_theta_dp + q * grad_zeta_dp + q_derivative * (@view bg.v0[idx, 3, :])
dB_dp = dbase_dp * chi_prime
bsq_psi_loop1[idx] = 2 * dot((@view bg.v_zeta_psi0[idx, :]) .+ q .* (@view bg.v_psi_theta0[idx, :]), dB_dp) * chi_prime
end
bmag = sqrt.(bsq)
kappaw_periodic = zeros(mtheta + 1)
spl1_vals = jac_arr_loop1 .* bdot_theta_phi_loop1 ./ bmag
spl1_deriv = _periodic_fft_lowpass_derivative(spl1_vals, theta_grid; nkeep=32)
cell1 = -(jac_psi_loop1 ./ jac_arr_loop1 .+ 0.5 .* bsq_psi_loop1 ./ bsq) ./ chi_prime
cell2 = spl1_deriv ./ (jac_arr_loop1 .* bmag)
cell3 = two_pi_f .* q_derivative ./ (bsq .* jac_arr_loop1)
kappaw_periodic .= cell1 .+ cell2 .+ cell3
pressure_gradient += corr_pprime
q_derivative += corr_qprime
i_per_perturbed = _calculate_i_per_perturbed(
bg,
theta_grid,
corr_qprime,
corr_pprime;
theta_k=theta_k_wrapped
)
nabla_beta_sq_b_sq_periodic = zeros(mtheta + 1)
nabla_beta_sq_b_sq_peculiar_1st = zeros(mtheta + 1)
nabla_beta_sq_b_sq_peculiar_2nd = zeros(mtheta + 1)
jac_chiprime = zeros(mtheta + 1)
pprime_chiprime = fill(pressure_gradient / chi_prime, mtheta + 1)
for itheta in 0:mtheta
grad_psi_sq = bg.gradpsi_sq0[itheta+1]
i_per_val = i_per0_shifted[itheta+1]
i_per_total = i_per_val + i_per_perturbed[itheta+1]
term1 = 1.0 / (chi_prime^2 * grad_psi_sq)
term2_factor = grad_psi_sq / bsq[itheta+1]
nabla_beta_sq_b_sq_periodic[itheta+1] = term1 + term2_factor * (i_per_total^2 - 2.0 * theta_k_reference * q_derivative * i_per_total + (theta_k_reference * q_derivative)^2)
nabla_beta_sq_b_sq_peculiar_1st[itheta+1] = term2_factor * (2.0 * q_derivative * i_per_total - 2.0 * theta_k_reference * q_derivative^2)
nabla_beta_sq_b_sq_peculiar_2nd[itheta+1] = term2_factor * (q_derivative^2)
jac_chiprime[itheta+1] = jac_arr_loop1[itheta+1] / chi_prime
end
kappas = bg.kappas0
kappaw_periodic .+= -kappas .* i_per_perturbed .+ (theta_k_reference .* q_derivative .+ i_per0_thetak_shift) .* kappas
kappaw_secular = q_derivative .* kappas
# Only the 7 coefficients the ballooning ODE RHS reads are interpolated. bsq and sigma are kept as
# locals (used below for n0_fs/d0bar) but deliberately NOT added to the spline, since the RHS never
# uses them — interpolating 9 columns when 7 suffice wastes ~22% of every per-step spline evaluation.
bf_fs = zeros(mtheta + 1, 7)
bf_fs[:, 1] = nabla_beta_sq_b_sq_periodic
bf_fs[:, 2] = nabla_beta_sq_b_sq_peculiar_1st
bf_fs[:, 3] = nabla_beta_sq_b_sq_peculiar_2nd
bf_fs[:, 4] = kappaw_periodic
bf_fs[:, 5] = kappaw_secular
bf_fs[:, 6] = jac_chiprime
bf_fs[:, 7] = pprime_chiprime
theta_scale = _ballooning_theta_scale(
nabla_beta_sq_b_sq_periodic,
nabla_beta_sq_b_sq_peculiar_1st,
nabla_beta_sq_b_sq_peculiar_2nd
)
theta_max = min(BALLOONING_THETA_MAX_CAP, BALLOONING_THETA_SCALE_MULTIPLIER * theta_scale)
sigma = .-(two_pi_f .* pressure_gradient .* q_derivative) ./ (chi_prime^2 .* bsq)
m0_12 = jac_chiprime ./ nabla_beta_sq_b_sq_peculiar_2nd
m0_21 = -2.0 .* jac_chiprime .* pprime_chiprime .* kappaw_periodic
n0_fs = zeros(mtheta + 1, 4)
n0_fs[:, 1] = 0.5 .+ m0_12 .* sigma
n0_fs[:, 2] = m0_12
n0_fs[:, 3] = m0_21 .- sigma .- m0_12 .* sigma .^ 2
n0_fs[:, 4] = -0.5 .- m0_12 .* sigma
@views n0_fs[end, :] .= n0_fs[1, :]
n0_int = FastInterpolations.integrate(cubic_interp(theta_grid, Series(n0_fs); bc=PeriodicBC()))
d0bar = zeros(2, 2)
d0bar[1, 1] = n0_int[1]
d0bar[1, 2] = n0_int[2]
d0bar[2, 1] = n0_int[3]
d0bar[2, 2] = n0_int[4]
@views bf_fs[end, :] .= bf_fs[1, :]
ode_coefficient_spline = (
xs=theta_grid,
itp=cubic_interp(theta_grid, Series(bf_fs); bc=PeriodicBC()),
theta_max=theta_max
)
return (
ode_coefficient_spline=ode_coefficient_spline,
di=det(d0bar),
theta_grid=theta_grid
)
end
"""
salpha_reference(psi_idx, plasma_eq)
Compute local s-alpha reference values and physical profile derivatives at one flux surface.
"""
function salpha_reference(
psi_idx::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium
)
profiles = plasma_eq.profiles
psio = plasma_eq.psio
mu0 = Equilibrium.mu0
npsi = length(profiles.xs)
if psi_idx < 1 || psi_idx > npsi
throw(ArgumentError("psi_idx=$psi_idx is out of bounds for npsi=$npsi"))
end
if abs(psio) <= Base.eps(Float64)
throw(ArgumentError("plasma_eq.psio is too small to compute physical derivatives"))
end
dVdpsi_int = FastInterpolations.cumulative_integrate(profiles.dVdpsi_spline)
volume = max(Float64(dVdpsi_int[psi_idx]), 0.0)
psi = profiles.xs[psi_idx]
vprime_phys = profiles.dVdpsi_spline.y[psi_idx] / psio
q_ref = profiles.q_spline.y[psi_idx]
qprime_norm_ref = profiles.q_deriv(psi)
pprime_norm_ref = profiles.P_deriv(psi)
qprime_ref = qprime_norm_ref / psio
pprime_ref = (pprime_norm_ref / mu0) / psio
denom = q_ref * vprime_phys
s_ref = abs(denom) > Base.eps(Float64) ? (2.0 * volume * qprime_ref / denom) : NaN
major_radius = max(plasma_eq.ro, Base.eps(Float64))
alpha_geom = max(volume / (2π * major_radius), 0.0)
alpha_ref = -2.0 * mu0 * pprime_ref * vprime_phys * sqrt(alpha_geom)
return (
s_ref=s_ref,
alpha_ref=alpha_ref,
volume_ref=volume,
vprime_ref=vprime_phys,
q_ref=q_ref,
qprime_ref=qprime_ref,
pprime_ref=pprime_ref,
qprime_norm_ref=qprime_norm_ref,
pprime_norm_ref=pprime_norm_ref
)
end
"""
ballooning_delta_prime(psi_idx, plasma_eq; corr_qprime=0.0, corr_pprime=0.0, theta_k=0.0)
Evaluate one corrected local ballooning point. Corrections use the same
normalized units as `prepare_ballooning_coefficients`: add `corr_qprime` to
`dq/dpsi_norm` and `corr_pprime` to `d(mu0*p)/dpsi_norm`. `di` is the
`det(d0bar)` diagnostic assembled from the same corrected coefficients.
"""
function ballooning_delta_prime(
psi_idx::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium;
corr_qprime::Float64=0.0,
corr_pprime::Float64=0.0,
theta_k::Float64=0.0
)
coeff_data = prepare_ballooning_coefficients(
psi_idx,
plasma_eq;
corr_qprime=corr_qprime,
corr_pprime=corr_pprime,
theta_k=theta_k
)
delta_prime = integrate_ballooning_ode(
coeff_data.ode_coefficient_spline;
theta_k=theta_k
).value
return (delta_prime=delta_prime, di=coeff_data.di)
end
"""
scan_delta_prime_map(psi_idx, plasma_eq; s_scales, alpha_scales, ...)
Run a local s-alpha style scan at one flux surface using the `Ballooning.jl`
makefromZero ballooning path. The scan perturbs physical `dq/dpsi` and
`dp/dpsi`, converts them to the normalized units expected by the local
ballooning evaluator, and returns delta-prime and `det(d0bar)` `Di` maps.
"""
function scan_delta_prime_map(
psi_idx::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium;
theta_k::Float64=0.0,
s_scales::AbstractVector{<:Real},
alpha_scales::AbstractVector{<:Real},
verbose::Bool=false
)
ref = salpha_reference(psi_idx, plasma_eq)
s_scales_f = Float64.(s_scales)
alpha_scales_f = Float64.(alpha_scales)
isempty(s_scales_f) && throw(ArgumentError("s_scales must not be empty"))
isempty(alpha_scales_f) && throw(ArgumentError("alpha_scales must not be empty"))
delta_prime_map = fill(NaN, length(s_scales_f), length(alpha_scales_f))
di_map = fill(NaN, length(s_scales_f), length(alpha_scales_f))
for is in eachindex(s_scales_f), ia in eachindex(alpha_scales_f)
corr_qprime = ref.qprime_norm_ref * (s_scales_f[is] - 1.0)
corr_pprime = ref.pprime_norm_ref * (alpha_scales_f[ia] - 1.0)
result = try
ballooning_delta_prime(
psi_idx,
plasma_eq;
corr_qprime=corr_qprime,
corr_pprime=corr_pprime,
theta_k=theta_k
)
catch err
if verbose
@warn "s-alpha scan point failed" psi_idx is ia err
end
nothing
end
if result !== nothing
delta_prime_map[is, ia] = result.delta_prime
di_map[is, ia] = result.di
end
end
s_values = ref.s_ref .* s_scales_f
alpha_values = ref.alpha_ref .* alpha_scales_f
return (
values=delta_prime_map,
delta_prime=delta_prime_map,
di=di_map,
di_values=di_map,
s_values=s_values,
alpha_values=alpha_values,
s_scales=s_scales_f,
alpha_scales=alpha_scales_f,
dqdpsi_ref=ref.qprime_ref,
pprime_ref=ref.pprime_ref,
theta_k=theta_k,
reference=ref
)
end
"""
ballooning_alpha_crossings(psi_idx, plasma_eq; theta_k=0.0, max_alpha_scale=8.0, n_scan=24, tol=1e-3)
Locate the marginal-stability crossings of the ballooning Δ' along the pressure-gradient
scaling `α/α_exp ∈ [0, max_alpha_scale]` at fixed magnetic shear. Marching up from the
ballooning-stable `α = 0` anchor, every sign change between scan samples is bisected to
`tol`; sign changes with endpoint `|Δ'|` far above the anchor magnitude are Δ' pole
crossings (not marginal points) and are skipped. The first crossing is the first
stability boundary, the second the second-stability boundary, and so on.
Returns `(scales, alphas, reference)` with `alphas = alpha_ref * scales`, ordered in
increasing α. Surfaces that never cross return empty vectors. With `max_crossings > 0`
the scan stops after that many crossings (e.g. `1` for a first-boundary-only search,
which avoids scanning the full α range above the boundary).
"""
function ballooning_alpha_crossings(
psi_idx::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium;
theta_k::Float64=0.0,
max_alpha_scale::Float64=8.0,
n_scan::Int=24,
tol::Float64=1e-3,
max_crossings::Int=0
)
ref = salpha_reference(psi_idx, plasma_eq)
# Δ' as a function of the α scaling at fixed magnetic shear. Failed evaluations
# (extreme corrections can break the coefficient assembly) count as non-stable
# samples and are rejected by the crossing classification, like in scan_delta_prime_map.
delta_at(scale) = try
ballooning_delta_prime(
psi_idx,
plasma_eq;
corr_qprime=0.0,
corr_pprime=ref.pprime_norm_ref * (scale - 1.0),
theta_k=theta_k
).delta_prime
catch
NaN
end
samples = collect(range(0.0, max_alpha_scale; length=n_scan + 1))
scales = _ballooning_marginal_crossings(delta_at, samples, tol; max_crossings=max_crossings)
return (scales=scales, alphas=ref.alpha_ref .* scales, reference=ref)
end
# March along `samples` (monotone, either direction) from the stable anchor (first finite,
# nonzero sample), returning every sign change of `delta_at` between finite samples,
# bisected to `tol`. Sign changes whose endpoint magnitudes exceed pole_cap*|Δ'_anchor|
# are Δ' pole crossings (not marginal points) and are skipped; on an adequately fine
# scan all remaining crossings are genuine marginal zeros, ordered from the anchor.
#
# Samples are evaluated lazily; with `max_crossings > 0` the march stops once that many
# crossings are found, so a first-boundary-only search costs only the samples up to it.
function _ballooning_marginal_crossings(delta_at, samples, tol; pole_cap=3.0, max_crossings=0)
n = length(samples)
k0 = 0
d_prev = NaN
for k in 1:n
d = delta_at(samples[k])
if isfinite(d) && d != 0.0
k0 = k
d_prev = d
break
end
end
k0 == 0 && return Float64[]
d_anchor = abs(d_prev)
locs = Float64[]
for k in k0+1:n
d = delta_at(samples[k])
if isfinite(d_prev) && isfinite(d) && sign(d) != sign(d_prev) && max(abs(d_prev), abs(d)) <= pole_cap * d_anchor
lo, hi = samples[k-1], samples[k]
sign_lo = sign(d_prev)
while abs(hi - lo) > tol
mid = 0.5 * (lo + hi)
dm = delta_at(mid)
(isfinite(dm) && sign(dm) == sign_lo) ? (lo = mid) : (hi = mid)
end
push!(locs, 0.5 * (lo + hi))
(max_crossings > 0 && length(locs) >= max_crossings) && break
end
d_prev = d
end
return locs
end
"""
critical_ballooning_alpha(psi_idx, plasma_eq; theta_k=0.0, max_alpha_scale=8.0, n_scan=24, tol=1e-3)
First infinite-n ballooning stability boundary at one flux surface: the lowest Δ' zero
from [`ballooning_alpha_crossings`](@ref). `α` is linear in `dp/dψ`, so the boundary
maps directly to `α_crit = α_ref * scale_crit`.
Returns `(alpha_crit, alpha_scale_crit, found)`. When no crossing exists within
`max_alpha_scale` (always stable, or second-stability access) `alpha_crit = NaN` and
`found = false`.
"""
function critical_ballooning_alpha(
psi_idx::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium;
theta_k::Float64=0.0,
max_alpha_scale::Float64=8.0,
n_scan::Int=24,
tol::Float64=1e-3
)
cr = ballooning_alpha_crossings(psi_idx, plasma_eq; theta_k=theta_k, max_alpha_scale=max_alpha_scale, n_scan=n_scan, tol=tol, max_crossings=1)
isempty(cr.scales) && return (alpha_crit=NaN, alpha_scale_crit=NaN, found=false)
return (alpha_crit=cr.alphas[1], alpha_scale_crit=cr.scales[1], found=true)
end
"""
ballooning_alpha_boundary(plasma_eq; theta_k=0.0, n_scan=24, verbose=false)
Profile driver for the BALOO-style ballooning stability diagram. Loops over flux
surfaces returning the experimental pressure gradient `alpha` (from
[`salpha_reference`](@ref)) and the first stability boundary `alpha_critical` (from
[`critical_ballooning_alpha`](@ref)) versus normalized flux `psi`. Surfaces whose
experimental `alpha` exceeds `alpha_critical` are ballooning-unstable.
This is the fast first-boundary-only driver: `critical_ballooning_alpha` stops at the
first crossing, so cost scales with the boundary location rather than the full α range.
Use this (not [`ballooning_alpha_boundaries`](@ref)) when only the 1st boundary is
needed, e.g. a pedestal-stability constraint. `n_scan` sets the scan resolution; raise
it (e.g. 64) on edge surfaces where Δ' poles can shift a coarse first crossing.
The scan is evaluated only inside `BALLOONING_SCAN_PSI_WINDOW` — ballooning boundaries
are physically relevant in the mid-radius and pedestal, and the tightly packed axis and
far-edge surfaces dominate the scan cost. Per-surface failures, skipped surfaces, and
surfaces with no boundary within range are returned as `NaN`.
"""
function ballooning_alpha_boundary(
plasma_eq::Equilibrium.PlasmaEquilibrium;
theta_k::Float64=0.0,
n_scan::Int=24,
verbose::Bool=false
)
xs = plasma_eq.profiles.xs
npsi = length(xs)
psi = Vector{Float64}(xs)
alpha = fill(NaN, npsi)
alpha_critical = fill(NaN, npsi)
Threads.@threads :greedy for i in 1:npsi
_in_ballooning_scan_window(xs[i], xs[end]) || continue
try
alpha[i] = salpha_reference(i, plasma_eq).alpha_ref
alpha_critical[i] = critical_ballooning_alpha(i, plasma_eq; theta_k=theta_k, n_scan=n_scan).alpha_crit
catch err
if verbose
@warn "ballooning alpha boundary failed" psi_idx = i exception = err
end
end
end
return (psi=psi, alpha=alpha, alpha_critical=alpha_critical)
end
"""
second_critical_ballooning_alpha(psi_idx, plasma_eq, alpha_scale_crit1; max_alpha_scale=8.0, n_scan=24, tol=1e-3)
Second (upper) ballooning stability boundary at one flux surface: the first Δ' zero
above `alpha_scale_crit1` (as returned by [`critical_ballooning_alpha`](@ref)), from
[`ballooning_alpha_crossings`](@ref). Returns the physical critical α, or `NaN` if no
such crossing exists within `max_alpha_scale`.
"""
function second_critical_ballooning_alpha(
psi_idx::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium,
alpha_scale_crit1::Float64;
max_alpha_scale::Float64=8.0,
n_scan::Int=24,
tol::Float64=1e-3
)
alpha_scale_crit1 >= max_alpha_scale && return NaN
cr = ballooning_alpha_crossings(psi_idx, plasma_eq; max_alpha_scale=max_alpha_scale, n_scan=n_scan, tol=tol)
k2 = findfirst(>(alpha_scale_crit1), cr.scales)
return isnothing(k2) ? NaN : cr.alphas[k2]
end
"""
ballooning_alpha_boundaries(plasma_eq; theta_k=0.0, max_alpha_scale=8.0, n_scan=24, verbose=false)
Profile driver returning the experimental pressure gradient `alpha`, the first stability
boundary `alpha_critical1` (lowest Δ' zero), and the second stability boundary
`alpha_critical2` (next zero above it) versus normalized flux `psi`, from
[`ballooning_alpha_crossings`](@ref) at each surface. Arrays contain `NaN` where no
boundary exists.
`n_scan` sets the scan resolution of the crossing search; crossings closer together
than the scan step can be missed, which shows up as isolated outliers on otherwise
smooth boundary curves. Surfaces outside `BALLOONING_SCAN_PSI_WINDOW` are skipped
(returned as `NaN`), like per-surface failures.
"""
function ballooning_alpha_boundaries(
plasma_eq::Equilibrium.PlasmaEquilibrium;
theta_k::Float64=0.0,
max_alpha_scale::Float64=8.0,
n_scan::Int=24,
verbose::Bool=false
)
xs = plasma_eq.profiles.xs
npsi = length(xs)
psi = Vector{Float64}(xs)
alpha = fill(NaN, npsi)
alpha_critical1 = fill(NaN, npsi)
alpha_critical2 = fill(NaN, npsi)
Threads.@threads :greedy for i in 1:npsi
_in_ballooning_scan_window(xs[i], xs[end]) || continue
try
cr = ballooning_alpha_crossings(i, plasma_eq; theta_k=theta_k, max_alpha_scale=max_alpha_scale, n_scan=n_scan)
alpha[i] = cr.reference.alpha_ref
isempty(cr.alphas) && continue
alpha_critical1[i] = cr.alphas[1]
length(cr.alphas) >= 2 && (alpha_critical2[i] = cr.alphas[2])
catch err
if verbose
@warn "ballooning alpha boundaries failed" psi_idx=i exception=err
end
end
end
return (psi=psi, alpha=alpha, alpha_critical1=alpha_critical1, alpha_critical2=alpha_critical2)
end
"""
ballooning_qprime_crossings(psi_idx, plasma_eq; theta_k=0.0, min_qprime_scale=-2.0, max_qprime_scale=4.0, n_scan=24, tol=1e-3)
Locate the marginal-stability crossings of the ballooning Δ' along the magnetic shear
scaling `q'/q'_exp ∈ [min_qprime_scale, max_qprime_scale]` at the fixed experimental
pressure gradient — the q'-channel counterpart of [`ballooning_alpha_crossings`](@ref).
The march starts from the first-regime-stable high shear end (`max_qprime_scale`) and
proceeds downward; sign changes are bisected and Δ' pole crossings skipped exactly as
in the α scan, so the first crossing is the critical q' and the second the re-entry to
stability at lower (or reversed) shear.
Returns `(scales, qprimes, reference)` where `qprimes = qprime_norm_ref * scales` is in
`dq/dpsi_norm` units, ordered in decreasing q'.
"""
function ballooning_qprime_crossings(
psi_idx::Int,
plasma_eq::Equilibrium.PlasmaEquilibrium;
theta_k::Float64=0.0,
min_qprime_scale::Float64=-2.0,
max_qprime_scale::Float64=4.0,
n_scan::Int=24,
tol::Float64=1e-3
)
ref = salpha_reference(psi_idx, plasma_eq)
# Δ' as a function of the q' scaling at the experimental pressure gradient. Failed
# evaluations (reversed-shear corrections can break the coefficient assembly) count
# as non-stable samples and are rejected by the crossing classification.
delta_at(scale) = try
ballooning_delta_prime(
psi_idx,
plasma_eq;
corr_qprime=ref.qprime_norm_ref * (scale - 1.0),
corr_pprime=0.0,
theta_k=theta_k
).delta_prime
catch
NaN
end
samples = collect(range(max_qprime_scale, min_qprime_scale; length=n_scan + 1))
scales = _ballooning_marginal_crossings(delta_at, samples, tol)
return (scales=scales, qprimes=ref.qprime_norm_ref .* scales, reference=ref)
end