|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Reduced ensembles; the unchanged 192-marker test remains the full-tier oracle.""" |
| 3 | + |
| 4 | +from math import comb |
| 5 | +from pathlib import Path |
| 6 | +import os |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +from time import perf_counter |
| 10 | + |
| 11 | +from netCDF4 import Dataset |
| 12 | +import numpy as np |
| 13 | + |
| 14 | +import test_collisional_stl_wall as full |
| 15 | + |
| 16 | + |
| 17 | +def check_hits(result, name): |
| 18 | + hit = result["wall_hit"] == 1 |
| 19 | + assert np.any(hit), f"{name}: no STL hits" |
| 20 | + assert np.all(result["orbit_exit_code"][hit] == 2), name |
| 21 | + assert np.all(result["times_lost"][hit] > 10 * full.TRANSIT_TIME), name |
| 22 | + assert np.all(result["times_lost"][hit] <= full.TRACE_TIME), name |
| 23 | + assert np.all(np.isfinite(result["zend"][hit])), name |
| 24 | + angle = result["wall_hit_angle_rad"][hit] |
| 25 | + assert np.all((angle >= 0) & (angle <= np.pi / 2)), name |
| 26 | + np.testing.assert_allclose( |
| 27 | + result["xend_cart"][hit], result["wall_hit_cart"][hit], atol=1e-6, rtol=0 |
| 28 | + ) |
| 29 | + np.testing.assert_allclose( |
| 30 | + np.linalg.norm(result["wall_hit_normal_cart"][hit], axis=1), |
| 31 | + 1, |
| 32 | + atol=1e-12, |
| 33 | + rtol=0, |
| 34 | + ) |
| 35 | + print(f"{name}: {hit.sum()}/{len(hit)} STL hits", flush=True) |
| 36 | + return hit |
| 37 | + |
| 38 | + |
| 39 | +def write_case(base, case): |
| 40 | + name, ensemble, collisions, intervals = case |
| 41 | + work = base / name |
| 42 | + work.mkdir(exist_ok=True) |
| 43 | + (work / "results.nc").unlink(missing_ok=True) |
| 44 | + for filename in ("wall.stl", "chartmap.nc", "coils.simple", "wout.nc"): |
| 45 | + link = work / filename |
| 46 | + if not link.exists(): |
| 47 | + link.symlink_to(base / filename) |
| 48 | + np.savetxt(work / "start.dat", ensemble, fmt="%.17e") |
| 49 | + density = 0.0 if name == "dilute" else 2.5e20 |
| 50 | + (work / "simple.in").write_text( |
| 51 | + f"""&config |
| 52 | +field_input = 'coils.simple' |
| 53 | +coord_input = 'chartmap.nc' |
| 54 | +netcdffile = 'wout.nc' |
| 55 | +wall_input = 'wall.stl' |
| 56 | +wall_units = 'm' |
| 57 | +isw_field_type = 5 |
| 58 | +integmode = 0 |
| 59 | +startmode = 2 |
| 60 | +ntestpart = {len(ensemble)} |
| 61 | +trace_time = {full.TRACE_TIME:.17e} |
| 62 | +ntimstep = 101 |
| 63 | +npoiper2 = {intervals} |
| 64 | +multharm = 1 |
| 65 | +contr_pp = -1d10 |
| 66 | +relerr = 1d-9 |
| 67 | +facE_al = 1d2 |
| 68 | +deterministic = .true. |
| 69 | +ran_seed = 541 |
| 70 | +swcoll = {".true." if collisions else ".false."} |
| 71 | +output_results_netcdf = .true. |
| 72 | +/ |
| 73 | +&profiles |
| 74 | +profile_type = 'power_series' |
| 75 | +Te_scale = 1d3 |
| 76 | +Ti1_scale = 1d3 |
| 77 | +Ti2_scale = 1d3 |
| 78 | +ni1_scale = {density:.17e} |
| 79 | +ni2_scale = {density:.17e} |
| 80 | +/ |
| 81 | +""", |
| 82 | + encoding="ascii", |
| 83 | + ) |
| 84 | + return work |
| 85 | + |
| 86 | + |
| 87 | +def main(): |
| 88 | + begin = perf_counter() |
| 89 | + simple, chartmap, coils, wout = (Path(arg).resolve() for arg in sys.argv[1:]) |
| 90 | + base = Path.cwd() / "collisional_stl_wall_fast" |
| 91 | + base.mkdir(exist_ok=True) |
| 92 | + for source, name in ((chartmap, "chartmap.nc"), (wout, "wout.nc")): |
| 93 | + link = base / name |
| 94 | + if not link.exists(): |
| 95 | + link.symlink_to(source) |
| 96 | + data = np.loadtxt(coils, skiprows=1) |
| 97 | + data[:, 3] *= full.COIL_CURRENT_SCALE |
| 98 | + np.savetxt( |
| 99 | + base / "coils.simple", data, header=str(len(data)), comments="", fmt="%.17e" |
| 100 | + ) |
| 101 | + full.write_wall(chartmap, base / "wall.stl") |
| 102 | + rho = full.check_inside_lcfs(chartmap, wout) |
| 103 | + with Dataset(chartmap) as ds: |
| 104 | + theta, zeta = (np.asarray(ds[key][:]) for key in ("theta", "zeta")) |
| 105 | + rng = np.random.default_rng(541) |
| 106 | + # Subsample the original ensemble, without changing the physical duration, |
| 107 | + # fields, integration tolerances, collision density or wall resolution. |
| 108 | + starts = np.column_stack( |
| 109 | + ( |
| 110 | + np.full(full.NMARKERS, rho), |
| 111 | + rng.choice(theta, full.NMARKERS), |
| 112 | + rng.choice(zeta, full.NMARKERS), |
| 113 | + np.ones(full.NMARKERS), |
| 114 | + rng.uniform(-0.2, 0.2, full.NMARKERS), |
| 115 | + ) |
| 116 | + ) |
| 117 | + ref_indices = np.linspace(0, full.NMARKERS - 1, 32, dtype=int) |
| 118 | + coll_indices = np.linspace(0, full.NMARKERS - 1, 64, dtype=int) |
| 119 | + # Stored collisionless impacts in the 32-marker subset; replay all five |
| 120 | + # at doubled segment resolution. |
| 121 | + fine_indices = np.array([43, 98, 117, 166, 172]) |
| 122 | + cases = ( |
| 123 | + ("collisionless", starts[ref_indices], False, 64), |
| 124 | + ("dilute", starts[ref_indices], True, 64), |
| 125 | + ("collisional", starts[coll_indices], True, 64), |
| 126 | + ("repeat", starts[coll_indices], True, 64), |
| 127 | + ("collisionless_fine", starts[fine_indices], False, 128), |
| 128 | + ) |
| 129 | + |
| 130 | + workdirs = [write_case(base, case) for case in cases] |
| 131 | + (base / "simple.in").write_text((workdirs[0] / "simple.in").read_text()) |
| 132 | + # One production-library driver initializes the field once. OpenMP uses |
| 133 | + # four threads for both field construction and per-marker integration. |
| 134 | + env = dict( |
| 135 | + os.environ, |
| 136 | + OMP_NUM_THREADS="4", |
| 137 | + OMP_DYNAMIC="FALSE", |
| 138 | + GFORTRAN_UNBUFFERED_ALL="1", |
| 139 | + ) |
| 140 | + with (base / "run.log").open("w") as log: |
| 141 | + process = subprocess.run( |
| 142 | + [str(simple), *map(str, workdirs)], |
| 143 | + cwd=base, |
| 144 | + env=env, |
| 145 | + stdout=log, |
| 146 | + stderr=subprocess.STDOUT, |
| 147 | + timeout=120, |
| 148 | + ) |
| 149 | + assert process.returncode == 0, f"see {base / 'run.log'}" |
| 150 | + assert "Error in stost" not in (base / "run.log").read_text() |
| 151 | + results = [] |
| 152 | + for work in workdirs: |
| 153 | + with Dataset(work / "results.nc") as ds: |
| 154 | + result = {key: np.asarray(ds[key][:]) for key in full.RESULT_VARS} |
| 155 | + assert not np.any(result["orbit_exit_code"] == 3), str(work) |
| 156 | + assert np.all(result["orbit_exit_code"] < 100), str(work) |
| 157 | + results.append(result) |
| 158 | + reference, dilute, collisional, repeat, fine = results |
| 159 | + hit_ref = check_hits(reference, "collisionless") |
| 160 | + hit_coll = check_hits(collisional, "collisional") |
| 161 | + # Numerical drift budgets are unchanged; the stored mean is recomputed for |
| 162 | + # this exact deterministic subset, rather than widened for a smaller sample. |
| 163 | + assert abs(np.count_nonzero(hit_ref) - 5) <= 2, "collisionless hit-count drift" |
| 164 | + np.testing.assert_allclose( |
| 165 | + np.mean(reference["times_lost"][hit_ref]), |
| 166 | + 2.7560491342032043e-4, |
| 167 | + rtol=0.03, |
| 168 | + atol=0, |
| 169 | + ) |
| 170 | + matched = np.searchsorted(ref_indices, fine_indices) |
| 171 | + np.testing.assert_array_equal(reference["wall_hit"][matched], 1) |
| 172 | + np.testing.assert_array_equal(fine["wall_hit"], 1) |
| 173 | + np.testing.assert_allclose( |
| 174 | + fine["times_lost"], reference["times_lost"][matched], rtol=0.01, atol=1e-7 |
| 175 | + ) |
| 176 | + np.testing.assert_allclose( |
| 177 | + fine["wall_hit_cart"], reference["wall_hit_cart"][matched], rtol=0, atol=0.5 |
| 178 | + ) |
| 179 | + np.testing.assert_allclose(reference["zend"][hit_ref, 3], 1, rtol=0, atol=1e-7) |
| 180 | + for key in ("wall_hit", "orbit_exit_code"): |
| 181 | + np.testing.assert_array_equal(dilute[key], reference[key], err_msg=key) |
| 182 | + for key in ("zend", "times_lost", "wall_hit_cart", "wall_hit_angle_rad"): |
| 183 | + np.testing.assert_allclose( |
| 184 | + dilute[key], reference[key], rtol=2e-6, atol=2e-8, err_msg=key |
| 185 | + ) |
| 186 | + for key in full.RESULT_VARS: |
| 187 | + np.testing.assert_array_equal(repeat[key], collisional[key], err_msg=key) |
| 188 | + delayed = hit_coll & (collisional["times_lost"] > 20 * full.TRANSIT_TIME) |
| 189 | + energy = collisional["zend"][delayed, 3] ** 2 |
| 190 | + # Exact one-sided sign test of median E/E0 >= 0.99: under the null, each |
| 191 | + # independent delayed impact has probability <= 1/2 of being below 0.99. |
| 192 | + # P[Binomial(n, 1/2) >= k] <= 0.05 requires at least five slowed impacts; |
| 193 | + # it automatically tightens if any delayed impacts fail to slow down. |
| 194 | + n = len(energy) |
| 195 | + k = np.count_nonzero(energy < 0.99) |
| 196 | + p_value = sum(comb(n, j) for j in range(k, n + 1)) / 2**n |
| 197 | + assert p_value <= 0.05, f"unresolved slowing down: n={n}, k={k}, p={p_value}" |
| 198 | + assert np.mean(energy) < 0.99, "wall output lost the slowed-down state" |
| 199 | + print( |
| 200 | + f"Slowing down: n={n}, k={k}, sign-test p={p_value:.6g}; " |
| 201 | + f"mean E/E0={np.mean(energy):.9f}", |
| 202 | + flush=True, |
| 203 | + ) |
| 204 | + print("PASS: segment convergence, vacuum limit, slowing down, seeded repeat") |
| 205 | + print(f"Fast wall test: {perf_counter() - begin:.3f} s", flush=True) |
| 206 | + |
| 207 | + |
| 208 | +if __name__ == "__main__": |
| 209 | + main() |
0 commit comments