pymkm.io¶
I/O submodule for pyMKM.
This package provides functionality to load, manage, and serialize stopping power (LET) data used by the Microdosimetric Kinetic Model. It handles both individual ion tables and structured collections of precomputed datasets.
Modules¶
data_registry
: Functions for discovering and loading default .txt stopping power tables and the periodic table lookup (elements.json). See functions likeget_default_txt_path()
andload_lookup_table()
.stopping_power
: Defines theStoppingPowerTable
for parsing, validating, interpolating and plotting LET curves for a single ion.table_set
: ProvidesStoppingPowerTableSet
, a high-level container for multiple ion tables with utilities for batch resampling, filtering, and plotting.
- class pymkm.io.StoppingPowerTable(ion_input: str | int, energy: ndarray, let: ndarray, mass_number: int | None = None, source_program: str | None = None, ionization_potential: float | None = None)[source]¶
Bases:
object
Class for representing and handling stopping power (LET) data for ions in liquid water.
Provides utilities for data validation, plotting, serialization, and interpolation. :attr REQUIRED_HEADER_KEYS: Required header keys for parsing stopping power tables. :attr REQUIRED_DICT_KEYS: Required dictionary keys for internal representation. :attr DEFAULT_TARGET: Default target material (
WATER_LIQUID
).- DEFAULT_TARGET = 'WATER_LIQUID'¶
- REQUIRED_DICT_KEYS = ['ion_symbol', 'atomic_number', 'mass_number', 'source_program', 'ionization_potential', 'target']¶
- REQUIRED_HEADER_KEYS = ['Ion', 'AtomicNumber', 'MassNumber', 'SourceProgram', 'IonizationPotential', 'Target']¶
- property energy_grid: ndarray¶
Access the energy array (grid).
- Returns:
Energy values.
- Return type:
np.ndarray
- static from_dict(data: Dict) StoppingPowerTable [source]¶
Create a
StoppingPowerTable
instance from a serialized dictionary.The input dictionary must contain at least the required fields listed in
StoppingPowerTable.REQUIRED_DICT_KEYS
, also listed below.Expected dictionary format:
{ "ion_symbol": H, # str, symbol of the ion "energy": [...], # list/array of float, energy values (MeV/u) "let": [...], # list/array of float, corresponding stopping powers (MeV/cm) "mass_number": 1, # int, mass number of the ion "source_program": fluka_2020_0 # str, program used to generate data "ionization_potential": 75.0 # float, ionization potential (eV) }
- Parameters:
data (dict) – Dictionary containing serialized table data.
- Returns:
A new
StoppingPowerTable
instance.- Return type:
- Raises:
ValueError – If required fields are missing.
- static from_txt(filepath: str) StoppingPowerTable [source]¶
Create a
StoppingPowerTable
from a .txt file containing header and data.The input file must contain a header with required fields and a data section with energy and LET values. The header must include the
Ion
,AtomicNumber
,MassNumber
,SourceProgram
,IonizationPotential
, andTarget
(case-sensitive) fields.Example header:
SourceProgram=fluka_2020_0 Target=WATER_LIQUID IonizationPotential=77.0 Ion=H AtomicNumber=1 MassNumber=1
The data section should contain energy and LET values in two columns, expressed in MeV/u and MeV/cm respectively.
- Parameters:
filepath (str) – Path to the input .txt file.
- Returns:
StoppingPowerTable
instance parsed from file.- Return type:
- Raises:
ValueError – If required header keys or element definitions are missing or inconsistent.
- classmethod get_lookup_table() Dict[str, Dict[str, int]] [source]¶
Retrieve the ion properties lookup table used to resolve ion metadata.
The table maps element names (e.g., “Carbon”) to their symbol, atomic number, mass number, and display color. Based on IUPAC reference data from: https://ciaaw.org/atomic-weights.htm
- Returns:
A dictionary with element names as keys and their properties as nested dictionaries.
- Return type:
dict[str, dict[str, int]]
- interpolate(*, energy: ndarray | None = None, let: ndarray | None = None, loglog: bool = True)[source]¶
Interpolate LET or energy values using internal data.
Delegates to Interpolator and supports log-log interpolation.
- Parameters:
energy (Optional[np.ndarray]) – Energy values at which to compute LET.
let (Optional[np.ndarray]) – LET values at which to compute corresponding energies.
loglog (bool) – Whether to perform interpolation in log-log space.
- Returns:
Interpolated LETs or a dict of energies for each LET.
- Return type:
np.ndarray or dict[float, np.ndarray]
- property ion_name: str¶
Get the ion symbol (e.g., “C” for carbon).
- Returns:
Ion symbol string.
- Return type:
str
- plot(label: str | None = None, show: bool = True, ax: Axes | None = None)[source]¶
Plot stopping power (LET) as a function of energy.
- Parameters:
label (Optional[str]) – Optional label for the plot legend.
show (bool) – Whether to call plt.show().
ax (Optional[matplotlib.axes.Axes]) – Matplotlib Axes object to draw on. If None, a new figure is created.
- resample(new_grid: ndarray)[source]¶
Resample the LET curve onto a new energy grid using log-log interpolation.
- Parameters:
new_grid (np.ndarray) – The target energy grid (must be strictly increasing).
- Raises:
ValueError – If the new grid is not strictly increasing.
- property stopping_power: ndarray¶
Access the LET (stopping power) array.
- Returns:
LET values.
- Return type:
np.ndarray
- class pymkm.io.StoppingPowerTableSet[source]¶
Bases:
object
A container for managing multiple StoppingPowerTable instances.
Provides unified access to stopping power curves for multiple ions, identified by name, symbol, or atomic number. Supports serialization, resampling, filtering, and plotting.
- add(ion_input: str, table: StoppingPowerTable)[source]¶
Add a stopping power table to the set.
- Parameters:
ion_input (str) – Ion identifier (name, symbol, or atomic number).
table (pymkm.io.stopping_power.StoppingPowerTable) – Instance of
StoppingPowerTable
to add.
- filter_by_ions(ion_inputs: List[str]) StoppingPowerTableSet [source]¶
Create a subset containing only the specified ions. Each table is a
StoppingPowerTable
instance.- Parameters:
ion_inputs (list[str]) – List of identifiers (names, symbols, or atomic numbers).
- Returns:
New StoppingPowerTableSet with selected ions.
- Return type:
- classmethod from_default_source(source: str) StoppingPowerTableSet [source]¶
Load tables from a default internal source (e.g., “mstar_3_12”).
- Parameters:
source (str) – Name of the predefined source directory.
- Returns:
Table set initialized from source.
- Return type:
- Raises:
RuntimeError – If any file cannot be loaded.
- classmethod from_dict(data: Dict[str, dict]) StoppingPowerTableSet [source]¶
Create a
StoppingPowerTableSet
set from a dictionary.The input dictionary must map ion names to serialized stopping power tables. Each table dictionary must be a valid input for
from_dict()
.Expected dictionary format:
{ "Hydrogen": {}, "Helium": {}, ... }
- Parameters:
data (dict[str, dict]) – Dictionary mapping ion names to serialized tables.
- Returns:
StoppingPowerTableSet instance.
- Return type:
- Raises:
ValueError – If tables have inconsistent source program or ionization potential.
- classmethod from_directory(directory: str) StoppingPowerTableSet [source]¶
Load
StoppingPowerTable
instances from .txt files in a directory.Each file must follow the format described in
from_txt()
.- Parameters:
directory (str) – Path to directory containing .txt files.
- Returns:
StoppingPowerTableSet with all successfully loaded tables.
- Return type:
- classmethod from_json(json_str: str) StoppingPowerTableSet [source]¶
Create a
StoppingPowerTableSet
from a JSON string.The JSON must represent a dictionary mapping ion names to serialized stopping power tables. Each table must follow the format accepted by
from_dict()
.- Parameters:
json_str (str) – JSON-formatted table set string.
- Returns:
Deserialized
StoppingPowerTableSet
.- Return type:
- get(ion_input: str) StoppingPowerTable | None [source]¶
Retrieve a table by ion identifier.
- Parameters:
ion_input (str) – Ion name, symbol, or atomic number.
- Returns:
Corresponding
StoppingPowerTable
or None.- Return type:
- get_available_ions() List[str] [source]¶
Get the list of ion names present in the set.
- Returns:
List of ion names.
- Return type:
list[str]
- get_common_energy_range() List[float] | None [source]¶
Get the overlapping energy range across all tables.
- Returns:
[min, max] energy range, or None if no common range exists.
- Return type:
list[float] or None
- get_energy_grid(ion_input: str) ndarray [source]¶
Get the energy grid for a given ion.
- Parameters:
ion_input (str) – Ion identifier.
- Returns:
Energy array.
- Return type:
np.ndarray
- get_stopping_power(ion_input: str) ndarray [source]¶
Get the stopping power values for a given ion.
- Parameters:
ion_input (str) – Ion identifier.
- Returns:
LET array.
- Return type:
np.ndarray
- interpolate_all(energy: ndarray, loglog: bool = True) Dict[str, ndarray] [source]¶
Interpolate LET values at given energies for all tables.
- Parameters:
energy (np.ndarray) – Energy values at which to interpolate.
loglog (bool) – Use log-log interpolation if True.
- Returns:
Dictionary mapping ion names to interpolated LET arrays.
- Return type:
dict[str, np.ndarray]
- classmethod load(filepath: str) StoppingPowerTableSet [source]¶
Load a table set from a JSON file.
- Parameters:
filepath (str) – Path to JSON file.
- Returns:
Loaded StoppingPowerTableSet.
- Return type:
- plot(ions: List[str] | None = None, show: bool = True, ax: Axes | None = None, single_plot: bool = True)[source]¶
Plot stopping power curves for one or more ions.
- Parameters:
ions (Optional[List[str]]) – List of ion identifiers to plot. If None, all are plotted.
show (bool) – Whether to call plt.show().
ax (Optional[matplotlib.axes.Axes]) – Matplotlib Axes object to draw on. If None, a new figure is created.
single_plot (bool) – If True, plot all ions on one figure; otherwise, one figure per ion.
- remove(ion_input: str)[source]¶
Remove a table by ion identifier.
- Parameters:
ion_input (str) – Ion name, symbol, or atomic number.
- resample_all(new_grid: ndarray)[source]¶
Resample the LET curves of all tables onto a new energy grid.
- Parameters:
new_grid (np.ndarray) – Strictly increasing energy grid in MeV/u.
- Raises:
ValueError – If the grid is not strictly increasing.
- save(filepath: str)[source]¶
Save the table set to a JSON file.
- Parameters:
filepath (str) – Output file path.
- to_dict() Dict[str, dict] [source]¶
Serialize all tables to a dictionary.
- Returns:
Dictionary of ion names to serialized data.
- Return type:
dict[str, dict]
Submodules¶
- pymkm.io.data_registry
- pymkm.io.stopping_power
- Main features
StoppingPowerTable
StoppingPowerTable.DEFAULT_TARGET
StoppingPowerTable.REQUIRED_DICT_KEYS
StoppingPowerTable.REQUIRED_HEADER_KEYS
StoppingPowerTable.energy_grid
StoppingPowerTable.from_dict()
StoppingPowerTable.from_txt()
StoppingPowerTable.get_lookup_table()
StoppingPowerTable.interpolate()
StoppingPowerTable.ion_name
StoppingPowerTable.plot()
StoppingPowerTable.resample()
StoppingPowerTable.stopping_power
StoppingPowerTable.to_dict()
- pymkm.io.table_set
- Main features
StoppingPowerTableSet
StoppingPowerTableSet.add()
StoppingPowerTableSet.filter_by_ions()
StoppingPowerTableSet.from_default_source()
StoppingPowerTableSet.from_dict()
StoppingPowerTableSet.from_directory()
StoppingPowerTableSet.from_json()
StoppingPowerTableSet.get()
StoppingPowerTableSet.get_available_ions()
StoppingPowerTableSet.get_common_energy_range()
StoppingPowerTableSet.get_energy_grid()
StoppingPowerTableSet.get_stopping_power()
StoppingPowerTableSet.interpolate_all()
StoppingPowerTableSet.items()
StoppingPowerTableSet.keys()
StoppingPowerTableSet.load()
StoppingPowerTableSet.plot()
StoppingPowerTableSet.remove()
StoppingPowerTableSet.resample_all()
StoppingPowerTableSet.save()
StoppingPowerTableSet.to_dict()
StoppingPowerTableSet.to_json()
StoppingPowerTableSet.values()