Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.11"]
python-version: ["3.12"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.11"]
python-version: ["3.12"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.11"]
python-version: ["3.12"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
Expand Down
28 changes: 25 additions & 3 deletions docs/source/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Available Settings
- **use_IDS_plasma_composition**: (bool) whether to use plasma composition from input core_profiles IDS on F_INIT or from TORAX config. Defaults to False (i.e. use TORAX config).
- **t_initial**: (float) starting time of TORAX actor.
- **t_final**: (float) ending time of TORAX actor.
- **fixed_dt**: (float) timestep of TORAX actor.
- **fixed_dt**: (float) timestep of TORAX actor (``time_step_calculator.dt``, fixed calculator only).
- **communication_interval**: (float) time interval at which to send/receive data through MUSCLE3 connections. Common to all connected ports. Defaults to 1e-6 seconds.
- **max_consecutive_invalid_input**: (int) abort the run if a single port receives ``output_flag == -1`` this many times in a row. Defaults to unset, i.e. tolerate invalid input indefinitely. See `Handling invalid input`_ below.

Expand All @@ -57,11 +57,11 @@ would otherwise silently loop until some other timeout.
Simulated time window
---------------------

The simulated time window (``numerics.t_initial`` / ``numerics.t_final``) is
The simulated time window (``time_step_calculator.t_initial`` / ``t_final``) is
resolved from up to three sources, listed from lowest to highest precedence — a
later source overrides an earlier one key-by-key:

1. the ``numerics`` block in the TORAX config file (``python_config_module``);
1. the ``time_step_calculator`` block in the TORAX config file (``python_config_module``);
2. the **first and last** ``time`` of the equilibrium sequence received on
``equilibrium_in_f`` on F_INIT, if that port is connected. This lets a coupled
driver size the run from the data it sends, so the config file needs no
Expand Down Expand Up @@ -95,3 +95,25 @@ The Torax actor currently only has IDS coupling functionality for both input and
General
-------
The torax actor can be used with IMAS DDv4.

Equilibrium and core_profiles input
-----------------------------------

A received equilibrium sets TORAX's geometry and its plasma current
(``profile_conditions.I_p_source = 'geometry'``). Received core_profiles update
``profile_conditions`` key by key, but never the ``I_p_source`` /
``psi_source`` choices, which stay as set in the TORAX config.

To let the equilibrium code control psi (e.g. NICE evolutive with resistive
diffusion), set in the TORAX config::

"numerics": {"evolve_current": False},
"profile_conditions": {
"I_p_source": "geometry",
"psi_source": "geometry",
},

TORAX then takes psi from every received equilibrium (rebuilt from its
``j_phi``), and any psi in received core_profiles is ignored. The geometry in the
config must not be ``circular``; it is a placeholder replaced by the received
equilibrium.
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ authors = [
]
description = "TORAX IMAS MUSCLE3 wrapper"
readme = {file = "README.md", content-type = "text/markdown"}
requires-python = ">=3.11"
requires-python = ">=3.12"
license = {file = "LICENSE.txt"}
classifiers = [
"Development Status :: 3 - Alpha",
Expand Down Expand Up @@ -50,7 +50,8 @@ dependencies = [
"importlib_resources",
"rich",
"packaging",
"torax[dev]==1.4.0",
# "torax>=2",
"torax[dev] @ git+https://github.com/mikesndrs/torax.git@e96465188bf376c257bf4977bd775c710defe439",
"imas-python",
"muscle3>=0.10",
]
Expand Down
47 changes: 32 additions & 15 deletions torax_muscle3/tests/basic_config.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
"""Simplified config using mostly defaults for various simulation components."""

CONFIG = {
"profile_conditions": {}, # use default profile conditions
"plasma_composition": {}, # use default plasma composition
"numerics": {
"t_initial": 0,
"t_final": 5,
"fixed_dt": 0.1,
"adaptive_dt": False,
"profile_conditions": {
"I_p": 15e6,
"psi_source": "geometry",
},
"plasma_composition": {}, # use default plasma composition
"numerics": {},
# circular geometry is only for testing and prototyping
"geometry": {
"geometry_type": "chease",
"model_name": "chease",
"geometry_file": "iterhybrid.mat2cols",
"Ip_from_parameters": True,
"R_major": 6.2, # major radius (R) in meters
"a_minor": 2.0, # minor radius (a) in meters
"B_0": 5.3, # Toroidal magnetic field on axis [T]
Expand All @@ -23,25 +20,45 @@
},
"sources": {
# Current sources (for psi equation)
"generic_current": {},
"generic_current": {
"fraction_of_total_current": 0.2,
"gaussian_width": 0.05,
"gaussian_location": 0.4,
},
# Electron density sources/sink (for the n_e equation).
"generic_particle": {},
"gas_puff": {},
"pellet": {},
"generic_particle": {
"S_total": 1e22,
"particle_width": 0.25,
"deposition_location": 0.0,
},
"gas_puff": {"S_total": 1e22, "puff_decay_length": 0.05},
"pellet": {
"S_total": 2e22,
"pellet_width": 0.1,
"pellet_deposition_location": 0.85,
},
# Ion and electron heat sources (for the temp-ion and temp-el eqs).
"generic_heat": {},
"generic_heat": {
"P_total": 120e6,
"gaussian_width": 0.25,
"gaussian_location": 0.0,
"electron_heat_fraction": 0.66666,
},
"fusion": {},
"ei_exchange": {},
"ohmic": {},
},
"pedestal": {},
"transport": {
"model_name": "constant",
"core_transport_models": {"prescribed": {"model_name": "prescribed"}},
},
"solver": {
"solver_type": "linear",
},
"time_step_calculator": {
"calculator_type": "chi",
"t_initial": 0,
"t_final": 5,
"allow_backtracking": False,
},
}
13 changes: 13 additions & 0 deletions torax_muscle3/tests/psi_from_geometry_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""basic_config with psi owned by the received equilibrium (fixed time stepping)."""

import copy

from torax_muscle3.tests.basic_config import CONFIG as BASIC_CONFIG

CONFIG = copy.deepcopy(BASIC_CONFIG)
CONFIG["numerics"]["evolve_current"] = False
CONFIG["time_step_calculator"] = {
**CONFIG["time_step_calculator"],
"calculator_type": "fixed",
"dt": 0.1,
}
6 changes: 5 additions & 1 deletion torax_muscle3/tests/sawtooth_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@
"redistribution_model": {"model_name": "simple"},
}
}
CONFIG["time_step_calculator"] = {"calculator_type": "fixed"}
CONFIG["time_step_calculator"] = {
**CONFIG["time_step_calculator"],
"calculator_type": "fixed",
"dt": 0.1,
}
81 changes: 71 additions & 10 deletions torax_muscle3/tests/test_actor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
import multiprocessing
import sys
from pathlib import Path
from typing import Any, Dict, Optional
Expand Down Expand Up @@ -34,6 +35,7 @@
CORE_SOURCES_DATA_PATH = TESTS_DIR / "data" / "core_sources_ddv4.nc"
CONFIG_PATH = TESTS_DIR / "basic_config.py"
SAWTOOTH_CONFIG_PATH = TESTS_DIR / "sawtooth_config.py"
PSI_CONFIG_PATH = TESTS_DIR / "psi_from_geometry_config.py"

# ---------------------------------------------------------------------------
# MuscleTester-based tests: drive the real torax actor directly through the
Expand Down Expand Up @@ -285,6 +287,59 @@ def test_torax_sawtooth_keeps_announced_timestamps(
tester.receive("core_profiles_out_f")


def psi_rise(core_profiles: IDSToplevel) -> float:
"""Gauge-free psi measure: psi(rho_norm=0.5) - psi(axis)."""
grid = core_profiles.profiles_1d[0].grid
return float(np.interp(0.5, grid.rho_tor_norm, grid.psi) - grid.psi[0])


@pytest.mark.filterwarnings("ignore:.*use of fork():DeprecationWarning")
def test_torax_psi_from_equilibrium(muscle3_tester: MuscleTester) -> None:
"""With psi_source='geometry' and evolve_current=False, psi follows the in_s equilibrium,
also when core_profiles are received alongside it."""
config = build_config(
{
"s": ["equilibrium_in_s", "core_profiles_in_s"],
"o_i": ["core_profiles_out_i"],
"o_f": ["core_profiles_out_f"],
},
settings={
"torax.python_config_module": str(PSI_CONFIG_PATH),
"torax.t_final": 0.3,
},
)
tester = muscle3_tester.start_implementation(config, "torax", default_timeout=120)

reference = load_ids(EQUILIBRIUM_DATA_PATH, "equilibrium")
rises = []
while True:
request = tester.receive("core_profiles_out_i")
rises.append(psi_rise(deserialize("core_profiles", request.data)))
# current, and with it the geometry psi, doubles after the first reply
reply = copy.deepcopy(reference)
scale = 1.0 if len(rises) == 1 else 2.0
reply.time = [request.timestamp]
reply.time_slice[0].profiles_1d.j_phi *= scale
reply.time_slice[0].global_quantities.ip *= scale
for port, data in (
("equilibrium_in_s", reply.serialize()),
("core_profiles_in_s", request.data),
):
tester.send(
port,
Message(
request.timestamp,
data=data,
next_timestamp=request.next_timestamp,
),
)
if request.next_timestamp is None:
break

tester.receive("core_profiles_out_f")
assert rises[2] / rises[1] == pytest.approx(2.0, rel=0.02)


# ---------------------------------------------------------------------------
# Checkpoint/resume test: exercises MUSCLE3's snapshot/resume mechanics across
# two separate manager runs. MuscleTester/ImplementationTester has no
Expand Down Expand Up @@ -399,6 +454,8 @@ def sink_for_tests():
@pytest.mark.filterwarnings("ignore:.*use of fork():DeprecationWarning")
def test_checkpoint(tmp_path, monkeypatch, ymmsl_text, ymmsl_resume):
monkeypatch.chdir(tmp_path)
# Forking after JAX has initialised in this process (e.g. by another test) aborts
monkeypatch.setattr(libmuscle.runner, "mp", multiprocessing.get_context("spawn"))

filename = "ITERhybrid_COCOS17_IDS_ddv4.nc"
data_source_path = f"{torax_muscle3.__path__[0]}/tests/data/{filename}"
Expand Down Expand Up @@ -440,26 +497,26 @@ def test_checkpoint(tmp_path, monkeypatch, ymmsl_text, ymmsl_resume):
def test_time_window_from_equilibrium():
"""t_range from the received equilibrium sequence sets the window."""
assert numerics_overrides((1.5, 3.25), NO_YMMSL_NUMERICS) == {
"numerics.t_initial": 1.5,
"numerics.t_final": 3.25,
"time_step_calculator.t_initial": 1.5,
"time_step_calculator.t_final": 3.25,
}


def test_ymmsl_numerics_override_equilibrium_window():
"""Explicit ymmsl t_initial/t_final win over the equilibrium-derived range."""
assert numerics_overrides(
(1.5, 3.25), {"t_initial": 2.0, "t_final": 4.0, "fixed_dt": None}
) == {"numerics.t_initial": 2.0, "numerics.t_final": 4.0}
) == {"time_step_calculator.t_initial": 2.0, "time_step_calculator.t_final": 4.0}


def test_partial_ymmsl_keeps_equilibrium_window():
"""A ymmsl override of only fixed_dt leaves the equilibrium window intact."""
assert numerics_overrides(
(1.5, 3.25), {"t_initial": None, "t_final": None, "fixed_dt": 0.05}
) == {
"numerics.t_initial": 1.5,
"numerics.t_final": 3.25,
"numerics.fixed_dt": 0.05,
"time_step_calculator.t_initial": 1.5,
"time_step_calculator.t_final": 3.25,
"time_step_calculator.dt": 0.05,
}


Expand Down Expand Up @@ -503,7 +560,11 @@ def test_ec_power_density():
deposited = np.trapezoid(np.interp(rho_eq, r, d), scale * rho_eq**2)
np.testing.assert_allclose(deposited, 1e6 if t == 0.0 else 2e6, rtol=1e-4)

config["sources"]["ecrh"] = {}
config["sources"]["ecrh"] = {
"P_total": 1e6,
"gaussian_width": 0.1,
"gaussian_location": 0.3,
}
assert ec_deposition_shape(torax.ToraxConfig.from_dict(config)) is None


Expand All @@ -526,9 +587,9 @@ class Geo(pydantic.BaseModel):
runner = ToraxMuscleRunner.__new__(ToraxMuscleRunner)
runner.t_cur, runner.t_target = 1.0, 1.1
configs = runner.stepwise_geometry_configs(a)
assert configs == {"1.0": a, "1.1": a} and configs["1.0"] is not a
assert configs == {1.0: a, 1.1: a} and configs[1.0] is not a
runner.t_cur, runner.t_target = 1.1, 1.2
configs = runner.stepwise_geometry_configs(b)
assert configs == {"1.1": a, "1.2": b} and configs["1.1"] is not a
assert configs == {1.1: a, 1.2: b} and configs[1.1] is not a
runner.t_target = 1.1
assert runner.stepwise_geometry_configs(c) == {"1.1": c}
assert runner.stepwise_geometry_configs(c) == {1.1: c}
Loading
Loading