API Reference

The API reference is generated automatically from the package source.

Core

Provide spectrum simulation and spin-system optimization workflows.

The module exposes simulate() for generating spectra with the supported simulation routines and optimize() for fitting spin-system parameters.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

spinanalysis.core.optimize(Sys, Exp, SimOpt, FitOpt, Var)[source]

Optimize spin-system parameters using the selected routine.

Parameters:
  • Sys (Spinsystem) – Spin-system parameters from spinanalysis.epr.

  • Exp (Experimental) – Experimental parameters from spinanalysis.epr.

  • SimOpt (SimulationOptions) – Simulation options from spinanalysis.epr.

  • FitOpt (FittingOptions) – Fitting options from spinanalysis.epr.

  • Var (Variation) – Variation parameters from spinanalysis.epr.

Notes

SimOpt.mode is set to "fitting" before dispatch.

Raises:

ValueError – If FitOpt.routine is not supported.

Returns:

The best spin-system parameters found during optimization.

Return type:

Spinsystem

spinanalysis.core.simulate(Sys, Exp, SimOpt)[source]

Simulate a spectrum using the selected simulation routine.

Parameters:
  • Sys (Spinsystem) – Spin-system parameters from spinanalysis.epr.

  • Exp (Experimental) – Experimental parameters from spinanalysis.epr. The simulated spectrum is stored in Exp.spec_sim.

  • SimOpt (SimulationOptions) – Simulation options from spinanalysis.epr.

Notes

SimOpt.mode is set to "simulation" before dispatch. For the teacups routine with eigval_mode False the mode is overridden to "fitting" because teacups internally switches between the two. Exp.spec_sim is always set to the returned (normalized) spectrum.

Raises:

ValueError – If SimOpt.routine is not supported.

Returns:

The normalized simulated spectrum.

Return type:

ndarray

EPR

class spinanalysis.epr.Spinsystem(degree=False, **data)[source]

A class containing all parameters for various radical pair simulations.

g1_iso

Isotropic g value of electron 1.

Type:

float

g2_iso

Isotropic g value of electron 2.

Type:

float

n1

Number of chemically equivalent atoms.

Type:

int

I1

Corresponding nuclear spin.

Type:

float

n2

Number of chemically equivalent atoms.

Type:

int

I2

Corresponding nuclear spin.

Type:

float

n3

Number of chemically equivalent atoms.

Type:

int

I3

Corresponding nuclear spin.

Type:

float

n4

Number of chemically equivalent atoms.

Type:

int

I4

Corresponding nuclear spin.

Type:

float

n5

Number of chemically equivalent atoms.

Type:

int

I5

Corresponding nuclear spin.

Type:

float

donor_list

Defines which atom groups are donor groups.

Type:

np.ndarray

acceptor_list

Defines which atom groups are acceptor groups.

Type:

np.ndarray

frame_group_i

Define a frame_group which will be used in optimization mode. Each frame group contains the names of the angle lists which always will have same values during optimization. i is a variable and can be whatever you want. You can define as many frame groups as you want. An example frame group would be: frame_group_1 = ['A1', 'A2', 'D']. This list means that A2_frame and D_frame will always have the same values as A1_frame, no matter which values were given to them.

Type:

list

spin_system

Define the spin system by one out of: “rp” (radical pair), “doub” (doublet), “trip” (triplet), “tdp” (triplet-doublet pair).

Type:

str

precursor

State of the precursor. One out of: “zf”, “eigen”, “singlet”, “triplet-zf”, “triplet-eigen”, “coupled”, “basis”.

Type:

str

dynamics

Matrix with rate constants of relaxation process in 1/s. For further information see the documentation.

Type:

np.ndarray

distribution_order

Number of Gaussians used for Multi-Gauss-Fitting.

Type:

int

distribution

Distance distribution of the radical pair.

Type:

np.ndarray

load(profile_name)[source]

Load Spinsystem values from a config file (profile_name.ini).

save(profile_name)[source]

Save the current spinsystem values as a config file (profile_name.ini).

_get_g_iso()[source]

Determine both g_iso values. Needed in simulation.

Examples

Initialize a new object of class Spinsystem:

>>> Sys = Spinsystem()
>>> Sys.g1
np.array([2.002, 2.002, 2.002])
>>> Sys.g1_iso
2.002

Change values:

>>> Sys.g1 = np.array([2.0024, 2.00381, 2.0027])
>>> Sys.get_g_iso()
>>> Sys.g1
np.array([2.0024 , 2.00381, 2.0027 ])
>>> Sys.g1_iso
2.00297

Create a new spinsystem profile from an empty template and load it:

>>> Sys_profile = profiles.new_spinsystem_profile()
>>> Sys_profile['g_1'] = [2.0034, 2.00156, 2.00228]
>>> profiles.add_profile(Sys.profile, 'spinsystem', 'Sys_prof_1')
>>> Sys_2 = Spinsystem()
>>> Sys_2.load_profile('Sys_prof_1')
>>> Sys_2.g1
np.array([2.0034 , 2.00156, 2.00228])

You can also save your current spinsystem as a new profile:

>>> Sys_3 = Spinsystem()
>>> Sys_3.g1 = np.array([1, 2, 3])
>>> Sys_3.save('Sys_prof_2')
>>> Sys_4 = Spinsystem()
>>> Sys_4.load('Sys_prof_2')
>>> Sys_4.g1
np.array([1., 2., 3.])
load(profile_name, degree=False)[source]

Load a spinsystem from a profile.

Load the settings from ~/.config/spinanalysis/profiles/spinsystem/ [profile_name].ini into the Spinsystem object. Overwrites previous settings.

Parameters:
  • profile_name (str) – Name of the Spinsystem profile which will be loaded.

  • degree (bool) – If True, the angle values in the profile are given in degree not radian. Thus, they will be converted to radian. If False, the angles are given in radian and will therefore not be converted, default is False.

Return type:

None

model_config = {'arbitrary_types_allowed': True, 'extra': 'allow', 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

save(profile_name='', degree=False)[source]

Save the spinsystem as a profile.

Save the spinsystem object as a spinsystem profile using profile_management.add_profile(). Load the spinsystem using Spinsystem.load_profile(<profile_name>).

Parameters:

profile_name (str) – Name of the profile. If no profile name is given, a default one will be generated by get_profile_name(), default is ''.

Return type:

None

classmethod validate_nuclear_counts(value)[source]

Require non-negative integer counts for equivalent nuclei.

Return type:

int

classmethod validate_nuclear_spins(value)[source]

Require non-negative nuclear spins in half-integer steps.

Return type:

float

class spinanalysis.epr.Experimental(magnetic_field=None, real_int=None, imag_int=None, cmplx_int=None, time_axis=None, rescale=True, **data)[source]

A class containing all experimental parameters and data.

B_z

External magnetic field points in mT used for simulation. Conversions allowed.

Type:

np.ndarray

freq_mw

Frequency of induced microwave radiation in Gigahertz.

Type:

float

magnetic_field

Same as B_z, but will never be changed.

Type:

np.ndarray

int

Real and imaginary part of the measured intensities. 1d or 2d.

Type:

np.ndarray

time_axis

Contains all experimental time points.

Type:

np.ndarray, optional

spec_sim

Calculated spectrum. At initialisation empty.

Type:

np.ndarray

get_linear_time_axis()[source]

Get a linear time axis using the given boundaries from self.t_scale with self.t_points points.

get_linear_time_axis(t_min=None, t_max=None, t_points=None)[source]

Get a linear time axis for transient simulations.

Get a linear time axis using the given boundaries from self.t_scale with self.t_points points.

Parameters:
  • t_min (float | None) – Left boundary of the time axis. If None is given, the current value of self.t_scale[0] will be used. Else, the value of self.t_scale[0] will be replaced.

  • t_max (float | None) – Right boundary of the time axis. If None is given, the current value of self.t_scale[1] will be used. Else, the value of self.t_scale[1] will be replaced.

  • t_points (int | None) – Number of time points. If None is given, the current value of self.t_points will be used. Else, the value of self.t_points will be replaced.

Return type:

None

model_config = {'arbitrary_types_allowed': True, 'extra': 'allow', 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class spinanalysis.epr.Variation(**data)[source]

A class containing variation ranges for all possible parameters.

needed_digits

Number of needed digits for chromosomes.

Type:

int

number_of_genes

Number of varied parameters. Used for fp representation.

Type:

int

variation_array

Array with all variation ranges greater 0.

Type:

np.ndarray

boundaries

Sequence of tuples containing upper and lower bounds for all varied parameters. Used for scipy.optimize.

Type:

list

freq_mw

Frequency of induced microwave radiation in Hertz.

Type:

float

bohr_magneton

Bohr magneton in Hertz/Tesla.

Type:

float

load(profile_name: str)[source]

Load Spinsystem values from a config file (profile_name.ini).

save(profile_name: str)[source]

Save the current variation values as a config file (profile_name.ini).

get_digits_for_one_par(Par, digits_per_True, one_par=True)

Get the number of needed digits for one varied parameter.

get_needed_digits()[source]

Get the total number of needed digits in binary mode.

get_number_of_genes()[source]

Get the total number of genes. Is equal to the number of varied parameters.

get_variation_array()[source]

Create an array with all used variation ranges. Only used in floating point representation.

update_digits()[source]

Determine number of needed digits. Just calls get_needed_digits()

get_boundaries(Sys)[source]

Get a sequence of tuples containing the boundaries for the varied parameters.

Examples

Initialize a new object of class <Variation>:

>>> Var = Variation()
>>> Var.g1
np.array([0., 0., 0.])

Change values:

>>> Var.g1 = np.array([0.003, 0.004, 0.003])
>>> Var.g1
np.array([0.003, 0.004, 0.003])

Create a new variation profile from an empty template and load it:

>>> Var_profile = profiles.new_variation_profile()
>>> Var_profile['g_1'] = [0.001, 0.007, 0.003] #  use list not array!
>>> profiles.add_profile(Var.profile, 'variation', 'Var_prof_1')
>>> Var_2 = Variation()
>>> Var_2.load_profile('Var_prof_1')
>>> Var_2.g1
np.array([0.001, 0.007, 0.003])

You can also save your current variation object as a new profile:

>>> Var_3 = Variation()
>>> Var_3.g1 = np.array([1, 2, 3]) #  either array or list
>>> Var_3.save('Var_prof_2')
>>> Var_4 = Variation()
>>> Var_4.load('Var_prof_2')
>>> Var_4.g1
np.array([1., 2., 3.])
get_boundaries(Sys)[source]

Create a sequence of pairs with all bounds for the varied parameters.

Used for the scipy optimization routines.

Parameters:

Sys (object) – Spinsystem object.

Return type:

None

get_needed_digits()[source]

Get sum of needed digits for all varied parameters.

Return type:

None

get_number_of_genes()[source]

Determine number of parameters which get varied.

Return type:

None

get_variation_array()[source]

Put all variation ranges in one 1-D array.

Return type:

None

load(profile_name, degree=False)[source]

Load a variation object from a profile.

Load the settings from ~/.config/spinanalysis/profiles/variation/ [profile_name].ini into the Variation object. Overwrites previous settings.

Parameters:
  • profile_name (str) – Name of the Variation profile which will be loaded.

  • degree (bool) – If True, the angle values in the profile are given in degree not radian. Thus, they will be converted to radian. If False, the angles are given in radian and will therefore not be converted. The default is ‘False’.

Return type:

None

model_config = {'arbitrary_types_allowed': True, 'extra': 'allow', 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

save(profile_name='')[source]

Save a variation object as a profile.

Save the variation object as a variation profile using profile_management.add_profile(). Load the variation object using Variation.load_profile(<profile_name>).

Parameters:

profile_name (str) – Name of the profile. If no profile name is given, a default one will be generated by get_profile_name().

Return type:

None

update_digits()[source]

Update number of needed_digits.

Return type:

None

class spinanalysis.epr.SimulationOptions(**data)[source]

A class containing all simulation options.

routine

Name of the simulation routine which will be used by spinanalysis() and spinanalysis_optimize().

Type:

str

knots

Number of knots used for spherical grid.

Type:

int

grid_points

Deprecated alias for knots. It remains supported for compatibility but will be removed in a future release.

Type:

int

space

Name of the mathematical space used for some calculations.

Type:

str

pop_evolution

If set to True, the population evolution in calculated using teacups.

Type:

bool

eigval_mode

If set to True, only the eigenvalues of the system are calculated using teacups.

Type:

bool

force_cpu

If True, the simulation will be executed on the CPU, even if GPU is available. Default is False.

Type:

bool

regularization_mode

Choose the regularization matrix used for the Tikhonov-Regularization. 0 : Unitary matrix 1 : First order derivative matrix 2 : Second order derivative matrix (default)

Type:

int

load(profile_name: str)[source]

Load SimulationOptions values from a config file (profile_name.ini).

save(profile_name: str)[source]

Save the current simulation options as a config file (profile_name.ini).

Examples

Initialize an object of class <SimulationOptions>:

>>> SimOpt = SimulationOptions()
>>> SimOpt.knots
20

Change values:

>>> SimOpt.knots = 1000
>>> SimOpt.knots
1000

Save your current values as a new profile:

>>> SimOpt.save('SimOpt_prof_1')
>>> SimOpt_2 = SimulationOptions()
>>> SimOpt_2.knots
20
>>> SimOpt.load('SimOpt_prof_1')
>>> SimOpt_2.knots
1000

You can also create a simulation options profile from an empty template:

>>> simopt_prof = profiles.new_simulation_profile()
>>> simopt_prof['static_radpair']['knots'] = 1100
>>> profiles.add_profile(simopt_prof, 'simulation', 'SimOpt_prof_2')
>>> SimOpt_3 = SimulationOptions()
>>> SimOpt_3.knots
20
>>> SimOpt.load('SimOpt_prof_2')
>>> SimOpt_3.knots
1100
load(profile_name)[source]

Load simulation options from a profile.

Load the settings from ~/.config/spinanalysis/profiles/simulation/ [profile_name].ini into the SimulationOptions object. Overwrites previous settings.

Parameters:

profile_name (str) – Name of the simulation profile which will be loaded.

Return type:

None

model_config = {'arbitrary_types_allowed': True, 'extra': 'allow', 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

save(profile_name='')[source]

Save the simulation optionas as a profile.

Save the simulation options as a simulation options profile using profile_management.add_profile(). Load the simulation options using SimulationOptions.load_profile(<profile_name>).

Parameters:

profile_name (str) – Name of the profile. If no profile name is given, a default one will be generated by get_profile_name().

Return type:

None

class spinanalysis.epr.FittingOptions(**data)[source]

A class containing all optimization options.

routine

Name of the optimization routine which will be used by spinanalysis_optimize().

Type:

str

method

Name of the optimization method used in the scipy.optimize routines.

Type:

str

x0

Array containing the initial guess for the optimization routine for the parameters which will be varied.

Type:

np.ndarray

cpu_cores

Number of cores used for the optimization.

Type:

int

gui

Set to True if in GUI mode (PySpin).

Type:

bool

window

Plot canvas. Only needed in GUI mode.

Type:

object

load(profile_name: str)[source]

Load FittingOptions values from a config file (profile_name.ini).

save(profile_name: str)[source]

Save the current fitting options as a config file (profile_name.ini).

Examples

Initialize an object of class <FittingOptions>:

>>> FitOpt = FittingOptions()
>>> FitOpt.GAVaPS
True

Change values:

>>> FitOpt.GAVaPS = False
>>> FitOpt.GAVaPS
False

Save your current values as a new profile:

>>> FitOpt.save_simulationoptions('FitOpt_prof_1')
>>> FitOpt_2 = FittingOptions()
>>> FitOpt_2.GAVaPS
True
>>> FitOpt.load_profile('FitOpt_prof_1')
>>> FitOpt_2.GAVaPS
False

You can also create a fitting options profile from an empty template:

>>> fitopt_prof = profiles.new_optimization_profile()
>>> fitopt_prof['genetic']['GAVaPS'] = False
>>> profiles.add_profile(fitopt_prof, 'simulation', 'FitOpt_prof_2')
>>> FitOpt_3 = FittingOptions()
>>> FitOpt_3.GAVaPS
True
>>> FitOpt.load_profile('FitOpt_prof_2')
>>> FitOpt_3.GAVaPS
False
load(profile_name)[source]

Load fitting options from a profile.

Load the settings from ~/.config/spinanalysis/profiles/optimization/ [profile_name].ini into the FittingOptions object. Overwrites previous settings. Only loads the section given in [‘main’][‘routine’].

Parameters:

profile_name (str) – Name of the optimization profile which will be loaded.

Return type:

None

model_config = {'arbitrary_types_allowed': True, 'extra': 'allow', 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

save(profile_name='')[source]

Save the fitting options as a profile.

Save the fitting options as a fitting options profile using profile_management.add_profile(). Load the fitting options using FittingOptions.load_profile(<profile_name>).

Parameters:

profile_name (str) – Name of the profile. If no profile name is given, a default one will be generated by get_profile_name().

Return type:

None

class spinanalysis.epr.ExperimentalInput(**data)[source]

Validated input data for Experimental.

classmethod convert_arrays(value)[source]

Convert array-like input to an independent NumPy array.

Return type:

ndarray | None

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod require_complex_intensity(value)[source]

Require complex-valued input for cmplx_int.

Return type:

ndarray | None

classmethod require_real_arrays(value)[source]

Reject complex-valued real intensity and time-axis inputs.

Return type:

ndarray | None

classmethod require_real_field(value)[source]

Reject complex-valued magnetic-field input.

Return type:

ndarray | None

validate_intensity_sources()[source]

Ensure complex and component intensity inputs are not combined.

Return type:

ExperimentalInput

Loading

Read EPR data from BRUKER BES3T, ESP transient, MATLAB, and text formats.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

spinanalysis.loading.convert_parameter_type(value)[source]

Convert the type of a given string to bool, int or float if possible.

Parameters:

value (str) – Parameter string which should be converted.

Returns:

Parameter as bool, int or float. If none is possible, the stripped string will be returned.

Return type:

bool | int | float | str

spinanalysis.loading.get_DSC_parameters(path_to_folder)[source]

Extract all parameters from the DSC file.

The DSC file is found by searching for *.DSC in the data folder rather than assuming it shares the folder’s basename.

Parameters:

path_to_folder (str) – Full path to the folder containing the .DSC and .DTA files.

Returns:

Dictionary with all parameters. Keys are the same as in the .DSC file. An additional key 'path_to_folder' holds the folder path

Return type:

dict

spinanalysis.loading.get_byte_mode(DSC_dict, data_key='IRFMT')[source]

Get the used byte mode of the BRUKER BES3T data.

For more information about BES3T go to BRUKER website or easyspin on GitHub.

Parameters:
  • DSC_dict (dict) – Dictionary with all parameters. Key is the same as in .DSC.

  • data_key (str) – Key for the data array. Either ‘IRFMT’ or ‘IIFMT’.

Raises:

ValueError – If the BSEQ value is not ‘BIG’ or ‘LIT’, if the format value is not one of C, S, I, F, D, or if the format is ‘A’ (ASCII).

Returns:

Byte mode string for numpy.fromfile(dtype=...).

Return type:

str

spinanalysis.loading.get_data_dimension(DSC_dict)[source]

Determine the dimension of the measured spectrum (1d/2d/3d).

The result is stored in-place in DSC_dict under the key 'dimensions'.

Parameters:

DSC_dict (dict) – Dictionary with all parameters. Modified in place.

Return type:

None

spinanalysis.loading.get_full_path(directory_name, start_directory=None)[source]

Get the full path of a given directory. Search starts at home directory.

Parameters:
  • directory_name (str) – Name of the directory whose path is to be found.

  • start_directory (str | None) – Directory at which the search starts. If given, the performance increases very sharply. Recommended.

Raises:

FileNotFoundError – If the directory cannot be found.

Returns:

The full path of the directory.

Return type:

str

spinanalysis.loading.get_transient_data(fpath)[source]

Get the measured intensities of the whole spectrum from a transient EPR experiment measured by ESP380E.

Parameters:

fpath (str) – Full path to the folder with the experimental data.

Return type:

tuple[tuple[ndarray, ndarray], ndarray]

Returns:

  • axis (tuple[np.ndarray, np.ndarray]) – Tuple with all axis vectors as two numpy arrays (magnetic_field, time).

  • data (np.ndarray) – Measured real intensities as a np.complex128 numpy array. All imaginary parts are zero.

spinanalysis.loading.get_transient_info(fpath)[source]

Get all information about the time axis and magnetic field vector from the .info file.

The .info file is found by searching for *.info in the data folder.

Parameters:

fpath (str) – Full path to the folder with the experimental data.

Raises:

KeyError – If the section ‘MAGNETIC FIELD’ or ‘TRANSIENT’ could not be found in the .info file.

Returns:

Contains (time_length, time_points, mag_field_start, mag_field_stop, mag_field_step).

Return type:

tuple[float | int | None, ...]

spinanalysis.loading.load_axis_vector(axis, DSC_dict)[source]

Load the points of a given axis (x, y, z).

Parameters:
  • axis (str) – Name of the axis. Needs to start with x, X, y, Y or z, Z.

  • DSC_dict (dict) – Dictionary with all parameters. Key is the same as in .DSC.

Raises:

ValueError – If the given axis doesn’t start with an allowed character.

Returns:

Array with all axis points. Empty array if no axis data is available.

Return type:

ndarray

spinanalysis.loading.load_data_vector(DSC_dict)[source]

Load the binary intensity vector(s) from a BRUKER BES3T file.

Parameters:

DSC_dict (dict) – Dictionary with all parameters. Key is the same as in .DSC.

Raises:
  • ValueError – If IKKF is not ‘CPLX’ or ‘REAL’, or if the dimension is not 1 or 2.

  • KeyError – If an axis is given but the corresponding number of points is missing.

Returns:

Real and imaginary part of the measured intensities as a np.complex128 array. If no imaginary part is measured, zeros will be inserted.

Return type:

ndarray

spinanalysis.loading.load_epr_ESP_transient(folder, start_directory=None)[source]

Load data from a transient EPR experiment measured with ESP380E.

Parameters:
  • folder (str) – Name of the folder with all data files.

  • start_directory (str | None) –

    Give the path starting from your home folder which the search for the data folder should start at. E. g.: data is at /home/cooluser/nice/data/this_folder and you know, that all your data is in /home/cooluser/nice/*, then you can give this start_directory with start_directory=’nice’. So the function call would be:

    load_epr_ESP_transient(this_folder, 'nice')
    

    Recommended: without this parameter, the search for the right folder will be much longer.

Return type:

tuple[tuple[ndarray, ndarray], ndarray]

Returns:

  • axis (tuple[np.ndarray, np.ndarray]) – Tuple with all axis vectors as two numpy arrays (magnetic_field, time).

  • data (np.ndarray) – All intensity values as one complex np.complex128 numpy array. Imaginary part is always 0.

spinanalysis.loading.load_epr_bruker_bes3t(folder, start_directory=None)[source]

Load the whole dataset from a BRUKER BES3T data folder.

Time axis will be rescaled for OOP-ESEEM experiments if 'FTAcqModeSlct' is 'Tables'.

Parameters:
  • folder (str) – Name of the data folder with the corresponding data files.

  • start_directory (str | None) –

    Give the path starting from your home folder which the search for the data folder should start at. E. g.: data is at /home/cooluser/nice/data/this_folder and you know, that all your data is in /home/cooluser/nice/*, then you can give this start_directory with start_directory=’nice’. So the function call would be:

    load_epr_bruker_bes3t(this_folder, 'nice')
    

    Recommended: without this parameter, the search for the right folder will be much longer.

Return type:

tuple[tuple[ndarray, ndarray, ndarray], ndarray]

Returns:

  • axis (tuple[np.ndarray, np.ndarray, np.ndarray]) – Tuple of all axis vectors as three numpy arrays (x, y, z).

  • data (np.ndarray) – All intensity values as one complex np.complex128 numpy array.

spinanalysis.loading.load_matlab(folder, start_directory=None, field='field', signal='signal')[source]

Load EPR data from a MATLAB data file (.mat).

The folder argument is the name of the directory containing the .mat file. The first .mat file found in the directory is loaded.

Parameters:
  • folder (str) – Name of the data folder with the .mat file.

  • start_directory (str | None) –

    Give the path starting from your home folder which the search for the data folder should start at. E. g.: data is at /home/cooluser/nice/data/this_folder and you know, that all your data is in /home/cooluser/nice/*, then you can give this start_directory with start_directory=’cooluser/nice’. So the function call would be:

    load_matlab(this_folder, 'cooluser/nice')
    

  • field (str) – Name of the field array in the .mat file.

  • signal (str) – Name of the signal array in the .mat file.

Return type:

tuple[tuple[ndarray, ndarray], ndarray]

Returns:

  • axis (tuple[np.ndarray, np.ndarray]) – Tuple of np.ndarray containing the x and y axis.

  • data (np.ndarray) – np.ndarray with the measured intensities.

spinanalysis.loading.load_simulated_data(folder, start_directory=None)[source]

Load simulated data from spinanalysis or data saved with saving.save_simulation(). Uses numpy.loadtxt().

Parameters:
  • folder (str) – Name of the data folder with the corresponding data files (x_axis.txt, intensity.txt, optionally y_axis.txt).

  • start_directory (str | None) –

    Give the path starting from your home folder which the search for the data folder should start at. E. g.: data is at /home/cooluser/nice/data/this_folder and you know, that all your data is in /home/cooluser/nice/*, then you can give this start_directory with start_directory=’cooluser/nice’. So the function call would be:

    load_simulated_data(this_folder, 'cooluser/nice')
    

    Recommended: without this parameter, the search for the right folder will be much longer.

Return type:

tuple[ndarray, ...]

Returns:

  • x (np.ndarray) – Axis vector for the x-axis.

  • y (np.ndarray) – Axis vector for the y-axis. Only returned if the simulated data is 2d.

  • intensity (np.ndarray) – Simulated intensities as a np.complex128 numpy array. Either 1d or 2d.

spinanalysis.loading.load_txt(folder, start_directory=None)[source]

Load EPR data from a .txt file.

The folder argument is the name of the directory containing the .txt file. The first .txt file found in the directory is loaded.

Parameters:
  • folder (str) – Name of the data folder with the .txt file.

  • start_directory (str | None) –

    Give the path starting from your home folder which the search for the data folder should start at. E. g.: data is at /home/cooluser/nice/data/this_folder and you know, that all your data is in /home/cooluser/nice/*, then you can give this start_directory with start_directory=’cooluser/nice’. So the function call would be:

    load_txt(this_folder, 'cooluser/nice')
    

Return type:

tuple[tuple[ndarray, ndarray], ndarray]

Returns:

  • axis (tuple[np.ndarray, np.ndarray]) – Tuple of np.ndarray containing the x and y axis.

  • data (np.ndarray) – np.ndarray with the measured intensities.

spinanalysis.loading.read_single_transient_file(fpath, basename, filenumber, digits, time=False)[source]

Get the measured intensities of a single field point from a transient EPR experiment measured with ESP380E.

Parameters:
  • fpath (str) – Full path to the folder with the experimental data.

  • basename (str) – Shared basename of the numbered data files.

  • filenumber (int) – Number of the dataset for the magnetic field point, e. g. 3.

  • digits (int) – Number of digits in the file-number suffix.

  • time (bool) – If True, the time axis will also be returned.

Return type:

tuple[float, ndarray] | tuple[tuple[float, ndarray], ndarray]

Returns:

  • field (float) – Magnetic field point. Returned alone with data_vector when time is False.

  • data_vector (np.ndarray) – Measured intensities.

  • time_axis (tuple[float, np.ndarray]) – Tuple of (field, time_axis) returned with data_vector when time is True.

Processing

Transform EPR spectra through normalization, background correction, and reconstruction.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

spinanalysis.processing.background_corr(x, y, mode='biexp')[source]

Perform a background correction of measured data.

Available correction modes are: biexp, exp, lin, poly2, poly3 and poly4. biexp and exp use exponential models for the background; lin and poly2-4 are polynomial models of first to fourth order.

Warning

poly3 and poly4 can lead to overfitting!

Parameters:
  • x (ndarray) – x axis of the dataset.

  • y (ndarray) – y data which will be background corrected.

  • mode (str) – Select the type of the background. The default is 'biexp'.

Returns:

Background corrected y data.

Return type:

ndarray

spinanalysis.processing.biexp_fun(x, *coeff)[source]

Generalized biexponential function for background correction.

Parameters:
  • x (ndarray) – x values used to calculate corresponding y values.

  • *coeff (float) – Variables for the biexponential function which will be fitted.

Returns:

Calculated y values.

Return type:

ndarray

spinanalysis.processing.exp_fun(x, *coeff)[source]

Generalized monoexponential function for background correction.

Parameters:
  • x (ndarray) – x values used to calculate corresponding y values.

  • *coeff (float) – Variables for the monoexponential function which will be fitted.

Returns:

Calculated y values.

Return type:

ndarray

spinanalysis.processing.lin_fun(x, *coeff)[source]

Generalized linear function for background correction.

Parameters:
  • x (ndarray) – x values used to calculate corresponding y values.

  • *coeff (float) – Variables for the linear function which will be fitted.

Returns:

Calculated y values.

Return type:

ndarray

spinanalysis.processing.normalization(x, mode=None, dx=None)[source]

Normalize the given data.

\[x_{\mathrm{norm}} = \frac{x_i - \min(x)}{\max(x)-\min(x)}\]
Parameters:
  • x (ndarray) – Unnormalized data.

  • mode (str | None) – If 'area', the total AUC will be 1; if 'value', the maximum absolute value will be 1; otherwise the formula above is used. The default is None.

  • dx (float | None) – Distance between two points on the x axis. Only used for Simpson integration. The default is None.

Returns:

Normalized data.

Return type:

ndarray

spinanalysis.processing.poly2_fun(x, *coeff)[source]

Generalized polynomial function of degree 2 for background correction.

Parameters:
  • x (ndarray) – x values used to calculate corresponding y values.

  • *coeff (float) – Variables for the polynomial function of degree 2 which will be fitted.

Returns:

Calculated y values.

Return type:

ndarray

spinanalysis.processing.poly3_fun(x, *coeff)[source]

Generalized polynomial function of degree 3 for background correction.

Parameters:
  • x (ndarray) – x values used to calculate corresponding y values.

  • *coeff (float) – Variables for the polynomial function of degree 3 which will be fitted.

Returns:

Calculated y values.

Return type:

ndarray

spinanalysis.processing.poly4_fun(x, *coeff)[source]

Generalized polynomial function of degree 4 for background correction.

Parameters:
  • x (ndarray) – x values used to calculate corresponding y values.

  • *coeff (float) – Variables for the polynomial function of degree 4 which will be fitted.

Returns:

Calculated y values.

Return type:

ndarray

spinanalysis.processing.reconstruct(x, y)[source]

Reconstruct a time signal using the Yule-Walker algorithm.

Parameters:
  • x (ndarray) – x axis.

  • y (ndarray) – Intensities.

Return type:

tuple[ndarray, ndarray]

Returns:

  • x_new (np.ndarray) – Reconstructed x axis.

  • y_new (np.ndarray) – Reconstructed intensities.

spinanalysis.processing.reduce_offset(x)[source]

Eliminate the offset of the data by subtracting the mean of the last quarter.

Parameters:

x (ndarray) – Given data, e.g. measured intensities.

Returns:

Shifted data without offset.

Return type:

ndarray

Plotting

Render EPR spectra as 2D, 3D, heatmap, and shifted-line plots.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

spinanalysis.plotting.heatmap(x, y, Z, mpl_stylesheet='default_stylesheet', ax=None, **kwargs)[source]

Plot 2D data as a heatmap using matplotlib.pylab.pcolormesh().

The plot can be configured via plot profiles.

Parameters:
  • x (ndarray) – Array with values for the x axis.

  • y (ndarray) – Array with values for the y axis.

  • Z (ndarray) – 2D-Array with intensities.

  • mpl_stylesheet (str) – Name of the matplotlib style sheet (see: matplotlib documentation). If no style sheet is given, the styles defined in the plotting profile will be used.

  • ax (Axes | None) – Axes object, used for the PySpin GUI.

  • **kwargs (Any) – Keyword arguments passed to the matplotlib plot function. Overrides the arguments given in the stylesheet.

Returns:

fig – Figure object of matplotlib.

Return type:

Figure

spinanalysis.plotting.plot_2D(x, y, mpl_stylesheet='default_stylesheet', labels='no_label', ax=None, **kwargs)[source]

Plot the given y value(s) against the given x array.

Using matplotlib.pylab.plot(). The plot can be configured via plot profiles.

Parameters:
  • x (ndarray) – Array with values for the x axis.

  • y (ndarray) – 1D-Array or 2D-Array with values for y axis.

  • mpl_stylesheet (str) – Name of the matplotlib style sheet (see: matplotlib documentation). If no style sheet is given, the styles defined in the plotting profile will be used.

  • labels (list[str] | str) – List of labels for the legend. If only one label is given, all labels will be the same.

  • ax (Axes | None) – Axes object, used for the PySpin GUI.

  • **kwargs (Any) – Keyword arguments passed to the matplotlib plot function. Overrides the arguments given in the stylesheet.

Returns:

fig – Figure object of matplotlib.

Return type:

Figure

spinanalysis.plotting.plot_3D(x, y, Z, mpl_stylesheet='default_stylesheet', labels='no_label', ax=None, **kwargs)[source]

Plot 2D data in 3D using matplotlib.pylab.plot_surface().

The plot can be configured via plot profiles.

Parameters:
  • x (ndarray) – Array with values for the x axis.

  • y (ndarray) – Array with values for the y axis.

  • Z (ndarray) – 2D-Array with intensities.

  • mpl_stylesheet (str) – Name of the matplotlib style sheet (see: matplotlib documentation). If no style sheet is given, the styles defined in the plotting profile will be used.

  • labels (str) – At the moment no function.

  • ax (Axes | None) – Axes object, used for the PySpin GUI.

  • **kwargs (Any) – Keyword arguments passed to the matplotlib plot function. Overrides the arguments given in the stylesheet.

Returns:

fig – Figure object of matplotlib.

Return type:

Figure

spinanalysis.plotting.plot_3D_multiple_lines(x, y, Z, mpl_stylesheet='default_stylesheet', ax=None, **kwargs)[source]

Plot 2D data in 3D using matplotlib.pylab.plot().

Each y trace as a single line plot. The plot can be configured via plot profiles.

Parameters:
  • x (ndarray) – Array with values for the x axis.

  • y (ndarray) – Array with values for the y axis.

  • Z (ndarray) – 2D-Array with intensities.

  • mpl_stylesheet (str) – Name of the matplotlib style sheet (see: matplotlib documentation). If no style sheet is given, the styles defined in the plotting profile will be used.

  • ax (Axes | None) – Axes object, used for the PySpin GUI.

  • **kwargs (Any) – Keyword arguments passed to the matplotlib plot function. Overrides the arguments given in the stylesheet.

Returns:

fig – Figure object of matplotlib.

Return type:

Figure

spinanalysis.plotting.shifted_2D(x, Y, mpl_stylesheet='default_stylesheet', labels='no_label', ax=None, **kwargs)[source]

Plot multiple lines in 2D, shifted vertically.

The plot can be configured via plot profiles.

Parameters:
  • x (ndarray) – Array with values for the x axis.

  • Y (ndarray) – 2D-Array with values for y axis.

  • mpl_stylesheet (str) – Name of the matplotlib style sheet (see: matplotlib documentation). If no style sheet is given, the styles defined in the plotting profile will be used.

  • labels (list[str] | str) – List of labels for the legend. If only one label is given, all labels will be the same.

  • ax (Axes | None) – Axes object, used for the PySpin GUI.

  • **kwargs (Any) – Keyword arguments passed to the matplotlib plot function. Overrides the arguments given in the stylesheet.

Returns:

fig – Figure object of matplotlib.

Return type:

Figure

Saving

Write simulation results, figures, and output files to disk.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

spinanalysis.saving.save_plot(fname, *figures, path=None, **kwargs)[source]

Save the figures plotted with matplotlib.

Parameters:
  • fname (str) – Filename for the figure(s). If multiple figures are given, ‘_[number]’ will be appended to the filename.

  • *figures (object) – Matplotlib figure object(s).

  • path (str | Path | None) – Directory where the figures will be stored, default is ~/spinanalysis/plots/.

  • **kwargs (Any) – Other keyword arguments. Will be passed to plt.savefig(). See matplotlib documentation for further information.

Return type:

None

spinanalysis.saving.save_simulation(name, *data, path=None)[source]

Save the simulated data at [path]/[name]/[files].

Uses numpy.savetxt().

Parameters:
  • name (str) – Folder name for the dataset.

  • *data (ndarray) – Arrays with the simulated data. If 2 arrays: x_axis, int; if 3 arrays: x_axis, y_axis, int.

  • path (str | Path | None) – Directory where the data will be stored, default is ~/spinanalysis/simulations/.

Raises:

ValueError – If the number of data arrays is not 2 or 3.

Return type:

None

spinanalysis.saving.write_out_file(Sys, Exp, SimOpt, *FitOpt, current_best=False, path=None)[source]

Write an output file with all data from Sys, Exp, SimOpt.

If running in optimization mode, FitOpt data is also written.

Parameters:
  • Sys (Any) – Spinsystem object.

  • Exp (Any) – Experimental object.

  • SimOpt (Any) – SimulationOptions object.

  • *FitOpt (Any) – FittingOptions object (optional, only in optimization mode).

  • current_best (bool) – True if Sys and Exp are the current best while running in optimization mode. False if they are the final result or in normal simulation mode, default is False.

  • path (str | Path | None) – Directory where the output file will be stored. If None, default is to create a new folder spinanalysis_YYYY-MM-DD_N in the current working directory, where N is the lowest available positive integer.

Returns:

Path to the written output file.

Return type:

Path

Profiles

Manage configuration profiles for EPR simulations, plots, and optimization.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

spinanalysis.profiles.add_profile(profile, pkind, pname='')[source]

Add a new profile for spinanalysis.

Parameters:
  • profile (dict) – Dictionary with all profile settings.

  • pkind (str) – Kind of the profile. Not case sensitive. Can be ‘plot’, ‘simulation’, ‘optimization’, ‘spinsystem’ or ‘variation’.

  • pname (str) – Name of the profile. If no profile name is given, a default one will be generated by _get_profile_name(), default is ''.

Raises:

ValueError – If pkind is not a valid profile kind, or if the profile fails configspec validation.

Examples

Return type:

None

Creating and adding a new profile:

>>> from spinanalysis.epr import Spinsystem
>>> from spinanalysis import profiles
>>> Sys = Spinsystem()
>>> Sys_profile = profiles.new_spinsystem_profile()
>>> Sys_profile['main']['g1'] = [2.0034, 2.00156, 2.00228]
>>> profiles.add_profile(Sys_profile, 'spinsystem', 'Sys_prof_1')
spinanalysis.profiles.export(path=None, pkind='all', pname='all')[source]

Export the chosen profile(s) as a zip archive.

Parameters:
  • path (str | None) – Directory where the zip file will be stored. If None, the zip file will be stored in the current working directory, default is None.

  • pkind (str | list[str]) – Define which kind(s) of profiles should be exported. Options are ‘plot’, ‘spinsystem’, ‘optimization’, ‘simulation’, ‘variation’ and ‘all’, default is 'all'.

  • pname (str) – Give the basename of the profile, default is 'all'.

Return type:

None

spinanalysis.profiles.import_profiles(zipfile, override=False)[source]

Import profiles from a zip archive.

The archive must contain subdirectories matching valid profile kinds (e.g. spinsystem/, simulation/). Files are extracted directly into PROFILE_ROOT.

Parameters:
  • zipfile (str) – Path to the zip archive.

  • override (bool) – If True, existing profiles with the same name will be overwritten, default is False.

Raises:

ValueError – If the archive contains a top-level entry that does not correspond to a valid profile kind.

Return type:

None

spinanalysis.profiles.load_plot_profile(pname)[source]

Load a plotting profile from an mplstylesheet.

Parameters:

pname (str | None) – Name of the profile. Case sensitive. If None or a built-in matplotlib style, the default stylesheet is loaded.

Returns:

Settings for the plotting functions.

Return type:

dict

spinanalysis.profiles.load_profile(pname, pkind)[source]

Load a profile from a config file.

Parameters:
  • pname (str) – Name of the profile. Case sensitive. Either with .ini or not. E. g.: load_profile(‘test’) or load_profile(‘test.ini’).

  • pkind (str) – Kind of the profile. Not case sensitive. Can be ‘simulation’, ‘optimization’, ‘spinsystem’ or ‘variation’.

Raises:

ValueError – If pkind is not valid or the profile fails configspec validation.

Returns:

Loaded profile as a dictionary.

Return type:

dict

spinanalysis.profiles.new_optimization_profile()[source]

Get a default optimization profile.

Returns:

Dictionary with default settings for optimization routines.

Return type:

dict

spinanalysis.profiles.new_plot_profile()[source]

Get an empty plotting profile.

Returns:

Dictionary with default settings for plotting.

Return type:

dict

spinanalysis.profiles.new_simulation_profile()[source]

Get an empty simulation profile.

Returns:

Dictionary with default settings for simulation profiles.

Return type:

dict

spinanalysis.profiles.new_spinsystem_profile()[source]

Get a default spinsystem profile.

Returns:

Dictionary with default settings for a spinsystem.

Return type:

dict

spinanalysis.profiles.new_variation_profile()[source]

Get a default variation profile.

Returns:

Dictionary with default settings for variation.

Return type:

dict

Internal Modules

The following modules support internal execution and integration workflows.

Wrappers

Provide decorators and multicore helpers for simulation routines.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

spinanalysis._wrappers.function_benchmark(func, niter=100)[source]

Run func niter times and print best, worst, and average runtime.

Parameters:
  • func (Callable) – Function which will be benchmarked.

  • niter (int) – Number of function calls. The default is 100.

Returns:

Wrapper that runs the benchmark and prints timing statistics.

Return type:

Callable

spinanalysis._wrappers.multicore(simulation)[source]

Parallelise a simulation routine using multiprocessing.Pool.

The decorated function must accept (Sys, Exp, SimOpt) and is executed on SimOpt.cpu_cores processes, each handling a slice of the magnetic-field axis.

Parameters:

simulation (Callable) – Simulation function with the signature (Sys, Exp, SimOpt).

Returns:

Wrapper with signature (Sys, Exp, SimOpt) that distributes the work across CPU cores and returns the concatenated spectrum.

Return type:

Callable

spinanalysis._wrappers.timer(func)[source]

Measure the wall-clock runtime of a single function call.

Parameters:

func (Callable) – Function whose runtime will be measured.

Returns:

Wrapper that prints the runtime and returns the original result.

Return type:

Callable

Interface Handler

Bridge between spinanalysis objects and scipy.optimize routines.

© M. Sc. Florian Quintes, 2026

@contact: florian.quintes@pc.uni.freiburg.de

@author: Florian Quintes

class spinanalysis._interface_handler.BasinhoppingBounds(Var)[source]

Bases: object

Acceptance test for the scipy.optimize.basinhopping algorithm.

xmin

Lower bounds for the varied parameters.

Type:

np.ndarray

xmax

Upper bounds for the varied parameters.

Type:

np.ndarray

Var

Object of class Variation from the epr_setup module.

Type:

object

__call__(**kwargs)[source]

Check if the current guess is within the bounds.

class spinanalysis._interface_handler.BasinhoppingStatus(Sys, Var, verbose=False)[source]

Bases: object

Status callback for the scipy.optimize.basinhopping algorithm.

best

Best objective-function value found so far.

Type:

float

def_Sys

Reference spin-system object.

Type:

object

Var

Variation object containing the parameter ranges.

Type:

object

verbose

Controls whether status information is printed.

Type:

bool, optional

xmin

Lower bounds for the varied parameters.

Type:

np.ndarray

xmax

Upper bounds for the varied parameters.

Type:

np.ndarray

__call__(x, value, accepted)[source]

Print status information.

check_bounds(x)[source]

Check if the current guess is within the bounds.

Parameters:

x (GenericAlias[float64]) – Current guess.

Returns:

True if the guess is within the bounds, False if not.

Return type:

bool

save_best(x)[source]

Create a spin-system object from the best parameter vector and save it.

Parameters:

x (GenericAlias[float64]) – Current guess.

Return type:

None

class spinanalysis._interface_handler.BasinhoppingStep(Var, stepsize=0.75)[source]

Bases: object

Step generator for the scipy.optimize.basinhopping algorithm.

stepsize

Relative size of the random step with respect to the variation range.

Type:

float, optional

rng

NumPy random number generator.

Type:

object

Var

Object of class Variation from the epr_setup module.

Type:

object

bounds

Parameter boundaries as a two-dimensional array.

Type:

np.ndarray

lb

Lower bounds.

Type:

np.ndarray

ub

Upper bounds.

Type:

np.ndarray

var_range

Half the difference between lower and upper bounds.

Type:

np.ndarray

dim_var

Number of variables.

Type:

int

__call__(x)[source]

Generate the next random step.

check_guess(x)[source]

Check whether the current parameter vector is within the bounds.

Out-of-bound values are replaced by randomly generated values inside the bounds.

Parameters:

x (GenericAlias[float64]) – Current guess.

Returns:

x – Current guess.

Return type:

GenericAlias[float64]

spinanalysis._interface_handler.basinhopping(Sys, Exp, SimOpt, FitOpt, Var)[source]

Run scipy.optimize.basinhopping for global optimization.

Parameters:
  • Sys (Any) – Reference spin-system object.

  • Exp (Any) – Experimental data object.

  • SimOpt (Any) – Simulation options object.

  • Var (Any) – Variation object describing the fitted parameters.

  • FitOpt (Any) – Fitting options object.

Returns:

best_Sys – Best spin-system object found by the optimizer.

Return type:

Any

spinanalysis._interface_handler.differential_evolution(Sys, Exp, SimOpt, FitOpt, Var)[source]

Run scipy.optimize.differential_evolution for global optimization.

Parameters:
  • Sys (Any) – Reference spin-system object.

  • Exp (Any) – Experimental data object.

  • SimOpt (Any) – Simulation options object.

  • Var (Any) – Variation object describing the fitted parameters.

  • FitOpt (Any) – Fitting options object.

Returns:

best_Sys – Best spin-system object found by the optimizer.

Return type:

Any

spinanalysis._interface_handler.dualannealing(Sys, Exp, SimOpt, FitOpt, Var)[source]

Run scipy.optimize.dual_annealing for global optimization.

Parameters:
  • Sys (Any) – Reference spin-system object.

  • Exp (Any) – Experimental data object.

  • SimOpt (Any) – Simulation options object.

  • Var (Any) – Variation object describing the fitted parameters.

  • FitOpt (Any) – Fitting options object.

Returns:

best_Sys – Best spin-system object found by the optimizer.

Return type:

Any

spinanalysis._interface_handler.get_random_x0(boundaries)[source]

Generate a random initial guess within the variation boundaries.

Parameters:

boundaries (Sequence[tuple[float, float]]) – Lower and upper bounds of the fitted parameters.

Returns:

x0 – Randomly generated initial parameter vector.

Return type:

GenericAlias[float64]

spinanalysis._interface_handler.guess2Sys(x, Sys, Var, SimOpt)[source]

Create a spin-system object from the current optimizer vector.

Parameters:
  • x (GenericAlias[float64]) – Current parameter vector of the optimizer.

  • Sys (Any) – Reference spin-system object.

  • Var (Any) – Variation object.

  • SimOpt (Any) – Simulation options object.

Returns:

Sys_mod – Spin-system object corresponding to the current optimizer vector.

Return type:

Any

spinanalysis._interface_handler.least_squares(Sys, Exp, SimOpt, FitOpt, Var)[source]

Run scipy.optimize.least_squares for nonlinear optimization.

Parameters:
  • Sys (Any) – Reference spin-system object.

  • Exp (Any) – Experimental data object.

  • SimOpt (Any) – Simulation options object.

  • Var (Any) – Variation object describing the fitted parameters.

  • FitOpt (Any) – Fitting options object.

Returns:

best_Sys – Best spin-system object found by the optimizer.

Return type:

Any

spinanalysis._interface_handler.minimize(Sys, Exp, SimOpt, FitOpt, Var)[source]

Run scipy.optimize.minimize for local optimization.

Minimize provides multiple local optimization routines such as Nelder-Mead, COBYLA, Powell, CG and so on.

Parameters:
  • Sys (Any) – Reference spin-system object.

  • Exp (Any) – Experimental data object.

  • SimOpt (Any) – Simulation options object.

  • Var (Any) – Variation object describing the fitted parameters.

  • FitOpt (Any) – Fitting options object.

Return type:

Any

Returns:

  • best_Sys (object) – Best spin-system object found by the optimizer.

  • results (str, optional) – Results of the scipy optimization. Only for the GUI.

spinanalysis._interface_handler.plot_callback(xk, *_, Sys=None, Exp=None, SimOpt=None, FitOpt=None, Var=None, **_kwargs)[source]

Plot the current optimization state in the graphical user interface.

Parameters:
  • xk (GenericAlias[float64]) – Current best guess vector.

  • *_ – Unused positional arguments passed by some optimization routines to the callback function.

  • Sys (Any) – Reference spin-system object.

  • Exp (Any) – Experimental data object.

  • SimOpt (Any) – Simulation options object.

  • Var (Any) – Variation object describing the fitted parameters.

  • FitOpt (Any) – Fitting options object.

  • **_kwargs – Unused keyword arguments passed by some optimization routines to the callback function.

Raises:

ValueError – If the selected simulation routine is unknown.

Return type:

None

spinanalysis._interface_handler.shgo(Sys, Exp, SimOpt, FitOpt, Var)[source]

Run scipy.optimize.shgo for global optimization.

Parameters:
  • Sys (Any) – Reference spin-system object.

  • Exp (Any) – Experimental data object.

  • SimOpt (Any) – Simulation options object.

  • Var (Any) – Variation object describing the fitted parameters.

  • FitOpt (Any) – Fitting options object.

Returns:

best_Sys – Best spin-system object found by the optimizer.

Return type:

Any

spinanalysis._interface_handler.spinanalysis2scipy(x, *objects)[source]

Objective function for the scipy.optimize interface.

Used by scipy.optimize routines.

Parameters:
  • x (GenericAlias[float64]) – Current parameter vector of the optimizer.

  • *objects (Any) – Additional objects required for the simulation and fitting interface.

Raises:

ValueError – If the selected simulation routine is unknown.

Returns:

error – Sum of squared residuals between experimental and simulated data.

Return type:

float

spinanalysis._interface_handler.spinanalysis2scipy_res(x, *objects)[source]

Residual function for scipy.optimize least-squares algorithms.

Returns the absolute residuals between simulation and experiment.

Used by scipy.optimize routines.

Parameters:
  • x (GenericAlias[float64]) – Current parameter vector of the optimizer.

  • *objects (Any) – Additional objects required for the simulation and fitting interface.

Raises:

ValueError – If the selected simulation routine is unknown.

Returns:

error – One-dimensional array containing the absolute residuals.

Return type:

GenericAlias[float64]

spinanalysis._interface_handler.spinanalysis2scipy_singlecore(x, *objects)[source]

Objective function for the scipy.optimize interface.

Used by scipy.optimize.differential_evolution.

Parameters:
  • x (GenericAlias[float64]) – Current parameter vector of the optimizer.

  • *objects (Any) – Additional objects required for the simulation and fitting interface.

Raises:

ValueError – If the selected simulation routine is unknown.

Returns:

error – Sum of squared residuals between experimental and simulated data.

Return type:

float