Example: Machine symmetrisation
This notebook demonstrates how to turn an approximately up-down symmetric machine description into an exact up-down symmetric model.
By building perfectly up-down symmetric machine descriptions, we can use the static/evolutive solvers (and virtual PCS) to evolve the plasma dynamics with much larger timesteps than is usually possible. This is because the vertical instability timescale typically limits the timestep sizes (recall the Example 05 notebooks). Of course this only works for up-down symmetric plasmas but can be a good approximation for plasma scenario design before adding the vertical instabilities back in.
Overview
Let \(Z_0\) be the symmetry midplane vertical coordinate, and define the vertical reflection operator \(\mathcal{R}_Z : (R, Z) \mapsto (R, 2Z_0 - Z)\). Given an upper conductor element with coordinates \(\mathbf{x}_u = (R_u, Z_u)\) and its lower partner with coordinates \(\mathbf{x}_l = (R_l, Z_l)\), the paired geometry is replaced by its reflected average \(\mathbf{x}_{\mathrm{sym}}\):
Similarly, the currents \(I_u\) (upper) and \(I_l\) (lower) in an independently driven pair decompose into even (\(I_+\)) and odd (\(I_-\)) components:
Only the even component \(I_+\) is retained in the strictly symmetric machine, while the original currents remain recoverable via \(I_u = I_+ + I_-\) and \(I_l = I_+ - I_-\).
Below, we:
Build an imperfect toy machine (similar to the Anamak in Example 07a) with a small vertical offset, centimetre-scale upper/lower mismatches, and one electrically odd vertical-control circuit.
Symmetrise the machine with
prepare_up_down_symmetric_machine()—demonstrating how it flags and excludes the odd circuit, recentres the geometry at \(Z = 0\), and pairs/averages the remaining coils and boundaries.Quantify the resulting geometric and Green-function changes, verify the even/odd current transforms, and build the final symmetric
tokamakobject forSymmetryReducedSolver.
Define an imperfect source machine
The test machine intentionally includes:
A central solenoid and independently driven upper/lower shaping and divertor coils.
Paired passive wall elements.
A small common vertical offset and centimetre-scale upper/lower mismatches.
One anti-series vertical-control circuit, which is electrically odd.
Because prepare_up_down_symmetric_machine() operates on deep copies, the original dictionaries are never modified.
from copy import deepcopy
import matplotlib.pyplot as plt
import numpy as np
from freegsnke import build_machine, equilibrium_update
from freegsnke.up_down_symmetry import prepare_up_down_symmetric_machine
plt.rcParams.update({"figure.dpi": 120, "axes.grid": True})
def filament(r, z, *, multiplier=80, polarity=1):
"""Return one rectangular active-coil filament bundle."""
return {
"R": [r],
"Z": [z],
"dR": 0.07,
"dZ": 0.07,
"resistivity": 1.55e-8,
"polarity": polarity,
"multiplier": multiplier,
}
def rectangle(name, group, r, z, half_width=0.025):
"""Return one quadrilateral passive element."""
return {
"name": name,
"element": group,
"R": np.array(
[r - half_width, r + half_width, r + half_width, r - half_width]
),
"Z": np.array(
[z - half_width, z - half_width, z + half_width, z + half_width]
),
"resistivity": 5.5e-7,
}
def build_imperfect_source_machine():
"""Build an in-memory, approximately symmetric toy tokamak description."""
z0 = 0.008 # unknown to the preparation: an 8 mm global source offset
active = {
"solenoid": {
**filament(0.24, z0, multiplier=20),
"R": [0.24] * 6,
"Z": z0 + np.array([-1.05, -0.63, -0.21, 0.21, 0.63, 1.05]),
}
}
# Independent upper/lower circuits with small source-description errors.
locations = {
"PF1": (0.43, 1.18),
"PF2": (0.66, 1.34),
"PF3": (1.35, 1.20),
"PF4": (1.63, 0.87),
"PF5": (1.72, 0.48),
"PF6": (1.76, 0.17),
}
for index, (name, (r, z)) in enumerate(locations.items()):
dr = (index - 2.5) * 0.012
dz = (-1) ** index * 0.025
active[f"{name}_upper"] = filament(r, z0 + z)
active[f"{name}_lower"] = filament(r + dr, z0 - z + dz)
# Opposite winding polarities make this circuit odd under reflection.
active["vertical_control"] = {
"upper": filament(1.83, z0 + 0.31),
"lower": filament(1.83, z0 - 0.31, polarity=-1),
}
passive = []
angles = np.linspace(np.pi / 18, 17 * np.pi / 18, 9)
for index, angle in enumerate(angles):
r = 1.02 + 0.63 * np.cos(angle)
z = 1.02 * np.sin(angle)
dr = 0.020 * np.sin(2 * angle)
dz = 0.025 * np.cos(angle)
passive.extend(
[
rectangle(f"wall_{index}_upper", f"wall_{index}", r, z0 + z),
rectangle(
f"wall_{index}_lower",
f"wall_{index}",
r + dr,
z0 - z + dz,
),
]
)
theta = np.linspace(0.0, 2 * np.pi, 120, endpoint=True)
r_limiter = 0.98 + 0.4 * np.cos(theta + 0.13 * np.sin(theta)) + 0.03 * np.sin(theta)
z_limiter = z0 + 0.7 * np.sin(theta) + 0.04 * np.cos(theta) ** 2 * np.sin(theta + 0.4)
limiter = [
{"R": float(r), "Z": float(z)} for r, z in zip(r_limiter, z_limiter)
]
r_wall = 0.98 + 0.45 * np.cos(theta + 0.13 * np.sin(theta)) + 0.03 * np.sin(theta)
z_wall = z0 + 0.75 * np.sin(theta) + 0.04 * np.cos(theta) ** 2 * np.sin(theta + 0.4)
wall = [{"R": float(r), "Z": float(z)} for r, z in zip(r_wall, z_wall)]
return active, passive, limiter, wall
def active_parts(circuit):
"""Yield direct and compound active-coil parts in one form."""
if "R" in circuit:
return [circuit]
return [
part
for part in circuit.values()
if isinstance(part, dict) and "R" in part
]
def centroid(element):
return float(np.mean(element["R"])), float(np.mean(element["Z"]))
def plot_description(ax, active, passive, boundary, *, title, z_offset=0.0):
"""Plot a raw machine description without first building a tokamak object."""
for name, circuit in active.items():
colour = "tab:red" if name == "vertical_control" else "tab:blue"
parts = active_parts(circuit)
for part in parts:
r, z = centroid(part)
ax.scatter(r, z + z_offset, s=36, color=colour, zorder=4)
# Label a compound series circuit beside its upper bundle.
r_label, z_label = max((centroid(part) for part in parts), key=lambda p: p[1])
ax.annotate(
name,
(r_label, z_label + z_offset),
fontsize=6,
xytext=(3, 2),
textcoords="offset points",
)
for element in passive:
r = np.r_[element["R"], element["R"][0]]
z = np.r_[element["Z"], element["Z"][0]] + z_offset
ax.fill(r, z, color="0.65", alpha=0.55, linewidth=0.5, edgecolor="0.25")
points = np.asarray(
[[item["R"], item["Z"] + z_offset] for item in boundary]
)
ax.plot(*np.vstack((points, points[0])).T, color="black", linewidth=1.2)
ax.axhline(0.0, color="0.35", linewidth=0.8, linestyle=":")
ax.set(title=title, xlabel="R [m]", ylabel="Z [m]", aspect="equal")
ax.set_xlim(0.05, 1.95)
ax.set_ylim(-1.5, 1.5)
active_source, passive_source, limiter_source, wall_source = (
build_imperfect_source_machine()
)
source_tokamak = build_machine.tokamak(
active_coils_data=active_source,
passive_coils_data=passive_source,
limiter_data=limiter_source,
wall_data=wall_source,
)
Active coils --> built from user-provided data.
Passive structures --> built from user-provided data.
Limiter --> built from user-provided data.
Wall --> built from user-provided data.
Magnetic probes --> none provided.
Resistance (R) and inductance (M) matrices --> built using actives (and passives if present).
Tokamak built.
So now we can clearly see that this machine is not up-down symmetric!
The upper coils, passives, and limiter/wall are a few cms “off” vs. their lower counterparts.
# plot
fig, ax = plt.subplots(figsize=(4, 6))
source_tokamak.plot(axis=ax, show=False)
ax.plot(source_tokamak.limiter.R, source_tokamak.limiter.Z, "k-", linewidth=1.2)
ax.plot(source_tokamak.wall.R, source_tokamak.wall.Z, "r-", linewidth=1.2)
ax.axhline(0.0, color="0.35", linewidth=0.8, linestyle=":")
ax.set( xlabel="Major radius, R [m]", ylabel="Height, Z [m]", aspect="equal")
ax.set_xlim(0.05, 1.95)
ax.set_ylim(-1.5, 1.5)
plt.show()
Symmetrise the machine (detecting and excluding odd circuits)
Let \(G_{\mathrm{coil}}(R, Z)\) denote the poloidal-flux Green function produced on the grid by a unit current in a given active circuit. By default, prepare_up_down_symmetric_machine() raises an error if any active circuit has odd reflection parity (\(G_{\mathrm{coil}}(R, 2Z_0 - Z) = -G_{\mathrm{coil}}(R, Z)\)), preventing a circuit from being dropped silently.
After verifying that the expected error is raised, we pass exclude_odd_active=True to explicitly exclude the odd circuit, shift all retained geometry by \(-Z_0\) so the midplane lies at \(Z = 0\), average the reflected pairs, and return the PreparedUpDownMachine object.
# this call shows which circuits cannot be included in the new up-down symmetric model
try:
prepare_up_down_symmetric_machine(
active_source,
passive_source,
limiter_data=limiter_source,
wall_data=wall_source,
z_midplane="auto",
)
except ValueError as error:
print("Safety check stopped preparation:")
print(" ", error)
Safety check stopped preparation:
Electrically odd active circuits cannot be included in strict even evolution: ('vertical_control',). Pass 'exclude_odd_active=True' to omit and record them explicitly.
# this call will remove the named circuit above and symmetrise the machine
symmetric_machine_data = prepare_up_down_symmetric_machine(
active_source,
passive_source,
limiter_data=limiter_source,
wall_data=wall_source,
z_midplane="auto",
exclude_odd_active=True,
)
Retained active coil circuits (even): ('solenoid', 'PF1', 'PF2', 'PF3', 'PF4', 'PF5', 'PF6')
Explicitly excluded active circuits (odd): ('vertical_control',)
Passive structure pairs (9):
wall_0_upper / wall_0_lower
wall_1_upper / wall_1_lower
wall_2_upper / wall_2_lower
wall_3_upper / wall_3_lower
wall_4_upper / wall_4_lower
wall_5_upper / wall_5_lower
wall_6_upper / wall_6_lower
wall_7_upper / wall_7_lower
wall_8_upper / wall_8_lower
Source midplane: +8.000 mm
Applied whole-machine shift: -8.000 mm
Midplane fit RMS: 9.029 mm
Matched fit samples: 46
Active reflected pairs: 6
Component discrepancies (pre-averaging reflected RMS):
active PF6_upper / PF6_lower : 39.051 mm
active PF1_upper / PF1_lower : 39.051 mm
active PF5_upper / PF5_lower : 30.806 mm
active PF2_upper / PF2_lower : 30.806 mm
limiter upper path / lower path : 29.981 mm
wall upper path / lower path : 29.707 mm
passive wall_1_upper / wall_1_lower : 27.726 mm
passive wall_7_upper / wall_7_lower : 27.726 mm
active PF4_upper / PF4_lower : 25.710 mm
active PF3_upper / PF3_lower : 25.710 mm
passive wall_0_upper / wall_0_lower : 25.553 mm
passive wall_8_upper / wall_8_lower : 25.553 mm
passive wall_6_upper / wall_6_lower : 25.420 mm
passive wall_2_upper / wall_2_lower : 25.420 mm
passive wall_5_upper / wall_5_lower : 15.440 mm
passive wall_3_upper / wall_3_lower : 15.440 mm
passive wall_4_upper / wall_4_lower : 0.000 mm
active solenoid / solenoid : 0.000 mm
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/site-packages/freegsnke/up_down_symmetry.py:978: UserWarning: Limiter changed by intersection with its reflection about Z=0 m: removed 0.0470717 m² (5.3%); 120 -> 117 vertices.
_warn_boundary_change(original, symmetric, target_midplane, name)
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/site-packages/freegsnke/up_down_symmetry.py:978: UserWarning: Wall changed by intersection with its reflection about Z=0 m: removed 0.050868 m² (4.76%); 120 -> 117 vertices.
_warn_boundary_change(original, symmetric, target_midplane, name)
Let’s view the changes that have been made!
# plots the difference between the old and new machine
symmetric_machine_data.plot()
<Axes: title={'center': 'Original vs symmetrised machine geometry'}, xlabel='R [m]', ylabel='Z [m]'>
The next plot shows which coils and passives were linked together during the symmetrisation.
# Show the inferred pairings on the symmetrised machine description. The
# connecting lines are diagnostic only; they are not conductor geometry.
fig, ax = plt.subplots(figsize=(4,6))
plot_description(
ax,
symmetric_machine_data.active_coils_data,
symmetric_machine_data.passive_coils_data,
symmetric_machine_data.limiter_data,
title="Linked coils and passives",
)
for pair in symmetric_machine_data.active_pairs:
ru, zu = centroid(symmetric_machine_data.active_coils_data[pair.upper_name])
rl, zl = centroid(symmetric_machine_data.active_coils_data[pair.lower_name])
ax.plot([ru, rl], [zu, zl], color="tab:blue", alpha=0.35, linewidth=0.8)
passive_lookup = {item["name"]: item for item in symmetric_machine_data.passive_coils_data}
for pair in symmetric_machine_data.passive_pairs:
ru, zu = centroid(passive_lookup[pair.upper_name])
rl, zl = centroid(passive_lookup[pair.lower_name])
ax.plot([ru, rl], [zu, zl], color="tab:orange", alpha=0.35, linewidth=0.6)
plt.show()
Inspect geometric discrepancies
For each conductor pair with \(N\) discretisation (or polygon) points \(\mathbf{x}_{u,k}\) and \(\mathbf{x}_{l,k}\) (\(k = 1, \dots, N\)), the reported mismatch is the RMS Euclidean distance between the upper points and the reflected lower points before averaging:
For the limiter and wall, the symmetric footprint is the intersection of the outline with its reflection; whenever the footprint changes, a warning is emitted.
# check the biggest changes
largest = symmetric_machine_data.largest_geometry_discrepancies(count=10)
print("Largest pre-symmetrisation geometry discrepancies")
for record in largest:
print(
f"{record.component:8s} {record.upper_name:18s} / "
f"{record.lower_name:18s}: {1e3 * record.reflected_rms:6.3f} mm"
)
#
GEOMETRY_ACCEPTANCE = 0.050 # 50 mm RMS point distance
symmetric_machine_data.check_geometry_tolerance(GEOMETRY_ACCEPTANCE)
# lets plot them side by side
fig, axes = plt.subplots(1, 2, figsize=(8, 6), sharex=True, sharey=True)
plot_description(
axes[0],
active_source,
passive_source,
limiter_source,
title="Source geometry",
)
plot_description(
axes[1],
symmetric_machine_data.active_coils_data,
symmetric_machine_data.passive_coils_data,
symmetric_machine_data.limiter_data,
title="Exactly symmetric geometry",
)
plt.tight_layout()
plt.show()
Largest pre-symmetrisation geometry discrepancies
active PF6_upper / PF6_lower : 39.051 mm
active PF1_upper / PF1_lower : 39.051 mm
active PF5_upper / PF5_lower : 30.806 mm
active PF2_upper / PF2_lower : 30.806 mm
limiter upper path / lower path : 29.981 mm
wall upper path / lower path : 29.707 mm
passive wall_1_upper / wall_1_lower : 27.726 mm
passive wall_7_upper / wall_7_lower : 27.726 mm
active PF4_upper / PF4_lower : 25.710 mm
active PF3_upper / PF3_lower : 25.710 mm
Compare magnetic (Green-function) changes
We can compare the changes in Green’s function for the coils/passives in order to see how different things will be in the new machine.
Let \(G_{\mathrm{source}}\) and \(G_{\mathrm{sym}}\) denote the sampled Green-function matrices mapping unit conductor currents to poloidal flux on the equilibrium grid before and after symmetrisation, respectively. Using the Frobenius norm \(\lVert \cdot \rVert_F\), we report the relative percentage change separately for active and passive conductors:
A small value of \(\epsilon_G\) indicates that symmetrisation closely preserves the magnetic response of the original machine.
# Exclude the odd circuit from the source comparison so both bases have
# identical labels, ordering, and dimensions. The comparison then isolates
# recentering and geometric averaging, rather than circuit removal.
retained_source_active = {
name: deepcopy(active_source[name]) for name in symmetric_machine_data.original_active_names
}
raw_tokamak = build_machine.tokamak(
active_coils_data=retained_source_active,
passive_coils_data=passive_source,
limiter_data=limiter_source,
wall_data=wall_source,
)
symmetric_tokamak = build_machine.tokamak(
active_coils_data=symmetric_machine_data.active_coils_data,
passive_coils_data=symmetric_machine_data.passive_coils_data,
limiter_data=symmetric_machine_data.limiter_data,
wall_data=symmetric_machine_data.wall_data,
)
eq_kwargs = dict(
Rmin=0.05,
Rmax=1.95,
Zmin=-1.5,
Zmax=1.5,
nx=65,
ny=65,
psi=None,
)
# Equilibrium supplies a common grid and the sampled conductor Green basis;
# this audit does not require a Grad-Shafranov equilibrium solve.
raw_eq = equilibrium_update.Equilibrium(tokamak=raw_tokamak, **eq_kwargs)
symmetric_eq = equilibrium_update.Equilibrium(tokamak=symmetric_tokamak, **eq_kwargs)
# _vgreen is the internal conductor-to-grid poloidal-flux basis. Active rows
# precede passive rows; use the retained
# active count to split both machines at the same coordinate boundary.
n_active = len(symmetric_machine_data.original_active_names)
raw_active_g = raw_eq._vgreen[:n_active]
sym_active_g = symmetric_eq._vgreen[:n_active]
raw_passive_g = raw_eq._vgreen[n_active:]
sym_passive_g = symmetric_eq._vgreen[n_active:]
def percentage_change(original, updated):
return 100 * np.linalg.norm(updated - original) / np.linalg.norm(original)
active_change = percentage_change(raw_active_g, sym_active_g)
passive_change = percentage_change(raw_passive_g, sym_passive_g)
print(f"Active Green-basis change: {active_change:.4f}%")
print(f"Passive Green-basis change: {passive_change:.4f}%")
# The scalar percentages summarize the whole basis. Summing squared source
# rows gives a current-coordinate-independent basis magnitude at each grid
# point. Errors are normalized by its global maximum to avoid unstable local
# ratios where the source field basis is nearly zero.
active_strength = np.sqrt(np.sum(raw_active_g**2, axis=0))
passive_strength = np.sqrt(np.sum(raw_passive_g**2, axis=0))
active_error = np.sqrt(np.sum((sym_active_g - raw_active_g) ** 2, axis=0))
passive_error = np.sqrt(np.sum((sym_passive_g - raw_passive_g) ** 2, axis=0))
extent = [raw_eq.Rmin, raw_eq.Rmax, raw_eq.Zmin, raw_eq.Zmax]
Active coils --> built from user-provided data.
Passive structures --> built from user-provided data.
Limiter --> built from user-provided data.
Wall --> built from user-provided data.
Magnetic probes --> none provided.
Resistance (R) and inductance (M) matrices --> built using actives (and passives if present).
Tokamak built.
Active coils --> built from user-provided data.
Passive structures --> built from user-provided data.
Limiter --> built from user-provided data.
Wall --> built from user-provided data.
Magnetic probes --> none provided.
Resistance (R) and inductance (M) matrices --> built using actives (and passives if present).
Tokamak built.
Active Green-basis change: 3.3585%
Passive Green-basis change: 3.1781%
# plot the differences
fig, axes = plt.subplots(2, 2, figsize=(8, 10), sharex=True, sharey=True)
maps = [
(active_strength, "source active basis magnitude"),
(100 * active_error / np.max(active_strength), "active change / max source [%]"),
(passive_strength, "source passive basis magnitude"),
(
100 * passive_error / np.max(passive_strength),
"passive change / max source [%]",
),
]
for ax, (field, title) in zip(axes.flat, maps):
image = ax.imshow(field.T, origin="lower", extent=extent, aspect="auto")
ax.set_title(title)
ax.set_xlabel("R [m]")
ax.set_ylabel("Z [m]")
fig.colorbar(image, ax=ax, shrink=0.82)
plt.tight_layout()
plt.show()
Transform currents between original and reduced bases
PreparedUpDownMachine exposes the linear maps between the original active-current vector \(\mathbf{I}\) and the reduced even and odd current vectors \(\mathbf{I}_+\) and \(\mathbf{I}_-\):
where \(T_+\) (active_original_to_even) and \(T_-\) (active_original_to_odd) project onto the even and odd bases, and \(U_+\) (active_even_to_original) and \(U_-\) (active_odd_to_original) map back to the original circuit basis. Here we verify that split_active_currents() and combine_active_currents() invert one another to machine precision.
# A synthetic reconstructed current vector in the documented retained order.
# The excluded vertical_control circuit is intentionally not part of this
# transform because strict even evolution has no coordinate for it.
original_currents = np.array(
[7_000.0]
+ [
value
for pair in [
(2_100, 1_900),
(-3_200, -2_800),
(4_200, 3_900),
(-2_500, -2_650),
(3_100, 2_850),
(-1_700, -1_450),
]
for value in pair
]
)
assert len(original_currents) == len(symmetric_machine_data.original_active_names)
# Pair averages are the currents retained by strict even evolution; pair
# differences quantify the odd content discarded by that projection.
even_currents, odd_currents = symmetric_machine_data.split_active_currents(original_currents)
# Keeping both coordinates must reconstruct the source exactly. Omitting
# odd_currents deliberately returns the closest exactly even vector.
reconstructed = symmetric_machine_data.combine_active_currents(even_currents, odd_currents)
even_projection = symmetric_machine_data.combine_active_currents(even_currents)
np.testing.assert_allclose(reconstructed, original_currents)
print("Original active order:", symmetric_machine_data.original_active_names)
print("Reduced even order: ", symmetric_machine_data.even_active_names)
print("Odd pair coordinates: ", symmetric_machine_data.active_odd_names)
print(
f"Reconstruction error: "
f"{np.linalg.norm(reconstructed - original_currents):.3e} A"
)
# plot differences
x = np.arange(len(original_currents))
width = 0.38
fig, axes = plt.subplots(2, 1, figsize=(8, 6), constrained_layout=True)
axes[0].bar(x - width / 2, original_currents, width, label="original")
axes[0].bar(x + width / 2, even_projection, width, label="even projection")
axes[0].set_xticks(x, symmetric_machine_data.original_active_names, rotation=55, ha="right")
axes[0].set_ylabel("current [A]")
axes[0].set_title("Original currents and their exactly even projection")
axes[0].legend()
odd_x = np.arange(len(odd_currents))
axes[1].bar(odd_x, odd_currents, color="tab:orange")
axes[1].set_xticks(odd_x, symmetric_machine_data.active_odd_names, rotation=35, ha="right")
axes[1].set_ylabel("odd current coordinate [A]")
axes[1].set_title("Discarded upper/lower current differences")
plt.show()
Original active order: ('solenoid', 'PF1_upper', 'PF1_lower', 'PF2_upper', 'PF2_lower', 'PF3_upper', 'PF3_lower', 'PF4_upper', 'PF4_lower', 'PF5_upper', 'PF5_lower', 'PF6_upper', 'PF6_lower')
Reduced even order: ('solenoid', 'PF1', 'PF2', 'PF3', 'PF4', 'PF5', 'PF6')
Odd pair coordinates: ('PF1', 'PF2', 'PF3', 'PF4', 'PF5', 'PF6')
Reconstruction error: 0.000e+00 A
Summary
In summary, the new prepare_up_down_symmetric_machine():
Fits and removes a common vertical offset when
z_midplane="auto".Identifies reflected active and passive element pairs and records pre-averaging geometric mismatches.
Averages paired geometry onto exact reflection symmetry and intersects the limiter and wall with their reflections.
Detects and explicitly records electrically odd active circuits.
Provides linear transforms between original and even/odd active-current coordinates, together with the passive reflection operator \(S_p\) needed for reduced dynamics.
Deciding whether the resulting Green-function and geometric changes are physically acceptable remains a modelling choice for the user. Furthermore, excluded odd active circuits are not modelled in the strictly even solver.
Let’s take a look at the final up-down symmetric machine and some summary statistics.
# Passive elements remain separate in the machine description. Their
# reflection operator lets the evolutive solver select even passive modes.
passive_reflection = symmetric_machine_data.passive_reflection_operator
np.testing.assert_allclose(passive_reflection, passive_reflection.T)
np.testing.assert_allclose(
passive_reflection @ passive_reflection,
np.eye(len(passive_reflection)),
)
# (I + S_p) / 2 projects passive currents onto the even subspace. The trace
# of a projector is its rank, hence the number of retained passive modes.
n_passive_even = int(
np.trace((np.eye(len(passive_reflection)) + passive_reflection) / 2)
)
print("Final active series circuits:", symmetric_machine_data.even_active_names)
print("Final passive elements: ", len(symmetric_machine_data.passive_names))
print("Passive even coordinates: ", n_passive_even)
print("Odd source circuits omitted: ", symmetric_machine_data.excluded_odd_active_names)
Final active series circuits: ('solenoid', 'PF1', 'PF2', 'PF3', 'PF4', 'PF5', 'PF6')
Final passive elements: 18
Passive even coordinates: 9
Odd source circuits omitted: ('vertical_control',)
# final machine
fig, ax = plt.subplots(figsize=(4, 6))
symmetric_tokamak.plot(axis=ax, show=False)
ax.plot(symmetric_tokamak.limiter.R, symmetric_tokamak.limiter.Z, "k-", linewidth=1.2)
ax.plot(symmetric_tokamak.wall.R, symmetric_tokamak.wall.Z, "r-", linewidth=1.2)
ax.axhline(0.0, color="0.35", linewidth=0.8, linestyle=":")
ax.set( xlabel="Major radius, R [m]", ylabel="Height, Z [m]", aspect="equal")
ax.set_xlim(0.05, 1.95)
ax.set_ylim(-1.5, 1.5)
plt.show()