FrameAveragedMultiTACTCMAnalysis#

class petpal.kinetic_modeling.tac_fitting.FrameAveragedMultiTACTCMAnalysis(input_tac_path: str, roi_tacs_dir: str, scan_info_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 = 4096)#

Bases: FrameAveragedTCMAnalysis, petpal.utils.time_activity_curve.MultiTACAnalysisMixin

A class for performing frame-averaged TCM analysis on multiple tissue TACs.

This class extends FrameAveragedTCMAnalysis to handle multiple ROI TACs simultaneously, fitting each to the same compartment model. It inherits functionality from both FrameAveragedTCMAnalysis and MultiTACAnalysisMixin, and produces both individual JSON files for each ROI and consolidated TSV tables summarizing all results.

Variables:
  • input_tac_path (str) – Path to the input TAC file.

  • roi_tacs_dir (str) – Directory containing multiple ROI TAC files.

  • scan_info_path (str) – Absolute path to scan timing information. Typically a JSON file with metadata from a NIfTI file. Can also be the path to a NIfTI file if the metadata have the same name as the NIfTI file, but the extension is json.

  • output_directory (str) – Directory for saving analysis results.

  • output_filename_prefix (str) – Prefix for output filenames.

  • compartment_model (str) – Name of the compartment model to use.

  • parameter_bounds (np.ndarray or None) – Bounds for the fitting parameters.

  • weights (float, np.ndarray, or None) – Weights for fitting.

  • resample_num (int) – Number of resampling points.

  • fit_results (list) – List of fit results for each TAC.

  • fit_tacs (list[TimeActivityCurve]) – List of fitted TAC curves for each ROI.

Example

import petpal.kinetic_modeling.tac_fitting as pet_fit

analysis = pet_fit.FrameAveragedMultiTACTCMAnalysis(
    input_tac_path='./input.tsv',
    roi_tacs_dir='./roi_tacs/',
    scan_info_path='./pet_image.nii.gz', # Assuming that './pet_image.json/' exists.
    output_directory='./results',
    output_filename_prefix='sub-0001_ses-01',
    compartment_model='serial-2tcm'
)

analysis()  # Run and save all results

See also

Initialize a FrameAveragedMultiTACTCMAnalysis instance.

Parameters:
  • input_tac_path (str) – Path to the input/plasma TAC file.

  • roi_tacs_dir (str) – Directory containing multiple ROI TAC files.

  • scan_info_path (str) – Path to scan timing information. Typically a JSON file with metadata from a NIfTI file. Can also be the path to a NIfTI file if the metadata have the same name as the NIfTI file, but the extension is json.

  • output_directory (str) – Directory for saving analysis results.

  • output_filename_prefix (str) – Prefix for output filenames. Typically something like ‘sub-XXXX_ses-XX’.

  • compartment_model (str) – Name of the compartment model.

  • parameter_bounds (np.ndarray or None, optional) – Parameter bounds. Defaults to None.

  • weights (float, np.ndarray, or None, optional) – Weights for fitting. Defaults to None.

  • resample_num (int, optional) – Number of resampling points. Defaults to 4096.

init_analysis_props() list[dict]#

Initialize analysis properties for each tissue TAC.

Creates a list of analysis property dictionaries, one for each TAC file found in the ROI TACs directory. Updates each dictionary with the appropriate file paths.

Returns:

list[dict] – A list of analysis property dictionaries for each TAC.

Side Effects:

Updates FilePathTTAC and FilePathImageOrMetadata for each properties dictionary.

calculate_fit()#

Calculate the fit for each TAC in the directory.

Loads the input TAC and scan timing once, then iterates through all ROI TAC files, fitting each one and storing results.

Side Effects:
  • Populates fit_results list with fit results for each TAC.

  • Populates fit_tacs list with fitted TAC curves.

  • Sets bounds if they were None initially.

calculate_fit_properties(pretty_params: bool = False)#

Calculate and format fit properties for all TACs.

Iterates through fit results and updates each ROI’s analysis properties dictionary with formatted fit values, standard errors, and bounds.

Parameters:

pretty_params (bool, optional) – If True, use LaTeX-formatted parameter names. Defaults to False.

Side Effects:

Updates each dictionary in analysis_props with formatted fit results.

save_analysis()#

Save all analysis results to files.

Saves three types of outputs:
  1. Individual JSON files for each ROI’s fit properties

  2. A consolidated TSV table with all TACs and fits

  3. A consolidated TSV table with all fit parameters

Side Effects:

Writes multiple files to the output directory.

_save_fit_props()#

Save individual JSON fit properties files for each ROI.

Creates a separate JSON file for each ROI containing its fit properties, with filenames including the ROI segment label.

Side Effects:

Writes multiple JSON files to the output directory, one per ROI.

_save_multitacs_table()#

Save a consolidated table of all TACs, fits, and residuals.

Creates a tab-separated values (TSV) file containing time points and, for each ROI: measured activity, uncertainty, fitted activity, and residuals.

Side Effects:

Writes a TSV file named with pattern: {prefix}_desc-{model}_multitacs.tsv

See also

  • TimeActivityCurve

_save_multifitprops_table()#

Save a consolidated table of all fit parameters.

Creates a tab-separated values (TSV) file containing fitted parameter values and standard errors for all ROIs in a long-format table.

The output table has columns: seg-name, param, value, stderr

Side Effects:

Writes a TSV file named with pattern: {prefix}_desc-{model}_multifitprops.tsv

See also

static validated_tcm_name(compartment_model: str) str#

Validate and normalize a tissue compartment model name.

Parameters:

compartment_model (str) – The compartment model name to validate.

Returns:

str – The normalized model name.

Raises:

ValueError – If the model name is not valid for frame-averaged models.

See also

static validated_tcm_function(compartment_model: str) Callable#

Get the TCM function corresponding to a model name.

Parameters:

compartment_model (str) – The compartment model name.

Returns:

Callable – The frame-averaged TCM function.

Raises:

ValueError – If the model name does not correspond to a known frame-averaged model.

See also

  • FrameAvgdTcmModelConfig.resolve_model_name()

__call__(pretty_params: bool = False)#

Execute the complete analysis workflow.

Convenience method that runs the analysis and saves results.

Parameters:

pretty_params (bool, optional) – If True, use LaTeX-formatted parameter names in output. Defaults to False.

Side Effects:

Runs the fit analysis and saves results to the output directory.

run_analysis(pretty_params: bool = False)#

Run the fitting analysis workflow.

Executes calculate_fit() and calculate_fit_properties(), then sets the analysis-has-been-run flag.

Parameters:

pretty_params (bool, optional) – If True, use LaTeX-formatted parameter names. Defaults to False.

Side Effects:
  • Populates fit_results with fitted parameters and covariances.

  • Updates analysis_props with formatted fit values.

  • Sets _has_analysis_been_run to True.

update_props_with_formatted_fit_values(fit_values: numpy.ndarray, fit_covars: numpy.ndarray, param_bounds: numpy.ndarray, fit_props_dict: dict, pretty_params: bool = False) None#

Update properties dictionary with formatted fit results.

Computes standard errors from covariances, formats parameter names (optionally with LaTeX), and updates the fit properties dictionary.

Parameters:
  • fit_values (np.ndarray) – Array of fitted parameter values.

  • fit_covars (np.ndarray) – Covariance matrix from the fit.

  • param_bounds (np.ndarray) – Parameter bounds array.

  • fit_props_dict (dict) – Dictionary to update with formatted results.

  • pretty_params (bool, optional) – If True, use LaTeX-formatted parameter names. Defaults to False.

Side Effects:

Updates the FitProperties section of fit_props_dict with FitValues, FitStdErr, and Bounds.

_generate_formatted_bounds(param_bounds: numpy.ndarray, pretty_params: bool = False) dict#

Format parameter bounds into a dictionary structure.

Parameters:
  • param_bounds (np.ndarray) – Parameter bounds array with shape (num_params, 3).

  • pretty_params (bool, optional) – If True, use LaTeX-formatted parameter names. Defaults to False.

Returns:

dict

Formatted bounds dictionary with structure:

{param_name: {‘initial’: val, ‘lo’: lo_bound, ‘hi’: hi_bound}}

property tacs_dir#

Gets the TAC directory path.

property reference_tac_path#

Gets the reference TAC file path.

is_valid_tacs_dir(tacs_dir: str)#

Validates the TAC directory by checking for TAC files.

Parameters:

tacs_dir (str) – Directory to validate.

Returns:

bool – True if valid, otherwise False.

static get_tacs_list_from_dir(tacs_dir: str) list[str]#

Retrieves a sorted list of TAC file paths from a directory.

Parameters:

tacs_dir (str) – Directory from which to retrieve TAC files.

Returns:

list[str] – Sorted list of TAC file paths.

static get_tacs_objects_dict_from_files_list(tacs_files_list: list[str])#

Creates a dict of TAC objects from a list of file paths.

Parameters:

tacs_files_list (list[str]) – List of TAC file paths.

Returns:

dict – Dictionary of region name-TAC object pairs.

static get_tacs_objects_dict_from_dir(tacs_dir: str) dict#

Creates a dict of TAC objects from a directory of TAC files.

Parameters:

tacs_dir (str) – A directory of TAC files.

Returns:

dict – Dictionary of region name-TAC object pairs.

static get_tacs_objects_list_from_files_list(tacs_files_list: list[str])#

Creates a list of TAC objects from a list of file paths.

Parameters:

tacs_files_list (list[str]) – List of TAC file paths.

Returns:

list[TimeActivityCurve] – List of TAC objects.

static get_tacs_vals_from_objs_list(tacs_objects_list: list[TimeActivityCurve])#

Extracts TAC values from a list of TAC objects.

Parameters:

tacs_objects_list (list[TimeActivityCurve]) – List of TAC objects.

Returns:

list – List of TAC values.

get_tacs_vals_from_dir(tacs_dir: str)#

Retrieves TAC values from files in a specified directory.

Parameters:

tacs_dir (str) – Directory containing TAC files.

Returns:

list – List of TAC values.

static capitalize_first_char_of_str(input_str: str)#

Capitalize only the first character of a string, leaving the remainder unchanged.

Parameters:

input_str (str) – The string to capitalize the first character of.

Returns:

output_str (str) – The string with only the first character capitalized.

static infer_segmentation_label_from_tac_path(tac_path: str, tac_id: int)#

Infers a segmentation label from a TAC file path by analyzing the filename.

This method extracts a segment label from the filename of a TAC file. It checks the presence of a seg- marker in the filename, which is followed by the segment name. This segment name is then formatted with each part capitalized. If no segment label is found, a default unknown label is generated using the TAC’s ID.

Parameters:
  • tac_path (str) – Path of the TAC file.

  • tac_id (int) – ID of the TAC.

Returns:

str – Inferred segmentation label.

infer_segmentation_labels_for_tacs()#

Infers segmentation labels for TACs.

Returns:

list[str] – List of inferred segmentation labels.