TCMAnalysis#
- class petpal.kinetic_modeling.tac_fitting.TCMAnalysis(input_tac_path: str, roi_tac_path: str, output_directory: str, output_filename_prefix: str, compartment_model: str, parameter_bounds: None | numpy.ndarray = None, weights: float | None | numpy.ndarray = None, resample_num: int = 512, aif_fit_thresh_in_mins: float = 40.0, max_func_iters: int = 2500, ignore_blood_volume: bool = False)#
Bases:
objectA class dedicated to perform Tissue Compartment Model (TCM) fitting to time-activity curves (TACs).
This class consolidates all related TAC fitting functionalities. It first initializes relevant fitting parameters and paths to TAC data from input arguments. After initialization, an analysis with methods like run_analysis() and save_analysis() can be performed. The results, including fit parameters and properties, can be accessed after the analysis.
Example
In the proceeding example, we assume that we have two tacs: an input function tac, and a region of interest (ROI) tac named ‘input_tac.txt’ and ‘roi_tac.txt’, respectively. Here, we are trying to fit the ROI tac to a standard serial 2TCM. Note that we are not fitting any time delay or dispersion corrections.
import petpal.kinetic_modeling.tac_fitting as pet_fit fit_obj = pet_fit.TCMAnalysis(input_tac_path='./input_tac.txt', roi_tac_path='./roi_tac.txt', output_directory='./', output_filename_prefix='fit', compartment_model='serial-2tcm', weights=None, parameter_bounds=np.asarray([[0.1, 0.0, 1.0], [0.1, 0.0, 1.0], [0.1, 0.0, 1.0], [0.1, 0.0, 1.0], [0.1, 0.0, 1.0]]), resample_num=512 ) fit_obj.run_analysis() fit_obj.save_analysis()
See also
TACFitterTACFitterWithoutBloodVolume
Initializes an instance of the TCMAnalysis class.
- The initialization follows these steps:
Saves absolute paths of the TAC files and output directory.
Validates and stores the compartment model and the corresponding fitting function.
Stores the other fitting parameters passed as arguments.
Initializes the appropriate fitting object, depending on whether blood volume is considered or not.
Initializes the analysis properties structure.
After initialization, you can directly run and save the analysis using bundled methods
run_analysis()andsave_analysis(), respectively.See also
- init_analysis_props()#
Initialize the structure of the analysis properties dictionary. This dictionary can be saved as a JSON file for parsing the results.
- The dictionary structure is as follows:
FilePathPTAC -> path of the input TAC file
FilePathTTAC -> path of the ROI TAC file
TissueCompartmentModel -> type of tissue compartment model used
IgnoreBloodVolume -> flag indicating whether blood volume is being considered or not
PTACFittingThresholdTime -> threshold time for the AIF fitting
FitProperties -> an inner dictionary with empty lists/arrays as placeholders for FitValues, FitStdErr and Bounds. Also contains ResampleNum and MaxIterations.
FitProperties will be updated during the analysis process.
- Returns:
dict – Initialized dictionary with analysis properties structure.
See also
- static validated_tcm(compartment_model: str) str#
Validates the type of tissue compartment model.
Runs
resolve_model_name()for validation, and returns the normalized string by runningnormalize_name().- Parameters:
compartment_model (str) – The name of the compartment model.
- Returns:
str – The transformed name of the validated compartment model if it was valid.
- Raises:
KeyError – If the provided compartment model is not one of ‘1tcm’, ‘2tcm-k4zero’, ‘serial-2tcm’ or ‘2tcm’.
- static _get_tcm_function(compartment_model: str) Callable#
Returns the corresponding function for the provided tissue compartment model used for the fitting class. Runs
resolve_model_name()for validation, and returns the appropriate function.- Parameters:
compartment_model – The name of the tissue compartment model.
- Returns:
function – The corresponding function for the tissue compartment model.
- Raises:
KeyError – If the provided tissue compartment model name does not correspond to any known models.
See also
gen_tac_1tcm_cpet_from_tacgen_tac_2tcm_with_k4zero_cpet_from_tacgen_tac_2tcm_cpet_from_tac
- run_analysis()#
Runs the fitting analysis given the file-paths and method.
calculate_fit()andcalculate_fit_properties()are run, and the analysis-has-been-fun flag is set to true.This method first calculates the fit, then updates the analysis properties with the fit results and finally sets the flag denoting that analysis has been successfully run.
- save_analysis()#
Saves the analysis properties to a json file in the prescribed output directory.
The saved filename is constructed as a combination of the output directory, filename prefix, “analysis”, and the used TissueCompartmentModel. If the analysis has not been run before calling this method, a RuntimeError is raised.
- Raises:
RuntimeError – If the method is called before the analysis has been run.
- update_props_with_formatted_fit_values(fit_results, fit_props_dict: dict)#
Update the analysis properties dictionary with formatted fit results.
Extracts fit parameters and standard errors from fit results, formats them using pretty parameter names, and updates the provided properties dictionary.
- Parameters:
fit_results (tuple) – Tuple containing (fit_params, fit_covariances) from the fitting process.
fit_props_dict (dict) – Dictionary to update with formatted fit values and errors.
- Side Effects:
Updates the FitProperties section of fit_props_dict with formatted FitValues, FitStdErr, and Bounds.
- calculate_fit_properties()#
Calculates the fit properties and updates the analysis properties.
This method retrieves the fitting parameters and their standard errors from the fitting results, formats them for readability, and stores them in the analysis properties dictionary. Bounds to the fitting parameters are also formatted and stored.
- calculate_fit()#
Performs the fit and stores results to the instance.
- This method has a series of actions which it performs in the following order:
Loads TAC files using the
safe_load_tac()method, specific to the paths stored in instance variables.Creates a fitting object with the relevant parameters and TACs.
Runs the fit using the fitting object’s
run_fitmethod.Stores the results of the fit in the
fit_resultsinstance variable.
As a result of this method,
fit_resultsinstance variable will hold the results of the fit, that can be used for further analysis or calculations.See also
TACFitterTACFitterWithoutBloodVolume
- _generate_pretty_params(results: numpy.ndarray) dict#
Transforms array of results into a formatted dictionary.
This method formats the fitting results into a more human-readable form. If the fitting was done without blood volume, it formats all values as ‘k_i’: value. Otherwise it formats all but the last as ‘k_i’: value and the last as ‘vb’: value.
- Parameters:
results (np.ndarray) – The array of fitting results.
- Returns:
dict –
- The formatted fitting results as {param: value} pairs. In the case of
TACFitterWithBloodVolume, the last parameter will be named ‘vb’, others ‘k_i’. In the case of TACFitterWithoutBloodVolume, parameters will be named ‘k_i’.
- _generate_pretty_bounds(bounds: numpy.ndarray | None) dict#
Transforms array of bounds into a formatted dictionary.
This method creates a dictionary of the fitting parameters and their corresponding initial values and lower and upper bounds. The keys of the dictionary are the names of the fitting parameters from
_generate_pretty_params()method.- Parameters:
bounds (np.ndarray) – The array of parameter bounds.
- Returns:
dict –
- The fitting parameters with their corresponding initial values, and lower and
upper bounds, in the following format: {param: {‘initial’: val, ‘lo’: lo, ‘hi’: hi}}
- __call__()#