Code Reference

AMARES Fitting Kernel

Prior Knowledge Parsing Modules

pyAMARES.kernel.PriorKnowledge.assert_peak_format(input_str)

Ensures that numbers are used only as multiplet suffixes in the peak names. :param input_str: The peak name to be validated. :type input_str: str

Raises:
  • ValueError – If the peak name ends with a floating-point number.

  • ValueError – If the peak name contains numbers at the beginning or in the middle.

pyAMARES.kernel.PriorKnowledge.evaluate_expression_with_units(expr, row, MHz)

Evaluate an expression containing numeric values with Hz or ppm units, with consideration for data in a given row and a specified MHz value for conversion.

Parameters:
  • expr (str) – The expression to be evaluated, which may contain numeric values with Hz or ppm units.

  • row (pandas.Series) – A Series or similar structure containing data referenced in expr.

  • MHz (float, optional) – Field strength in MHz. Defaults to 120.0.

Returns:

The result of evaluating the modified expression, or the original expression if evaluation fails.

pyAMARES.kernel.PriorKnowledge.extract_expr(pk, MHz=120.0)

Process expressions within a subset of a DataFrame, converting units in strings and modifying cell values to include parameter prefixes.

Parameters:
  • pk (pandas.DataFrame) – The input DataFrame of Prior Knowledge.

  • MHz (float, optional) – Field Strength in MHz used for unit conversion. Defaults to 120.0.

Returns:

A DataFrame with processed expressions and potential parameter prefixes in cell values.

Return type:

pandas.DataFrame

pyAMARES.kernel.PriorKnowledge.extractini(pk, MHz=120.0)

Process a subset of a DataFrame, evaluating expressions containing units (‘Hz’ or ‘ppm’), and converting values to numeric types where possible.

Parameters:
  • pk (pandas.DataFrame) – The input DataFrame of Prior Knowledge.

  • MHz (float, optional) – Field strength in MHz. Defaults to 120.0.

Returns:

A DataFrame with evaluated expressions and numeric values.

Return type:

pandas.DataFrame

pyAMARES.kernel.PriorKnowledge.find_header_row(filename, comment_char='#')

Determine the index of the first non-commented line.

pyAMARES.kernel.PriorKnowledge.generateparameter(fname, MHz=120.0, g_global=0.0, scale_amplitude=1.0, paramter_prefix=['ak', 'freq', 'dk', 'phi', 'g'], preview=False, delta_phase_rad=0)

Generate a lmfit Parameters object for modeling, based on data read from an Excel or CSV file.

This function reads initial values, expressions, and bounds for each parameter from an Excel file, applies necessary unit conversions, and initializes a Parameters object with this information.

Parameters:
  • fname (str) – Path to the Excel or CSV file containing prior knowledge

  • MHz (float, optional) – Field strength in MHz, used for unit conversions. Defaults to 120.0.

  • g_global (float, optional) – Global value for the g parameter. Defaults to 0.0. If set to False, the g values specified in the prior knowledge will be used.

  • parameter_prefix (list of str, optional) – List of parameter prefixes (e.g., ak, freq, dk, phi, g). Defaults to [‘ak’, ‘freq’, ‘dk’, ‘phi’, ‘g’].

  • delta_phase_rad (float, optional) – Additional phase shift (in radians) to be applied to the prior knowledge phase values. Defaults to 0.0.

Returns:

Parameters object with initialized parameters for modeling.

Return type:

lmfit.Parameters

pyAMARES.kernel.PriorKnowledge.initialize_FID(fid, priorknowledgefile=None, MHz=120, sw=10000, deadtime=0.0002, normalize_fid=False, flip_axis=False, preview=False, xlim=None, truncate_initial_points=0, g_global=0.0, scale_amplitude=1.0, carrier=0.0, lb=2.0, ppm_offset=0, noise_var='OXSA', delta_phase=0.0)

Initialize fitting parameters from prior knowledge (priorknowledgefile) or HSVD initialized result if there is not a prior knowledge file.

Parameters:
  • fid (numpy.ndarray) – The input FID data.

  • priorknowledgefile (str, optional) – Path to an Excel file containing prior knowledge parameters.

  • MHz (float) – The field strength in MHz.

  • sw (float) – The spectral width in Hz.

  • deadtime (float) – The dead time or begin time in seconds before the FID signal starts.

  • normalize_fid (bool) – If True, normalize the FID data.

  • scale_amplitude (float, optional) – Scaling factor applied to the amplitude parameters loaded from priorknowledgefile. Useful when prior knowledge amplitudes significantly differ from the FID amplitude. Defaults to 1.0 (no scaling).

  • flip_axis (bool) – If True, flip the FID axis by taking the complex conjugate. Useful in some GE scanners where the MNS axis needs to be flipped.

  • preview (bool) – If True, display a preview plot of the original and initialized FID spectra.

  • xlim (tuple) – The x-axis limits for the preview plot in ppm.

  • truncate_initial_points (int) – Truncate initial points from FID to remove fast decaying components (e.g. macromolecule). This usually makes baseline more flat.

  • g_global (float, optional) – Global value for the g parameter. Defaults to 0.0. If set to False,

  • used. (the g values specified in the prior knowledge will be)

  • lb (float, optional) – Line broadening parameter in Hz, used for spectrum visualization. Defaults to 2.0.

  • carrier (float, optional) – The carrier frequency in ppm, often used for water (4.7 ppm) or other reference metabolite such as Phosphocreatine (0 ppm).

  • ppm_offset (float, optional) – Adjust the ppm in priorknowledgefile. Default 0 ppm

  • noise_var (str or float) –

    Method or value used to estimate the noise variance in the data. Options include:

    • OXSA: Uses the default noise variance estimation method employed by OXSA. See pyAMARES.util.crlb.evaluateCRB for details.

    • jMRUI: Employs the default noise variance estimation method used by jMRUI.

    • A float value: Directly specifies the noise variance calculated externally.

  • delta_phase (float, optional) – Additional phase shift (in degrees) to be applied to the prior knowledge phase values. Defaults to 0.0.

Returns:

An object containing FID fitting parameters.

Return type:

argparse.Namespace

pyAMARES.kernel.PriorKnowledge.parse_bounds(df)

Parse bounds from a DataFrame and separate them into two DataFrames for lower and upper bounds.

This function assumes that bounds are represented as strings in the format ‘(lower, upper)’, ‘(lower,’ for lower bounds only, or ‘,upper)’ for upper bounds only. It supports bounds specified either as tuples or as individual values.

Parameters:

df (pandas.DataFrame) – The input DataFrame containing bounds as string representations.

Returns:

A DataFrame containing the parsed lower bounds. df_ub (pandas.DataFrame): A DataFrame containing the parsed upper bounds.

Return type:

df_lb (pandas.DataFrame)

pyAMARES.kernel.PriorKnowledge.unitconverter(df_ini, MHz=120.0)

Convert units of parameters in a DataFrame based on their physical context.

This function adjusts ‘chemicalshift’ values by multiplying with the MHz value, ‘linewidth’ values by multiplying with pi, and ‘phase’ values from degrees to radians.

Parameters:
  • df_ini (pandas.DataFrame) – The input DataFrame containing initial conditions or parameters.

  • MHz (float, optional) – The field strength in MHz, used for converting ‘chemicalshift’ values. Defaults to 120.0.

Returns:

A DataFrame with converted unit values in specified rows.

Return type:

pandas.DataFrame

FID modeling functions

pyAMARES.kernel.fid.Jac6(params, x, fid=None)

Calculate the Jacobian matrix for the FID signals generated by multieq6.

This function computes the partial derivatives of FID signals with respect to the parameters used to generate them, which is useful for optimization and analysis.

Parameters:
  • params (dict) – Dictionary or similar structure with FID signal parameters.

  • x (1D array) – The time axis for which the FID signal is generated.

  • fid (1D array) – Not used in this function but included for interface consistency.

Returns:

The interleaved Jacobian matrix of the FID signals with respect to the parameters.

Return type:

numpy.ndarray

pyAMARES.kernel.fid.Jac6c(params, x, fid=None)

Calculate the Jacobian matrix for the FID signals generated by multieq6, excluding g.

This function is a variant of Jac6 and computes the partial derivatives of FID signals with respect to the parameters used to generate them, excluding the lineshape parameter g.

Parameters:
  • params (dict) – Dictionary or similar structure with FID signal parameters.

  • x (1D array) – The time axis for which the FID signal is generated.

  • fid (1D array) – Not used in this function but included for interface consistency.

Returns:

The interleaved Jacobian matrix of the FID signals with respect to the parameters,

excluding the lineshape parameter g.

Return type:

numpy.ndarray

pyAMARES.kernel.fid.add_noise_FID(purefid, snr_target, indsignal=(0, 10), pts_noise=200)

Adds Gaussian white noise to a pure FID signal to achieve a target SNR

Parameters:
  • purefid (numpy.ndarray) – simulated pure FID signal

  • snr_target (float) – The target SNR for noisy FID

  • indsignal (tuple, optional) and pts_noise (int, optional) – See fidSNR

Returns:

The FID signal array with added Gaussian white noise, aiming for the specified target SNR.

Return type:

numpy.ndarray

pyAMARES.kernel.fid.equation6(x, ak=75, fk=0, dk=50, phi=0, g=0)

Generate a FID signal according to equation 6 of Vanhamme, L. et al, J Magn Reson 1997, 129 (1), 35-43.

Parameters:
  • x (1D array) – The time axis for which the FID signal is generated.

  • ak (float) – Amplitude.

  • fk (float) – Frequency.

  • dk (float) – Damping factor.

  • phi (float) – Phase.

  • g (float) – Lineshape parameter. g=0 for Lorentzian; g=1 for Gaussian.

Returns:

An interleaved array containing the real and imaginary parts of the generated FID signal.

Return type:

1D array

pyAMARES.kernel.fid.fft_params(timeaxis, params, fid=False, return_mat=False)

Perform Fast Fourier Transform (FFT) on the FID signals generated by multieq6.

This function optionally returns the raw FID signals or their FFT spectra depending on the provided arguments. It is designed to work with lmfit-style parameter objects.

Parameters:
  • timeaxis (1D array) – The time axis for which the FID signals are generated.

  • params (lmfit.Parameters) – Object containing the FID signal parameters.

  • fid (bool) – If True, returns the uninterleaved FID signals without applying FFT.

  • return_mat (bool) – If True, returns the raw FID signals as generated by multieq6.

Returns:

Depending on the arguments, either raw FID signals, uninterleaved FID signals, or the FFT spectra of the FID signals.

Return type:

numpy.ndarray

pyAMARES.kernel.fid.fidSNR(fid, indsignal=(0, 10), pts_noise=200)

Calculates the signal-to-noise ratio (SNR) of a FID signal.

Here, the SNR is measured by dividing the mean signal amplitude within a specified region (indsignal) by the standard deviation of the noise, determined from the last points (pts_noise) of the FID signal.

Parameters:
  • fid (numpy.ndarray) – The FID from which the SNR is to be calculated.

  • indsignal (tuple, optional) – A tuple including start and end indices

  • (s1

  • amplitude. (s2) of the signal region used to calculate the mean signal)

  • to (Defaults)

  • calculation. (the SNR)

  • pts_noise (int, optional) – The number of noisy points in an FID. There

  • region. (should be no signal in this)

Returns:

The calculated signal-to-noise ratio (SNR) of the provided FID signal.

Return type:

float

pyAMARES.kernel.fid.interleavefid(fid)

Interleave the real and imaginary parts of a 1D or 2D FID signal.

Parameters:

fid (numpy.ndarray) – A numpy array representing the FID signal. Can be 1D or 2D.

Returns:

A numpy array with interleaved real and imaginary parts of the FID signal.

Return type:

numpy.ndarray

pyAMARES.kernel.fid.multieq6(params, x, fid=None, return_mat=False)

Combine multiple FID signals according to equation 6 of Vanhamme, L. et al, J Magn Reson 1997, 129 (1), 35-43.

This function iterates over subsets of parameters in params, each subset used to generate an FID signal via equation6. The function can return either a matrix of individual FID signals or their sum. An existing FID signal can be subtracted from the sum if provided.

Parameters:
  • params (dict) – Dictionary or similar structure with FID signal parameters.

  • x (1D array) – The time axis for which the FID signal is generated.

  • fid (1D array, optional) – Existing FID signal to subtract from the sum of generated FID signals.

  • return_mat (bool) – If True, returns a matrix of individual FID signals; otherwise, returns their sum.

Returns:

Array of individual FID signals or their sum, optionally with fid subtracted.

Return type:

1D or 2D array

pyAMARES.kernel.fid.process_fid(fid, deadtime=0.0, sw=10000, lb=5.0, ifphase=False, ifplot=False)

Processes an FID signal, applies exponential linbroadening, performs FFT, and optionally phases and plots the spectrum.

Parameters:
  • fid (ndarray) – The FID signal array.

  • deadtime (float, optional) – FID dead time in seconds. Defaults to 0.0.

  • sw (int, optional) – Spectral width in Hz. Defaults to 10000.

  • lb (float, optional) – Line broadening factor in Hz. Defaults to 5.0

  • ifphase (bool, optional) – If True, apply phase correction. Defaults to False.

  • ifplot (bool, optional) – If True, plot the spectrum. Defaults to False.

Returns:

The processed spectrum.

Return type:

1D numpy array

pyAMARES.kernel.fid.remove_zero_padding(fid, threshold=1e-10, window_size=5)

Detect and remove the zero-filling-like constant tail from an FID signal using derivative analysis.

This function analyzes an FID signal using derivative analysis to identify and remove constant-value tail sections. These sections may have zero or near-zero values but share the characteristic of being constant.

Parameters:
  • fid (numpy.ndarray) – Input FID signal.

  • threshold (float) – Threshold value for detecting constant regions using signal differentiation. Default: 1e-10

  • window_size (int) – Number of consecutive points needed to confirm a constant region. Default: 5

Returns:

Index where the signal was truncated.

Return type:

int

pyAMARES.kernel.fid.simulate_fid(params, MHz=120.0, sw=10000.0, deadtime=0.0, fid_len=1024, snr_target=50, indsignal=(0, 10), pts_noise=200, preview=False, extra_line_broadening=0.0)

A function that simulates an FID from an lmfit Parameter object and optionally adds Gaussian white noise to achieve a target SNR.

Parameters:
  • params (lmfit.Parameters) – Object containing the FID signal parameters.

  • MHz (float) – The field strength in MHz.

  • sw (float) – The spectral width in Hz.

  • deadtime (float) – The dead time or begin time in seconds before the FID signal starts.

  • fid_len (int, optional) – The number of points of FID. Defaults to 1024.

  • snr_target (float, optional) – The target SNR for the simulated FID signal. If None, a simulated FID without noise is returned. Defaults to 50.

  • indsignal (tuple, optional) – A tuple including start and end indices (s1, s2) of the signal region used to calculate the mean signal amplitude. Defaults to (0, 10). Sometimes the first bad points may be excluded from the SNR calculation.

  • pts_noise (int, optional) – The number of noisy points in an FID. There should be no signal in this region.

  • preview (bool, optional) – If True, plots the FTed simulated FID signal. Defaults to False.

  • extra_line_broadening (float, optional) – Additional line broadening in Hz to apply to the simulated FID. Defaults to 0.0.

Returns:

The simulated FID signal, optionally with added noise to achieve the target SNR.

Return type:

numpy.ndarray

pyAMARES.kernel.fid.uninterleave(fid)

Reconstruct a complex FID signal from an interleaved array.

Parameters:

fid (numpy.ndarray) – A numpy array with interleaved real and imaginary parts of the FID signal. Can be 1D or 2D.

Returns:

A numpy array representing the complex FID signal.

Return type:

numpy.ndarray

AMARES fitting function by lmfit

pyAMARES.kernel.lmfit.check_removed_expr(df)

Checks if the expression (‘expr’) for all parameters in a ftting parameter Dataframe is restricted to a parameter that has already been filtered out.

This function iterates through each ‘expr’ in the provided DataFrame, checking if it is based on a parameter that is not present in the ‘peaklist’. If an ‘expr’ is based on a removed parameter, it’s set to None, and a warning is issued.

Parameters:

df (pandas.DataFrame) – The fitting parameters

Returns:

A copy of the input DataFrame with updated ‘expr’ column where expressions based on removed parameters are set to None.

Return type:

pandas.DataFrame

Raises:

UserWarning – If an ‘expr’ is found to be dependent on a removed parameter.

pyAMARES.kernel.lmfit.dataframe_to_parameters(df)

Convert a Pandas DataFrame into an lmfit.Parameters object.

Parameters:

df (pandas.DataFrame) – The DataFrame to convert, where each row represents a parameter and columns correspond to parameter attributes.

Returns:

An object constructed from the DataFrame.

Return type:

lmfit.Parameters

pyAMARES.kernel.lmfit.filter_param_by_ppm(allpara, fit_ppm, MHz, delta=100)

Filters the input DataFrame based on specified criteria.

Parameters:
  • tofilter_pd (DataFrame) – DataFrame to be filtered.

  • fit_Hz (list) – List of frequency values in Hz to define the filtering range.

  • delta (float) – Extra regions to be included in fit_Hz (Hz).

Returns:

DataFrame filtered based on the specified criteria.

Return type:

DataFrame

pyAMARES.kernel.lmfit.fitAMARES(fid_parameters, fitting_parameters, objective_func=<function default_objective>, method='least_squares', ifplot=True, fit_range=None, inplace=False, plotParameters=None, initialize_with_lm=False, fit_kws=None)

Fit the AMARES algorithm to the given FID parameters and fitting parameters.

This function applies the AMARES fitting algorithm to the provided FID and fitting parameters, optionally plotting the results and modifying the parameters in place.

Parameters:
  • fid_parameters (argspace namespace) – The FID parameters to be used in the fitting process.

  • fitting_parameters (lmfit.Parameters) – The initial parameters for lmfitting

  • objective_func (function) – The objective function to be minimized during the fitting.

  • method (str, optional) – The method to be used for fitting. Defaults to ‘least_squares’.

  • initialize_with_lm (bool, optional, default False, new in 0.3.9) – If True, a Levenberg-Marquardt initializer (least_sq) is executed internally.

  • fit_range (tuple or None, optional) – The range within which to perform the fitting. Defaults to None.

  • inplace (bool, optional) – If True, the original fid_parameters will be modified. Otherwise, a copy will be modified and returned.

  • plotParameters (argparse.Namespace or None, optional) –

    A namespace containing parameters for plotting and data processing. The namespace includes:

    • deadtime (float): The dead time before the FID acquisition starts.

    • lb (float): Line broadening factor in Hz.

    • sw (float): Spectral width in Hz.

    • xlim (tuple of float): Limits for the x-axis in ppm, for example, (10, -20).

    • ifphase (bool): turn on 0th and 1st order phasing.

    If None, default parameters defined in fid_parameters.plotParameters are used.

Returns:

If inplace=True, the function returns the lmfit.MinimizerResult object while the input fid_parameters is modified in place. Otherwise, the function returns the modified fid_parameters instead of modifying fid_parameters inplace.

pyAMARES.kernel.lmfit.fitAMARES_kernel(fid_parameters, fitting_parameters, objective_func, method='least_squares', fit_range=None, fit_kws=None)

Core fitting routine for the AMARES algorithm using a specified objective function and fitting parameters.

Parameters:
  • fid_parameters (argspace namespace) – Contains FID data and associated parameters like time axis and ppm scale.

  • fitting_parameters (lmfit.Parameters) – Parameters for the fitting process.

  • objective_func (function) – The objective function to be minimized, should take at least the fitting parameters and additional data as arguments.

  • method (str, optional) – Minimization method used by lmfit.Minimizer. Defaults to ‘least_squares’.

  • fit_range (tuple or None, optional) – Indices specifying the fitting range on the ppm scale. Uses full range if None.

  • fit_kws (dict, optional) – Options to pass to the lmfit.Minimizer

Returns:

Object containing the fitting results.

Return type:

lmfit.MinimizerResult

pyAMARES.kernel.lmfit.load_parameter_from_csv(filename='params.csv')

Loads fitting parameters from a CSV file into an lmfit.Parameters object for fitAMARES.

Parameters:

filename (str, optional) – The name of the CSV file from which to load the parameters. Defaults to ‘params.csv’.

Returns:

An object containing the fitting parameters loaded from the CSV file.

Return type:

lmfit.Parameters

Note

The function reads the CSV file into a DataFrame, processes it to convert NaN to pd.Nonetype so that lmfit can handle, and then converts it to an lmfit.Parameters object.

pyAMARES.kernel.lmfit.parameters_to_dataframe(params)

Convert an lmfit.Parameters object into a Pandas DataFrame.

Parameters:

params (lmfit.Parameters) – The lmfit.Parameters object to convert.

Returns:

A DataFrame with each parameter as a row and its attributes as columns.

Return type:

pandas.DataFrame

pyAMARES.kernel.lmfit.parameters_to_dataframe_result(params)

Convert the fitting result as a lmfit.Parameters object into a Pandas DataFrame.

Parameters:

params (lmfit.Parameters) – The lmfit.Parameters object to convert.

Returns:

A DataFrame with each parameter as a row and its attributes as columns.

Return type:

pandas.DataFrame

pyAMARES.kernel.lmfit.params_to_result_pd(params, MHz=300.0)

Converts a Parameters object back into a DataFrame format. The inverse function of result_pd_to_params.

Parameters:
  • params (Parameters) – The lmfit Parameters() object.

  • MHz (float) – Field strength in MHz.

Returns:

The fitting results table.

Return type:

pd.DataFrame

pyAMARES.kernel.lmfit.plotAMARES(fid_parameters, fitted_params=None, plotParameters=None, filename=None)

Plots the results of AMARES fitting.

This function visualizes the fitted results obtained from the AMARES algorithm by plotting the original FID data, the fitted FID data, and the corresponding frequency components identified during the fitting process.

Parameters:
  • fid_parameters (argspace namespace) – The FID parameters, including time axis and original FID data, used during the fitting process.

  • fitted_params (lmfit.Parameters, optional) – The fitting results obtained from the lmfit fitting

  • plotParameters (argparse.Namespace, optional) –

    A namespace containing parameters for plotting and data processing. The namespace includes:

    • deadtime (float): The dead time before the FID acquisition starts.

    • lb (float): Line broadening factor in Hz.

    • sw (float): Spectral width in Hz.

    • xlim (tuple of float): Limits for the x-axis in ppm, for example, (10, -20).

    • ifphase (bool): turn on 0th and 1st order phasing.

    filename (str or None, optional): If provided, the figure will be saved to this file. Defaults to None.

pyAMARES.kernel.lmfit.print_lmfit_fitting_results(result)

Print important fitting results from an lmfit MinimizerResult object.

Parameters:

result (lmfit.MinimizerResult) – The result object from lmfit fitting.

pyAMARES.kernel.lmfit.result_pd_to_params(result_table, MHz=120.0)

Converts fitted results from a DataFrame format into a Parameters object for simulation.

Parameters:
  • result_table (pd.DataFrame) – The fitting results table, which can be like result_sum or result_multiplet.

  • MHz (float) – Field strength in MHz.

Returns:

A lmfit Parameters() object, ready for use in simulations but not for fitting, because there is no constraint.

Return type:

Parameters

Notes

This function serves as a utility for simulate_fid.

pyAMARES.kernel.lmfit.save_parameter_to_csv(params, filename='params.csv')

Saves the fitting parameters into a CSV file for easy editing

Parameters:
  • params (lmfit.Parameters) – The lmfit.Parameters object containing the fitting parameters to be saved.

  • filename (str, optional) – The name of the CSV file where the parameters will be saved. Defaults to ‘params.csv’.

Note

This function converts the params object to a DataFrame before saving it as a CSV file.

pyAMARES.kernel.lmfit.set_vary_parameters(params, vary_parameter_list=[])

Fix all parameters except for those specified in vary_parameter_list and set them to be varied.

Parameters:
  • params (lmfit.Parameters object) – Initial parameters for AMARES fitting

  • vary_parameter_list (list of str) – A list of the names of parameters to be varied

Returns:

The modified Parameters object with the specified

Return type:

lmfit.Parameters object

parameters set to vary and all others fixed.

Objective Function

Libs

pyAMARES.libs.MPFIR(fid, dwelltime, MHz=120.0, ppm_range=(-20, 20), rippass=0.01, M=50, carrier=0, ifplot=False, xlim=None)

Filter out a specific region of the spectrum using the maximum-phase FIR filter (Ref 1)

This function applies an MPFIR filter to the provided FID signal based on the specified parameters, optionally plotting the original and filtered FID signals in the frequency domain. Adapted from the SPID software. See Ref2.

Parameters:
  • fid (1D array) – The FID signal array.

  • dwelltime (float) – Dwell time.

  • MHz – The field strength in MHz.

  • ppm_range (tuple, optional) – The range of ppm values to filter. Defaults to (-20, 20).

  • rippass (float, optional) – The passband ripple of the filter. Defaults to 0.01.

  • M (int, optional) – The filter length. Defaults to 50.

  • carrier (float, optional) – The carrier frequency offset in ppm. Defaults to 0.

  • ifplot (bool, optional) – If True, plots the input and filtered FID signals. Defaults to False.

  • xlim (tuple, optional) – The x-axis limits for the plot. Defaults to None.

Returns:

The filtered FID signal.

References

    1. Sundin et al, JMR, 139(2):189-204, 1999.

  1. Poullet et al, Manual: Simulation Package based on In vitro Databases (SPID).

pyAMARES.libs.filter_fid_by_ppm(opts, fit_ppm, ifplot=False, rippass=0.01, M=50)

Filters the FID signal in the argspace Namespace object ‘opts’ by a specified ppm range.

This function takes an ‘opts’ object containing FID signal parameters, applies a Minimum Phase Finite Impulse Response (MPFIR) filter to the FID signal based on the specified ppm range, and returns a modified ‘opts’ object with the filtered FID.

Parameters:
  • opts (Namespace) – An object containing FID signal parameters, including the FID signal, dwell time, spectrometer frequency, and optionally x-axis limits for plotting.

  • fit_ppm (tuple) – The ppm range to filter the FID signal by.

  • ifplot (bool, optional) – If True, plots the original and filtered FID signals. Defaults to False.

  • rippass (float, optional) – The passband ripple of the MPFIR filter. Defaults to 0.01.

  • M (int, optional) – The number of coefficients for the MPFIR filter. Defaults to 50.

Returns:

A modified copy of ‘opts’ with the filtered FID signal.

Return type:

Namespace

MPFIR

pyAMARES.libs.MPFIR.MPFIR(fid, dwelltime, MHz=120.0, ppm_range=(-20, 20), rippass=0.01, M=50, carrier=0, ifplot=False, xlim=None)

Filter out a specific region of the spectrum using the maximum-phase FIR filter (Ref 1)

This function applies an MPFIR filter to the provided FID signal based on the specified parameters, optionally plotting the original and filtered FID signals in the frequency domain. Adapted from the SPID software. See Ref2.

Parameters:
  • fid (1D array) – The FID signal array.

  • dwelltime (float) – Dwell time.

  • MHz – The field strength in MHz.

  • ppm_range (tuple, optional) – The range of ppm values to filter. Defaults to (-20, 20).

  • rippass (float, optional) – The passband ripple of the filter. Defaults to 0.01.

  • M (int, optional) – The filter length. Defaults to 50.

  • carrier (float, optional) – The carrier frequency offset in ppm. Defaults to 0.

  • ifplot (bool, optional) – If True, plots the input and filtered FID signals. Defaults to False.

  • xlim (tuple, optional) – The x-axis limits for the plot. Defaults to None.

Returns:

The filtered FID signal.

References

    1. Sundin et al, JMR, 139(2):189-204, 1999.

  1. Poullet et al, Manual: Simulation Package based on In vitro Databases (SPID).

pyAMARES.libs.MPFIR.filter_fid_by_ppm(opts, fit_ppm, ifplot=False, rippass=0.01, M=50)

Filters the FID signal in the argspace Namespace object ‘opts’ by a specified ppm range.

This function takes an ‘opts’ object containing FID signal parameters, applies a Minimum Phase Finite Impulse Response (MPFIR) filter to the FID signal based on the specified ppm range, and returns a modified ‘opts’ object with the filtered FID.

Parameters:
  • opts (Namespace) – An object containing FID signal parameters, including the FID signal, dwell time, spectrometer frequency, and optionally x-axis limits for plotting.

  • fit_ppm (tuple) – The ppm range to filter the FID signal by.

  • ifplot (bool, optional) – If True, plots the original and filtered FID signals. Defaults to False.

  • rippass (float, optional) – The passband ripple of the MPFIR filter. Defaults to 0.01.

  • M (int, optional) – The number of coefficients for the MPFIR filter. Defaults to 50.

Returns:

A modified copy of ‘opts’ with the filtered FID signal.

Return type:

Namespace

HSVD initialization

pyAMARES.util.hsvd.HSVDinitializer(fid_parameters, fitting_parameters=None, num_of_component=12, lw_threshold=500, verbose=False, preview=False)

Initializes HSVD parameters for a given FID signal.

Parameters:
  • fid_parameters (argspace.Namespace) – An object containing FID, dwell time, time axis, ppm, MHz, g_global, Hz, and xlim_Hz attributes.

  • fitting_parameters (lmfit.Parameters) – Parameters for fitting, if any.

  • num_of_component (int) – Number of components to decompose the FID into.

  • lw_threshold (float) – Linewidth threshold for filtering out broad components.

  • verbose (bool) – If True, prints additional information during processing.

  • preview (bool) – If True, displays a preview of the fitted components.

Returns:

A DataFrame containing the initialized parameters for HSVD.

Return type:

pandas.DataFrame

pyAMARES.util.hsvd.HSVDp0(hsvdfid, timeaxis, ppm, MHz=120, ifplot=True)

Fit a Lorentzian model to an HSVD-processed NMR FID to estimate initial parameters.

Parameters:
  • hsvdfid (numpy.ndarray) – The HSVD-processed FID.

  • timeaxis (numpy.ndarray) – The time axis for the FID data.

  • ppm (numpy.ndarray) – The chemical shift axis in ppm.

  • MHz (float, optional) – The field strength in MHz. Defaults to 120 MHz.

  • ifplot (bool, optional) – Flag to plot the original and fitted spectra. Defaults to True.

Returns:

An array containing the fitted parameters [amplitude, frequency, linewidth, phase].

Return type:

numpy.ndarray

pyAMARES.util.hsvd.assign_hsvd_peaks(measured_peaks_df, peak_info=None)

Assign peak names to measured peaks based on provided information and keep other columns in the measured_peaks_df.

Parameters:
  • measured_peaks_df (pandas.DataFrame) – DataFrame with a column [‘fk’] containing measured peak positions and possibly other columns.

  • peak_info (pandas.DataFrame) – DataFrame with columns [‘name’, ‘value’, ‘min’, ‘max’].

Returns:

DataFrame with original columns from measured_peaks_df plus [‘name’, ‘value’, ‘min’, ‘max’].

Return type:

pandas.DataFrame

pyAMARES.util.hsvd.hsvd_initialize_parameters(temp_to_unfold, allpara_hsvd=None, g_global=0.0)

Update parameters in allpara_hsvd based on the values in temp_to_unfold.

Parameters:
  • temp_to_unfold (pandas.DataFrame) – DataFrame containing parameter values and names.

  • allpara_hsvd (dict) – Dictionary (or similar structure) to be updated.

Returns:

Modified allpara_hsvd with updated values.

Return type:

dict

pyAMARES.util.hsvd.uniquify_dataframe(df)

Processes a DataFrame to ensure that for each unique name, only the entry with the maximum absolute ak value is retained with its name. The name for other entries in the same group is set to NaN. Rows where name is initially NaN are left unchanged.

Parameters:

df (pandas.DataFrame) – The input DataFrame with name and ak columns.

Returns:

A DataFrame where for each unique name, only the entry with the maximum absolute

ak value retains its name, and others have their name set to NaN.

Return type:

pandas.DataFrame

HLSVDPro

The hlsvd documentation can be found in the VESPA documentation.

Logging System

pyAMARES.libs.logger.get_logger(name: str, format_string: str = '[AMARES | {levelname}] {message}') Logger

Get or create a logger with the specified name and format.

If the logger has no existing handlers, it initializes one based on the provided log style. The log level defaults to DEFAULT_LOG_LEVEL. To change it globally, use set_log_level().

Parameters:
  • name (str) – The name of the logger.

  • format_string (str, optional) – The format string for log messages (default: “[AMARES | {levelname}] {message}”).

Returns:

A configured logger instance.

Return type:

logging.Logger

Raises:

ValueError – If an invalid LOG_STYLE is provided.

Examples

>>> logger = get_logger("example_logger")
>>> logger.debug("This is a debug message.")
[DEBUG] example_logger: This is a debug message.
pyAMARES.libs.logger.set_log_level(level: str = 'info', verbose: bool = True)

Set the global logging level for all loggers.

This function sets the logging level across the entire application using the basicConfig method of the logging module. It also ensures that all existing loggers adhere to this global level.

Parameters:
  • level (str) – The logging level to set globally. Acceptable values are ‘critical’, ‘error’, ‘warning’, ‘info’, ‘debug’, and ‘notset’. Default is the DEFAULT_LOG_LEVEL.

  • verbose (bool) – Print an overview of the log levels and highlight the selected level.

Examples

>>> set_log_level('info')
>>> logger = logging.getLogger('example_logger')
>>> logger.debug('This debug message will not show.')
>>> logger.info('This info message will show.')
[INFO] example_logger: This info message will show.

Utilities

Cramer Rao Lower Bound Estimation

pyAMARES.util.crlb.calculateCRB(D, variance, P=None, verbose=False, condthreshold=100000000000.0, cond=False)

Calculates the Cramer-Rao Bound (CRB) for parameter estimation error.

This function computes the CRB based on the provided Jacobian matrix (D), the noise variance, and optionally prior knowledge represented by matrix P.

Parameters:
  • D (numpy.ndarray) – Jacobian matrix.

  • variance (float) – The variance of the noise in the measurements.

  • P (numpy.ndarray, optional) – Prior knowledge matrix. Assumes identity if None. Defaults to None.

  • verbose (bool, optional) – If True, prints detailed information about the computation. Defaults to False.

  • condthreshold (float, optional) – Condition number threshold to identify ill-conditioned matrices. Defaults to 1e11.

  • cond (bool, optional) – If True, also returns a boolean indicating if the Fisher information matrix is ill-conditioned.

Returns:

The square root of the diagonal elements of the CRB covariance matrix, indicating the lower bound on the standard deviation of the parameter estimates.

If cond is True, a boolean indicating if the Fisher information matrix is ill-conditioned.

Return type:

numpy.ndarray or boolean

References

  1. S Cavassila et al NMR Biomed. 2001 Jun;14(4):278-83.

  2. Purvis et al, OXSA: An open-source magnetic resonance spectroscopy analysis toolbox in MATLAB. PLoS ONE 12(9): e0185356.

pyAMARES.util.crlb.create_pmatrix(pkpd, verbose=False, ifplot=False)

Creates a prior knowledge matrix (P-matrix) from a prior knowledge dataframe.

The P-matrix represents the relationships and constraints between parameters based on prior knowledge, calculated according to Reference: S Cavassila et al., NMR Biomed. 2001 Jun;14(4):278-83.

Parameters:
  • pkpd (pandas.DataFrame) – Prior knowledge dataframe with the expr column.

  • verbose (bool) – Flag to enable verbose output for debugging.

  • ifplot (bool) – Flag to enable plotting of the P-matrix.

Returns:

Transposed P-matrix representing the relationships between parameters.

Return type:

numpy.ndarray

pyAMARES.util.crlb.evaluateCRB(outparams, opts, P=None, Jacfunc=<function Jac6>, verbose=False)

Evaluates the Cramer-Rao Bound (CRB) for lmfit fitting results, fitting parameters, and an optional prior knowledge matrix.

This function uses a specified Jacobian function to compute the Jacobian matrix, calculates the residuals between model predictions and actual data, computes the variance of these residuals, and then calculates the CRB based on this information.

Parameters:
  • outparams – Output parameters from the lmfit fitting results.

  • opts (argspace.Namespace) – An object containing options and data for the CRB calculation, including: timeaxis (numpy.ndarray): The time axis for the data. fid (numpy.ndarray): The FID signal.

  • P (numpy.ndarray, optional) – Prior knowledge matrix. Assumes identity if None. Defaults to None.

  • Jacfunc (function, optional) – The function used to compute the Jacobian matrix. Defaults to Jac6.

  • verbose (bool, optional) – If True, displays additional information about the process, including a plot of the residuals.

Returns:

The Cramer-Rao Bound (CRB) values calculated for the given parameters. Note: opts will be modified in place.

Return type:

numpy.ndarray

AMARES Report Generation

pyAMARES.util.report.highlight_dataframe(df, by='CRLB(%)', is_smaller=True, threshold=20.0, numeric_format='{:.3f}')

A versatile tool that highlights rows in a DataFrame based on a specified column’s values.

This function applies a background color to the rows of the input DataFrame. Rows where the specified column’s value meets the threshold condition are highlighted in green, while the others are highlighted in red.

Parameters:
  • df (pd.DataFrame) – The input DataFrame to be styled.

  • by (str) – The column name to be used for the threshold comparison.

  • is_smaller (bool) – If True, highlight rows where the column value is less than or equal to the threshold. If False, highlight rows where the column value is greater than or equal to the threshold.

  • threshold (float) – The threshold value to compare against.

  • numeric_format (str) – The format string used to display numeric values in the DataFrame. By default, {:.3f} formats a float as 0.241, while {:.1f} formats it as 0.2.

Returns:

A DataFrame for presentation of the results with selected rows are highlighted by green.

Return type:

pandas.Styler

Examples

>>> highlight_dataframe(FIDobj.result_multiplets)
>>> highlight_dataframe(FIDobj.result_sum, numeric_format='{:1.1f}')
>>> highlight_dataframe(FIDobj.result_sum, threshold=5, by='SNR', is_smaller=False)
pyAMARES.util.report.report_amares(outparams, fid_parameters, verbose=False)

Generates a comprehensive report on AMARES analysis results.

Parameters:
  • outparams (lmfit fitting parameter) – Output parameters from the fitting process.

  • fid_parameters (argspace Namespace object) – FID parameters object.

  • verbose (bool, optional) – Controls verbosity of output. Defaults to False.

Returns:

A DataFrame for presentation of the results with rows whose CRLB<=20 are highlighted by green.

Return type:

pandas.Styler

pyAMARES.util.report.report_crlb(outparams, crlb, Jacfunc=None)

Generates a report on Cramér-Rao Lower Bounds (CRLBs).

Parameters:
  • outparams (lmfit Parameters object) – DataFrame containing model parameters.

  • crlb (numpy.ndarray) – Array of CRLB values.

  • Jacfunc (callable, optional) – Function to compute the Jacobian. Defaults to None.

Returns:

DataFrame with CRLB information for relevant parameters.

Return type:

pandas.DataFrame

pyAMARES.util.report.sum_multiplets(df)

Sums amplitude and standard deviation for multiplets with the same base name in the given DataFrame.

Groups the DataFrame on base peak names (extracted by removing digits) and aggregates the columns, summing amplitude and standard deviation but taking the first value for other columns like chemical shift.

Parameters:

df (DataFrame) – DataFrame with columns including ‘amplitude’, ‘sd’, ‘chem shift(ppm)’

Returns:

DataFrame grouped and aggregated on base peak names

Return type:

DataFrame

Visualization of Fitting Results

pyAMARES.util.visualization.combined_plot(hsvdarr, ppm, p_pd, fid, fid_fit, xlim=None, mode='real', label='Fitted Spectrum', title=None, xlabel=None, plotParameters=None, filename=None)

Plot the results of AMARES or HSVD fitting results

This function creates a two-part figure: the top part displays the fitted spectrum alongside the original FID data and their residual, and the bottom part previews the AMARES or HSVD fitting results

Parameters:
  • hsvdarr (numpy.ndarray) – Array containing AMARES or HSVD data for each component.

  • ppm (numpy.ndarray) – Array of chemical shift values (ppm).

  • p_pd (pandas.DataFrame) – DataFrame containing peak information for each component.

  • fid (numpy.ndarray) – Array containing the original FID data.

  • fid_fit (numpy.ndarray) – Array containing the fitted FID data.

  • xlim (tuple, optional) – Lower and upper limits for the x-axis. Defaults to None.

  • mode (str, optional) – Mode for plotting the spectrum (real for real part, abs or mag for magnitude). Defaults to real.

  • label (str, optional) – Label for the fitted spectrum line in the plot. Defaults to ‘Fitted Spectrum’.

  • title (str, optional) – Title for the entire figure. Defaults to None.

  • xlabel (str, optional) – Label for the x-axis, shared by both subplots. Defaults to None.

  • plotParameters (argparse.Namespace, optional) –

    A namespace containing parameters for plotting and data processing. The namespace includes:

    • deadtime (float): The dead time before the FID acquisition starts.

    • lb (float): Line broadening factor in Hz.

    • sw (float): Spectral width in Hz.

    • xlim (tuple of float): Limits for the x-axis in ppm, for example, (10, -20).

    • ifphase (bool): turn on 0th and 1st order phasing.

    filename (str or None, optional): If provided, the figure will be saved to this file. Defaults to None.

pyAMARES.util.visualization.plot_fit(ax, fid, fid_fit, ppm, xlim=None, mode='real', label='Fitted Spectrum', plotParameters=None)

Plots the fitted spectrum, original spectrum, and residual for comparison.

Parameters:
  • ax (matplotlib.axes._axes.Axes) – Matplotlib axes object for plotting.

  • fid (numpy.ndarray) – Array containing the original FID data.

  • fid_fit (numpy.ndarray) – Array containing the fitted FID data.

  • ppm (numpy.ndarray) – Array of chemical shift values (ppm).

  • xlim (tuple, optional) – Lower and upper limits for the x-axis. Defaults to None.

  • mode (str, optional) –

    Mode for plotting the spectrum. Defaults to real.

    • real: Plots the real part of the spectrum.

    • abs or mag: Plots the absolute value (magnitude) of the spectrum.

  • label (str, optional) – Label for the fitted spectrum line. Defaults to ‘Fitted Spectrum’.

  • plotParameters (argparse.Namespace, optional) –

    A namespace containing parameters for plotting and data processing. The namespace includes:

    • deadtime (float): The dead time before the FID acquisition starts.

    • lb (float): Line broadening factor in Hz.

    • sw (float): Spectral width in Hz.

    • xlim (tuple of float): Limits for the x-axis in ppm, for example, (10, -20).

    • ifphase (bool): turn on 0th and 1st order phasing.

pyAMARES.util.visualization.preview_HSVD(ax, hsvdarr, ppm, p_pd, xlim=None, title='', xlabel=None)

Preview the HSVD analysis results.

Parameters:
  • ax (matplotlib.axes._axes.Axes) – Matplotlib axes object for plotting.

  • hsvdarr (numpy.ndarray) – Array containing HSVD data.

  • ppm (numpy.ndarray) – Array of chemical shift values (ppm).

  • p_pd (pandas.DataFrame) – DataFrame containing peak information.

  • xlim (tuple, optional) – Lower and upper limits for the x-axis. Defaults to None.

  • title (str, optional) – Title for the plot. Defaults to "".

  • xlabel (str, optional) – Label for the x-axis. Defaults to None.

Multiprocessing

pyAMARES.util.multiprocessing.fit_dataset(fid_current, FIDobj_shared, initial_params, method='leastsq', initialize_with_lm=False, objective_func=None)

Fits a dataset to a shared FID Parameter object using the AMARES algorithm with specified initial parameters and fitting method.

This function deep copies a shared FID object so that it won’t conflict in the multiprocessing. Then it updates its FID with the current dataset, and applies the AMARES fitting algorithm using the provided initial parameters. The fitting results are returned in the pandas dataframe FIDobj.result_multiplet

Parameters:
  • fid_current (array-like) – The current FID dataset to be fitted.

  • FIDobj_shared (FID object) – A shared FID object template to be used for fitting. This object should contain common settings and parameters applicable to all datasets.

  • initial_params (lmfit.Parameters) – Initial fitting parameters for the AMARES algorithm.

  • method (str, optional) – The fitting method to be used. Defaults to “leastsq” (Levenberg-Marquardt).

  • initialize_with_lm (bool, optional, default False, new in 0.3.9) – If True, a Levenberg-Marquardt initializer (least_sq) is executed internally. See pyAMARES.lmfit.fitAMARES for details.

  • objective_func (callable, optional) – Custom objective function for pyAMARES.lmfit.fitAMARES. If None, the default objective function will be used. Defaults to None.

Returns:

A DataFrame containing the fitting results for the current dataset. Returns None if an error occurs during fitting.

Return type:

pandas.DataFrame or None

Raises:

Exception – If an error occurs during the fitting process, it is caught and a message is printed to the console, and None is returned.

pyAMARES.util.multiprocessing.redirect_stdout_to_file(filename)

A context manager that redirects stdout and stderr to a specified file.

This function temporarily redirects the standard output (stdout) and standard error (stderr) streams to a file, capturing all outputs generated within the context block.

pyAMARES.util.multiprocessing.run_parallel_fitting_with_progress(fid_arrs, FIDobj_shared, initial_params, method='leastsq', initialize_with_lm=False, num_workers=8, logfilename='multiprocess_log.txt', objective_func=None, notebook=True)

Runs parallel AMARES fitting of multiple FID datasets using a shared FID object template and initial parameters.

This function deep copies a shared FID object and performs parallel fitting on an array of FID datasets. It utilizes a process pool to handle the fitting tasks concurrently, logging progress and results to a specified file logfilename. The execution time is printed upon completion.

Parameters:
  • fid_arrs (numpy.ndarray) – An array of FID datasets to be fitted, where each row corresponds to a different dataset.

  • FIDobj_shared (FID object) – A shared FID object template to be used for all fitting tasks. This object should contain common settings and parameters applicable to all datasets.

  • initial_params (lmfit.Parameters) – Initial fitting parameters for the AMARES algorithm.

  • method (str, optional) – The fitting method to be used. Defaults to ‘leastsq’ (Levenberg-Marquardt).

  • initialize_with_lm (bool, optional, default False, new in 0.3.9) – If True, a Levenberg-Marquardt initializer (least_sq) is executed internally. See pyAMARES.lmfit.fitAMARES for details.

  • num_workers (int, optional) – The number of worker processes to use in parallel processing. Defaults to 8.

  • logfilename (str, optional) – The name of the file where the progress log is saved. Defaults to ‘multiprocess_log.txt’.

  • objective_func (callable, optional) – Custom objective function for pyAMARES.lmfit.fitAMARES. If None, the default objective function will be used. Defaults to None.

  • notebook (bool, optional) – If True, uses tqdm.notebook for progress display in Jupyter notebooks. If False, uses standard tqdm. Defaults to True.

Returns:

A list of fitting result objects (e.g., pandas DataFrames) for each FID dataset.

Return type:

list

File I/O

Note

This module is still under active development. pyAMARES is designed to work with FID as a 1D NumPy complex array, making it compatible with other Python NMR/MRS libraries. Currently, pyAMARES.fileio.readmrs supports relatively general data formats, such as CSV, ASCII, Python NumPy, and Matlab MAT-files or Version 7.3 MAT-files. Users are encouraged to develop and use their own FID I/O modules.

Read 2-Column FID Data

pyAMARES.fileio.readmat.readmrs(filename)

Reads MRS data from a file, supporting multiple file formats including ASCII, CSV, NPY, and MATLAB files.

This function detects the file format based on the file extension and loads the MRS data accordingly. For ASCII files, it expects two columns representing the real and imaginary parts. NPY files should contain a NumPy array, and MATLAB files should contain a variable named fid and/or data, when both fid and data present, only fid will be used. This function detects the file format based on the file extension and loads the MRS data accordingly. For ASCII files, it expects two columns representing the real and imaginary parts. NPY files should contain a NumPy array, and MATLAB files should contain a variable named fid and/or data, when both fid and data present, only fid will be used.

Parameters:

filename (str) – The path and name of the file from which to load the MRS data.

Returns:

A complex numpy array containing the MRS data from the file.

Return type:

numpy.ndarray

Raises:
  • FileNotFoundError – If the specified file does not exist or cannot be opened.

  • ValueError – If the file format is unsupported or the required data cannot be found in the file.

  • KeyError

Example

>>> data = readmrs('fid.txt')
>>> print(data.shape)
>>> print(data.dtype)

Note

  • For ASCII files, data is expected to be in two columns with the first column as the real part and the second as the imaginary part.

  • For NPY files, it directly loads the NumPy array.

  • For MATLAB files, both traditional (.mat) and V7.3 (.mat) files are supported, but the variable must be named fid or data.

Read GE MNS Research Pack fidall Data

pyAMARES.fileio.readfidall.header2par(h)

Extracts MHz, deadtime, and sw from the GE MR header structure.

This function reads the GE MR header structure as a Python dict and returns an argparse Namespace with the parameters needed for AMARES fitting.

Parameters:

h (dict) – A dictionary representing the header of an MRS file, which contains nested fields with the MRS acquisition parameters.

Returns:

A namespace object containing the extracted parameters:
  • MHz (float): The magnetic field strength in MHz.

  • sw (float): The spectral width in Hz.

  • deadtime (float): Echo time in seconds.

Return type:

argparse.Namespace

Note

  • Rolf Schulte: It is better to use the echo time (including the time to the iso center of the RF pulse) for initializing the linear phase in the AMARES fit.

pyAMARES.fileio.readfidall.header2par_v73(h)

Extracts MHz, deadtime, and sw from the GE MR header structure (V-7.3).

This function reads the GE MR header structure as a Python dict and returns an argparse Namespace with the parameters needed for AMARES fitting.

Parameters:

h (dict) – A dictionary representing the header of an MRS file, which contains nested fields with the MRS acquisition parameters.

Returns:

A namespace object containing the extracted parameters:
  • MHz (float): The magnetic field strength in MHz.

  • sw (float): The spectral width in Hz.

  • deadtime (float): Echo time in seconds.

Return type:

argparse.Namespace

Note

  • Rolf Schulte: It is better to use the echo time (including the time to the iso center of the RF pulse) for initializing the linear phase in the AMARES fit.

pyAMARES.fileio.readfidall.read_fidall(filename)

Loads MRS data and associated header information from the GE MNS Research Pack fidall generated MATLAB .mat file, handling both v7.3 and earlier versions of MATLAB files.

This function detects the version of the MATLAB file and uses appropriate methods to load the data. It attempts to extract the complex data (‘data’) variable from the file. It also parses the header using a specific function depending on the file version to extract MRS parameters for AMARES fitting

Parameters:

filename (str) – The path and name of the .mat file to be read.

Returns:

  • header (argparse.Namespace): A namespace object containing MRS parameters for AMARES fitting spectral width (sw), dead time

  • data (numpy.ndarray): A complex numpy array containing the FID

Return type:

tuple

Raises:
  • FileNotFoundError – If the specified file does not exist.

  • KeyError – If the ‘data’ key is not found in the loaded .mat file.

  • Warning – Warns if the data loaded is not 1D, as the pyAMARES.fit_AMARES function only supports 1D MRS data.

Example

>>> header, data = read_fidall('sample_data.mat')
>>> print(header.MHz, header.sw)
>>> print(data.shape)

A Wrapper for Reading NifTI-MRS

pyAMARES.fileio.readnifti.read_nifti(filename)

Reads MRS data from a NIfTI-MRS file, it assumes single voxel spectroscopy (SVS), and returns a header and an 1D FID array

Parameters:

filename (str) – The path and name of the NIfTI file to load.

Returns:

A tuple containing:
  • header (argparse.Namespace): A namespace object with center frequency (MHz), spectral width (sw), dwell time (second), and optionally dead time (second).

  • fid (numpy.ndarray): A complex numpy array containing the frequency-domain MRS data.

Return type:

tuple

Raises:
  • FileNotFoundError – If the specified file does not exist.

  • IndexError – If the required header extension is not found in the NIfTI file.

  • KeyError – If essential metadata is missing in the NIfTI header.

  • ImportError – If nibabel is not installed.

Example

>>> header, fid = read_nifti('example_mrs.nii')
>>> print(header.MHz, header.sw)
>>> print(fid.shape)

Note