Skip to content

narumii.simpson

narumii.simpson

Simulator dataclass

Simulator(simpson_path, params=dict())

Simulator for running SIMPSON simulations.

Parameters:

Name Type Description Default
simpson_path str

Path to the SIMPSON executable binary that will be invoked.

required

Attributes:

Name Type Description
simpson_path str

Path to the SIMPSON executable.

params dict[str, str]

Dictionary of parameter names and stringified values that will be substituted into the input template.

filenames dict[str, str]

Filenames used for input/output when running simulations. Populated when create_filenames is used or when provided to simulate.

b, spin_rate, angle_set optional

Optional simulation parameters set when calling simulate.

simulate

simulate(filenames=None, b=None, spin_rate=None, angle_set=None, **kwargs)

Run a single SIMPSON simulation using the current settings.

Parameters:

Name Type Description Default
filenames dict[str, str] or None

Filename mapping to use for this run. If provided, it will be stored on the simulator instance. If not provided, the instance must already have a filenames attribute (otherwise a ValueError is raised).

None
b float or None

Dipolar coupling constant to set for this run. When provided, it is stored in self.params['beff'] (default: None).

None
spin_rate float or None

Rotor/spin rate to set for this run (stored as self.params['spin_rate']) (default: None).

None
angle_set list[float] or None

List of six Euler angles; when provided they will be stored in self.params['angle1']..'angle6' (default: None).

None
**kwargs dict

Additional parameter key/value pairs to insert into self.params before running the simulation.

{}

Returns:

Type Description
float

Elapsed wall-clock time for the call to the SIMPSON executable, in seconds.

Raises:

Type Description
ValueError

If no filenames mapping is available on the simulator instance.

Optimizer dataclass

Optimizer(simpson_path, params=dict(), exp_type='CTDrenar', data_parser_exp=None, data_parser_sim=None)

Bases: Simulator

Optimizer that runs repeated SIMPSON simulations to fit parameters.

Inherits from :class:Simulator and adds helpers to parse experimental and simulated data, compute residuals, and perform scalar optimization (currently using scipy.optimize.minimize_scalar).

Attributes:

Name Type Description
exp_type str

Experiment type used to choose a default data parser (e.g. 'CTDrenar', 'REDOR', 'DQ').

data_parser_exp, data_parser_sim callable or None

Functions that extract comparison vectors from experimental and simulated output files. If not provided, a default is selected from exp_type.

param_name str

Name of the parameter being optimized (e.g. 'beff').

residual_function callable

Function that computes the residual between simulated and experimental data (e.g. RMSD).

bounds Sequence[float]

Bounds passed to the scalar optimizer.

optimize

optimize(param_name, residual_function, bounds, method, options)

Run scalar optimization to fit a single simulation parameter.

Parameters:

Name Type Description Default
param_name str

Name of the parameter to optimize. If the user supplies 'b' it is translated to 'beff' internally.

required
residual_function callable

Function accepting two arrays (simulated, experimental) and returning a scalar residual. If None, a default RMSD function is used.

required
bounds Sequence

Two-element sequence giving (min, max) bounds for the optimizer.

required
method str

Method passed to scipy.optimize.minimize_scalar (e.g. 'bounded').

required
options dict

Additional solver options passed to the optimizer.

required

Returns:

Type Description
tuple

(x_opt, fun_opt, elapsed_time) where x_opt is the best-fit parameter value, fun_opt is the residual at that value, and elapsed_time is the total wall-clock time spent in seconds.

simulate

simulate(filenames=None, b=None, spin_rate=None, angle_set=None, **kwargs)

Run a single SIMPSON simulation using the current settings.

Parameters:

Name Type Description Default
filenames dict[str, str] or None

Filename mapping to use for this run. If provided, it will be stored on the simulator instance. If not provided, the instance must already have a filenames attribute (otherwise a ValueError is raised).

None
b float or None

Dipolar coupling constant to set for this run. When provided, it is stored in self.params['beff'] (default: None).

None
spin_rate float or None

Rotor/spin rate to set for this run (stored as self.params['spin_rate']) (default: None).

None
angle_set list[float] or None

List of six Euler angles; when provided they will be stored in self.params['angle1']..'angle6' (default: None).

None
**kwargs dict

Additional parameter key/value pairs to insert into self.params before running the simulation.

{}

Returns:

Type Description
float

Elapsed wall-clock time for the call to the SIMPSON executable, in seconds.

Raises:

Type Description
ValueError

If no filenames mapping is available on the simulator instance.

create_filenames

create_filenames(basename, template=None, **kwargs)

Create filenames for simulation files from a basename.

Parameters:

Name Type Description Default
basename str

Base name for simulation files (without extension).

required
template str or None

Path to a template file to use. If None, the default basename + '.template' will be used (default: None).

None
**kwargs str

Extra filename mappings to include in the returned dict.

{}

Returns:

Type Description
dict[str, str]

Mapping of filename keys to their paths. Always contains keys 'input', 'output', 'log', 'txt' and 'template', plus any additional items from kwargs.

create_input_file

create_input_file(filenames, params=None)

Generate a SIMPSON input file by substituting parameters into a template.

The template file is read from filenames['template'] and occurrences of the token VALUE_{KEY} (where KEY is an upper-case parameter name) are replaced with the corresponding value from params.

Parameters:

Name Type Description Default
filenames dict[str, str]

Mapping that must contain at least the keys 'template', 'input' and 'output'. 'template' is the path to the template file; 'input' is the path to write the generated input file; 'output' is the expected SIMPSON output filename and will be inserted into the template as the value for output_file.

required
params dict[str, str] or None

Parameter values to substitute into the template. Keys are case- insensitive and will be converted to the placeholder format VALUE_{KEY} when performing replacements. If None, an empty parameter set is used (default: None).

None

Raises:

Type Description
FileNotFoundError

If the template file (filenames['template']) does not exist.

Returns:

Type Description
None

run_simulation

run_simulation(simpson_path, basename='./new_simulation', template=None, beff=None, params=[], verbose=True)

Run a single Simpson simulation using an input template and provided parameters.

Parameters:

Name Type Description Default
simpson_path str

Path to the Simpson executable.

required
basename str

Basename of the simulation file. Files will be generated based on this basename: - input - basename.in - output - basename.fid Default is './new_simulation'.

'./new_simulation'
template str

Path to the input template file used to generate the real input file from provided parameters. If None, the filename basename.template will be used. Default is None.

None
beff float

Dipolar coupling constant in Hz. Should have the opposite sign to the product of the gyromagnetic ratios of both nuclei. Default is None.

None
params list of str or dict

Simulation parameters. Can be either: - A list of strings in 'key=value' format, e.g., ['spin_rate=17000.0', 'l0=1'] - A dictionary of key-value pairs, e.g., {'spin_rate': '17000.0', 'l0': '1'} Default is None.

[]
verbose bool

If True, print simulation progress to stdout. Default is True.

True

Returns:

Name Type Description
elapsed_time float

Elapsed time for the simulation in seconds.

Examples:

>>> run_simulation(simpson_path, basename='sim', template='input_template.txt', beff=-600)
>>> run_simulation(simpson_path, basename='sim', template='input_template.txt', beff=-600, 
...                params=['spin_rate=17000.0', 'l0=1'])

run_optimization

run_optimization(simpson_path, exp_type, basename='./new_optimization', template=None, reference='./reference.txt', params=None, param_name='b', residual_function=compute_rmsd, method='bounded', bounds=(-1500, 0), options={'xatol': 1}, verbose=True)

Optimize a parameter using SIMPSON simulations. Runs by iteratively running simulations and comparing the results with a reference experimental data.

Parameters:

Name Type Description Default
simpson_path str

Path to the Simpson executable.

required
exp_type str

Type of NMR experiment. Supported values (either in full capitalized or small forms):
- 'CTDRENAR', 'CT-DRENAR' for CTDrenar experiments
- 'REDOR', 'REAPDOR' for REDOR/REAPDOR experiments
- 'REDOR3' for compensated REDOR experiments
- 'DQ', 'DOUBLEQUANTUM', 'DOUBLE-QUANTUM' for double quantum spectroscopy

required
basename str

Basename of the simulation file. Files will be generated based on this basename:
- input - basename.in
- output - basename.fid
- log (as number-only csv) - basename.log
- log (more readable with rich information) - basename.txt
Default is './new_optimization'.

'./new_optimization'
template str

Path to the input template file used to generate the real input file from provided parameters. If None, the filename basename.template will be used. Default is None.

None
reference str

Path to the reference experimental data file. Default is './reference.txt'.

'./reference.txt'
params list[str] or dict

Additional simulation parameters. Can be either:
- A list of strings in 'key=value' format
- A dictionary of key-value pairs
Default is None.

None
param_name str

Name of the parameter to be optimized. Default is 'b'.

'b'
residual_function Callable

The function used to calculate the residual difference between simulation and experiment. Default is .functions.compute_rmsd.

compute_rmsd
method str

Optimization method used by scipy.optimize. Currently only the method 'bounded' is implemented. See scipy document. Default is "bounded".

'bounded'
bounds Sequence

Optimization bounds. Must have two finite items. See scipy document. Default is (-1500, 0).

(-1500, 0)
options

A dictionary of additional solver options. See scipy document. Default is {'xatol': 1}.

{'xatol': 1}
verbose bool

If True, print optimization progress to stdout. Default is True.

True

Returns:

Type Description
tuple[float, float, float]

A tuple containing:
- b_opt : float
Optimized dipolar coupling constant value in Hz.
- residual : float
Residual (RMSD) at the optimized b_eff value.
- elapsed_time : float
Total elapsed time for optimization in seconds.

Examples:

>>> b_opt, residual, time = run_optimization(
...     simpson_path,
...     exp_type='CT-DRENAR',
...     basename='dataset_name_opt',
...     reference='dataset_name_int.txt', 
... )
>>> b_opt, residual, time = run_optimization(
...     simpson_path,
...     exp_type='CT-DRENAR',
...     basename='dataset_name_opt',
...     template='input_template.txt',
...     reference='dataset_name_int.txt', 
...     bounds=(-3000, 0), 
... )