Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

fitting.AMARES

fitting.AMARES

Attributes

NameDescription
DEFAULT_BATCH_FIT_PARAMS
DEFAULT_FIT_PARAMS
DEFAULT_INIT_PARAMS
DEFAULT_PLOT_PARAMS

Classes

NameDescription
FitResultsContainer for extracted pyAMARES batch fitting results.

FitResults

fitting.AMARES.FitResults(badfit_ids, goodness_of_fit, combined_fit_results)

Container for extracted pyAMARES batch fitting results.

Attributes

NameDescription
badfit_ids
combined_fit_results
goodness_of_fit

Functions

NameDescription
add_colored_table_to_plotAdd a colored table beneath the given axis in the plot.
extract_from_fit_resultsExtract goodness-of-fit metrics and combined fit parameters from batch fit results.
fit_multiple_fidsBatch-fit multiple FIDs in parallel using the pyAMARES library.
fit_single_fidFit a single FID using the pyAMARES fitting library.
load_extracted_resultsLoad extracted fitting results from an HDF5 file.
multiindex_to_priorknowledgeConvert a MultiIndex prior-knowledge DataFrame back into a raw DataFrame.
plot_amares_fittingPlot an AMARES fitting result, optionally with a parameter table.
priorknowledge_to_multiindexConvert a prior-knowledge DataFrame into a MultiIndex DataFrame.
save_extracted_resultsSave the extracted fitting results to an HDF5 file.

add_colored_table_to_plot

fitting.AMARES.add_colored_table_to_plot(table_ax, table, sig=3)

Add a colored table beneath the given axis in the plot.

Parameters

NameTypeDescriptionDefault
table_axmatplotlib.axes.AxesThe axis to which the table will be added.required
tablepandas.DataFrameThe table data to be displayed, with a 2-level MultiIndex column (parameter, value_type).required
sigintThe number of significant digits to round the table values to. Defaults to 3.3

Returns

NameTypeDescription
matplotlib.axes.AxesThe axis the table was added to.

extract_from_fit_results

fitting.AMARES.extract_from_fit_results(
    fit_results,
    bad_fit_chisqr_threshold=-1.0,
    ppm_offset=DEFAULT_INIT_PARAMS['ppm_offset'],
    index_key='voxel_id',
    index_values=None,
)

Extract goodness-of-fit metrics and combined fit parameters from batch fit results.

Parameters

NameTypeDescriptionDefault
fit_resultslist of tuplePer-voxel results as returned by fit_multiple_fids, each a (DataFrame, MinimizerResult) tuple.required
bad_fit_chisqr_thresholdfloatChi-squared threshold above which a fit is flagged as bad. If negative (default), it is set to 3x the median chi-squared.-1.0
ppm_offsetfloatOffset subtracted from the fitted chemical shift values. Defaults to DEFAULT_INIT_PARAMS["ppm_offset"].DEFAULT_INIT_PARAMS['ppm_offset']
index_keystrName used for the voxel index in the returned DataFrames. Defaults to “voxel_id”.'voxel_id'
index_valueslist or pandas.IndexValues to use for the voxel index. Must match the length of fit_results if provided. Defaults to a range index.None

Returns

NameTypeDescription
FitResultsThe bad fit ids, goodness-of-fit metrics, and combined fit results.

fit_multiple_fids

fitting.AMARES.fit_multiple_fids(
    fids,
    batch_fitting_params=None,
    init_params=None,
    batch_fitting_obj=None,
    raw_header=None,
)

Batch-fit multiple FIDs in parallel using the pyAMARES library.

Initializes a batch fitting object from the average FID of the highest SNR voxels, then applies parallel fitting to every input FID.

Parameters

NameTypeDescriptionDefault
fidsndarray or xarray.DataArrayThe input FIDs (time-domain signals) to be fitted. Expected shape is (n_signals, n_points).required
batch_fitting_paramsdictParameters for batch fitting, merged over DEFAULT_BATCH_FIT_PARAMS.None
init_paramsdictInitial parameters for fitting, merged over DEFAULT_INIT_PARAMS.None
batch_fitting_objoptionalA pre-initialized batch fitting object to reuse instead of creating a new one.None
raw_headerdictRaw header information passed to the initial single-FID fit.None

Returns

NameTypeDescription
list[tuple]The fitting results for each FID, each including the fitted parameters and other relevant information.

Notes

The batch fitting object is initialized using the average FID of the 10 highest-SNR voxels (or fewer if there are fewer than 10 FIDs). pyAMARES.run_parallel_fitting_with_progress performs the parallel fitting with a progress indicator.

fit_single_fid

fitting.AMARES.fit_single_fid(
    fid,
    init_params,
    fit_params=None,
    raw_header=None,
    filter_by_ppm=None,
)

Fit a single FID using the pyAMARES fitting library.

Parameters

NameTypeDescriptionDefault
fidndarray or xarray.DataArrayThe input FID (time-domain signal) to be fitted.required
init_paramsdictInitial parameters for fitting. Must include priorknowledgefile, MHz, sw, and deadtime (directly or via raw_header).required
fit_paramsdictFitting parameters, merged over DEFAULT_FIT_PARAMS.None
raw_headerdictRaw scanner header, used to derive MHz/sw/deadtime defaults.None
filter_by_ppmtuple[float, float]If given, restrict fitting to this ppm range.None

Returns

NameTypeDescription
pyAMARES fit resultThe fitted FID result object.

Raises

NameTypeDescription
ValueErrorIf a required field (priorknowledgefile, MHz, sw, deadtime) is missing from the merged init parameters.

load_extracted_results

fitting.AMARES.load_extracted_results(path)

Load extracted fitting results from an HDF5 file.

Parameters

NameTypeDescriptionDefault
pathstr or PathThe file path from which the results will be loaded.required

Returns

NameTypeDescription
tuple[FitResults, dict]The loaded fitting results, and a dictionary of user attributes stored alongside them.

Raises

NameTypeDescription
(FileNotFoundError, KeyError, OSError, ValueError)If reading the HDF5 file fails.

multiindex_to_priorknowledge

fitting.AMARES.multiindex_to_priorknowledge(pk_df, group_order=None)

Convert a MultiIndex prior-knowledge DataFrame back into a raw DataFrame.

Parameters

NameTypeDescriptionDefault
pk_dfpandas.DataFrameThe MultiIndex prior-knowledge DataFrame.required
group_orderlist of strSection headers to group and sort by. Defaults to ["Initial Values", "Bounds"].None

Returns

NameTypeDescription
pandas.DataFrameThe flattened, sorted DataFrame.

plot_amares_fitting

fitting.AMARES.plot_amares_fitting(
    result,
    title=None,
    fig_kwargs=None,
    ax_kwargs=None,
    autophase=DEFAULT_PLOT_PARAMS['ifphase'],
    add_table=False,
)

Plot an AMARES fitting result, optionally with a parameter table.

Parameters

NameTypeDescriptionDefault
resultpyAMARES fit resultThe result object containing the fitting parameters and data.required
titlestrThe title of the plot. Defaults to “AMARES Fitting Result”.None
fig_kwargsdictAdditional keyword arguments for plt.subplots.None
ax_kwargsdictAdditional keyword arguments applied to the main axes via ax.set.None
autophaseboolWhether to apply autophase to the data. Defaults to DEFAULT_PLOT_PARAMS["ifphase"].DEFAULT_PLOT_PARAMS['ifphase']
add_tableboolWhether to add a parameter table beneath the plot. Defaults to False.False

Returns

NameTypeDescription
matplotlib.figure.FigureThe combined figure.

priorknowledge_to_multiindex

fitting.AMARES.priorknowledge_to_multiindex(pk_df, sections=None)

Convert a prior-knowledge DataFrame into a MultiIndex DataFrame.

Parameters

NameTypeDescriptionDefault
pk_dfpandas.DataFrameThe prior-knowledge DataFrame.required
sectionslist of strSection headers to group by. Defaults to ["Initial Values", "Bounds"].None

Returns

NameTypeDescription
pandas.DataFrameThe DataFrame reindexed with a (Group, Index) MultiIndex.

save_extracted_results

fitting.AMARES.save_extracted_results(
    path,
    fit_results,
    attributes_to_add=None,
    additional_datasets=None,
    prepend_datetime=False,
    move_old=True,
)

Save the extracted fitting results to an HDF5 file.

Parameters

NameTypeDescriptionDefault
pathstr or PathThe file path where the results will be saved. Forced to a .h5 suffix if it doesn’t already end in .h5/.hdf5.required
fit_resultsFitResultsThe fitting results to save (badfit IDs, goodness-of-fit metrics, and combined fit results).required
attributes_to_adddict[str, str or int]Additional attributes to add to the HDF5 file.None
additional_datasetsdict[str, ndarray]Additional datasets to write into the HDF5 file.None
prepend_datetimeboolWhether to prepend the current datetime to the filename.False
move_oldboolWhether to move any existing file with the same stem into an “old” subfolder first. Defaults to True.True

Returns

NameTypeDescription
PathThe path to the saved file.

Raises

NameTypeDescription
FileExistsErrorIf the target path already exists (after any datetime prefix).
(OSError, KeyError, ValueError)If writing the HDF5 file fails.