FrameAveragedMultiTACTCMAnalysis ==================================================================== .. py: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: :py:obj:`FrameAveragedTCMAnalysis`, :py:obj:`petpal.utils.time_activity_curve.MultiTACAnalysisMixin` A class for performing frame-averaged TCM analysis on multiple tissue TACs. This class extends :class:`~.FrameAveragedTCMAnalysis` to handle multiple ROI TACs simultaneously, fitting each to the same compartment model. It inherits functionality from both :class:`~.FrameAveragedTCMAnalysis` and :class:`~.MultiTACAnalysisMixin`, and produces both individual JSON files for each ROI and consolidated TSV tables summarizing all results. :ivar input_tac_path: Path to the input TAC file. :vartype input_tac_path: str :ivar roi_tacs_dir: Directory containing multiple ROI TAC files. :vartype roi_tacs_dir: str :ivar scan_info_path: 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. :vartype scan_info_path: str :ivar output_directory: Directory for saving analysis results. :vartype output_directory: str :ivar output_filename_prefix: Prefix for output filenames. :vartype output_filename_prefix: str :ivar compartment_model: Name of the compartment model to use. :vartype compartment_model: str :ivar parameter_bounds: Bounds for the fitting parameters. :vartype parameter_bounds: np.ndarray or None :ivar weights: Weights for fitting. :vartype weights: float, np.ndarray, or None :ivar resample_num: Number of resampling points. :vartype resample_num: int :ivar fit_results: List of fit results for each TAC. :vartype fit_results: list :ivar fit_tacs: List of fitted TAC curves for each ROI. :vartype fit_tacs: list[TimeActivityCurve] .. rubric:: Example .. code-block:: python 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 .. seealso:: * :class:`~.FrameAveragedTCMAnalysis` * :class:`~.MultiTACAnalysisMixin` * :class:`~.MultiTACTCMAnalysis` for non-frame-averaged multi-TAC analysis Initialize a FrameAveragedMultiTACTCMAnalysis instance. :param input_tac_path: Path to the input/plasma TAC file. :type input_tac_path: str :param roi_tacs_dir: Directory containing multiple ROI TAC files. :type roi_tacs_dir: str :param scan_info_path: 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. :type scan_info_path: str :param output_directory: Directory for saving analysis results. :type output_directory: str :param output_filename_prefix: Prefix for output filenames. Typically something like 'sub-XXXX_ses-XX'. :type output_filename_prefix: str :param compartment_model: Name of the compartment model. :type compartment_model: str :param parameter_bounds: Parameter bounds. Defaults to None. :type parameter_bounds: np.ndarray or None, optional :param weights: Weights for fitting. Defaults to None. :type weights: float, np.ndarray, or None, optional :param resample_num: Number of resampling points. Defaults to 4096. :type resample_num: int, optional .. py:method:: 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. .. py:method:: 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. .. seealso:: * :class:`~.FrameAveragedTACFitter` .. py:method:: 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. :param pretty_params: If True, use LaTeX-formatted parameter names. Defaults to False. :type pretty_params: bool, optional Side Effects: Updates each dictionary in analysis_props with formatted fit results. .. py:method:: 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. .. seealso:: * :meth:`_save_fit_props` * :meth:`_save_multitacs_table` * :meth:`_save_multifitprops_table` .. py:method:: _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. .. py:method:: _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 .. seealso:: * :class:`TimeActivityCurve` .. py:method:: _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 .. seealso:: * :mod:`pandas` .. py:method:: validated_tcm_name(compartment_model: str) -> str :staticmethod: Validate and normalize a tissue compartment model name. :param compartment_model: The compartment model name to validate. :type compartment_model: str :returns: *str* -- The normalized model name. :raises ValueError: If the model name is not valid for frame-averaged models. .. seealso:: * :meth:`~.FrameAvgdTcmModelConfig.normalize_name` .. py:method:: validated_tcm_function(compartment_model: str) -> Callable :staticmethod: Get the TCM function corresponding to a model name. :param compartment_model: The compartment model name. :type compartment_model: str :returns: *Callable* -- The frame-averaged TCM function. :raises ValueError: If the model name does not correspond to a known frame-averaged model. .. seealso:: * :meth:`FrameAvgdTcmModelConfig.resolve_model_name` .. py:method:: __call__(pretty_params: bool = False) Execute the complete analysis workflow. Convenience method that runs the analysis and saves results. :param pretty_params: If True, use LaTeX-formatted parameter names in output. Defaults to False. :type pretty_params: bool, optional Side Effects: Runs the fit analysis and saves results to the output directory. .. seealso:: * :meth:`run_analysis` * :meth:`save_analysis` .. py:method:: run_analysis(pretty_params: bool = False) Run the fitting analysis workflow. Executes :meth:`calculate_fit` and :meth:`calculate_fit_properties`, then sets the analysis-has-been-run flag. :param pretty_params: If True, use LaTeX-formatted parameter names. Defaults to False. :type pretty_params: bool, optional Side Effects: - Populates fit_results with fitted parameters and covariances. - Updates analysis_props with formatted fit values. - Sets _has_analysis_been_run to True. .. py:method:: 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. :param fit_values: Array of fitted parameter values. :type fit_values: np.ndarray :param fit_covars: Covariance matrix from the fit. :type fit_covars: np.ndarray :param param_bounds: Parameter bounds array. :type param_bounds: np.ndarray :param fit_props_dict: Dictionary to update with formatted results. :type fit_props_dict: dict :param pretty_params: If True, use LaTeX-formatted parameter names. Defaults to False. :type pretty_params: bool, optional Side Effects: Updates the FitProperties section of fit_props_dict with FitValues, FitStdErr, and Bounds. .. py:method:: _generate_formatted_bounds(param_bounds: numpy.ndarray, pretty_params: bool = False) -> dict Format parameter bounds into a dictionary structure. :param param_bounds: Parameter bounds array with shape (num_params, 3). :type param_bounds: np.ndarray :param pretty_params: If True, use LaTeX-formatted parameter names. Defaults to False. :type pretty_params: bool, optional :returns: *dict* -- Formatted bounds dictionary with structure: {param_name: {'initial': val, 'lo': lo_bound, 'hi': hi_bound}} .. py:property:: tacs_dir Gets the TAC directory path. .. py:property:: reference_tac_path Gets the reference TAC file path. .. py:method:: is_valid_tacs_dir(tacs_dir: str) Validates the TAC directory by checking for TAC files. :param tacs_dir: Directory to validate. :type tacs_dir: str :returns: *bool* -- True if valid, otherwise False. .. py:method:: get_tacs_list_from_dir(tacs_dir: str) -> list[str] :staticmethod: Retrieves a sorted list of TAC file paths from a directory. :param tacs_dir: Directory from which to retrieve TAC files. :type tacs_dir: str :returns: *list[str]* -- Sorted list of TAC file paths. .. py:method:: get_tacs_objects_dict_from_files_list(tacs_files_list: list[str]) :staticmethod: Creates a dict of TAC objects from a list of file paths. :param tacs_files_list: List of TAC file paths. :type tacs_files_list: list[str] :returns: *dict* -- Dictionary of region name-TAC object pairs. .. py:method:: get_tacs_objects_dict_from_dir(tacs_dir: str) -> dict :staticmethod: Creates a dict of TAC objects from a directory of TAC files. :param tacs_dir: A directory of TAC files. :type tacs_dir: str :returns: *dict* -- Dictionary of region name-TAC object pairs. .. py:method:: get_tacs_objects_list_from_files_list(tacs_files_list: list[str]) :staticmethod: Creates a list of TAC objects from a list of file paths. :param tacs_files_list: List of TAC file paths. :type tacs_files_list: list[str] :returns: *list[TimeActivityCurve]* -- List of TAC objects. .. py:method:: get_tacs_vals_from_objs_list(tacs_objects_list: list[TimeActivityCurve]) :staticmethod: Extracts TAC values from a list of TAC objects. :param tacs_objects_list: List of TAC objects. :type tacs_objects_list: list[TimeActivityCurve] :returns: *list* -- List of TAC values. .. py:method:: get_tacs_vals_from_dir(tacs_dir: str) Retrieves TAC values from files in a specified directory. :param tacs_dir: Directory containing TAC files. :type tacs_dir: str :returns: *list* -- List of TAC values. .. py:method:: capitalize_first_char_of_str(input_str: str) :staticmethod: Capitalize only the first character of a string, leaving the remainder unchanged. :param input_str: The string to capitalize the first character of. :type input_str: str :returns: *output_str (str)* -- The string with only the first character capitalized. .. py:method:: infer_segmentation_label_from_tac_path(tac_path: str, tac_id: int) :staticmethod: 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. :param tac_path: Path of the TAC file. :type tac_path: str :param tac_id: ID of the TAC. :type tac_id: int :returns: *str* -- Inferred segmentation label. .. py:method:: infer_segmentation_labels_for_tacs() Infers segmentation labels for TACs. :returns: *list[str]* -- List of inferred segmentation labels. .. seealso:: :meth:`infer_segmentation_label_from_tac_path`