TCMAnalysis =============================================== .. py: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: Union[None, numpy.ndarray] = None, weights: Union[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: :py:obj:`object` A 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. .. rubric:: 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. .. code-block:: python 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() .. seealso:: * :class:`TACFitter` * :class:`TACFitterWithoutBloodVolume` Initializes an instance of the TCMAnalysis class. The initialization follows these steps: 1. Saves absolute paths of the TAC files and output directory. 2. Validates and stores the compartment model and the corresponding fitting function. 3. Stores the other fitting parameters passed as arguments. 4. Initializes the appropriate fitting object, depending on whether blood volume is considered or not. 5. Initializes the analysis properties structure. After initialization, you can directly run and save the analysis using bundled methods :meth:`run_analysis` and :meth:`save_analysis`, respectively. .. seealso:: * :meth:`validated_tcm` .. py:method:: 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. .. seealso:: * :meth:`calculate_fit_properties` .. py:method:: validated_tcm(compartment_model: str) -> str :staticmethod: Validates the type of tissue compartment model. Runs :meth:`~.ConvTcmModel.resolve_model_name` for validation, and returns the normalized string by running :meth:`~.ConvTcmModel.normalize_name`. :param compartment_model: The name of the compartment model. :type compartment_model: str :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'. .. py:method:: _get_tcm_function(compartment_model: str) -> Callable :staticmethod: Returns the corresponding function for the provided tissue compartment model used for the fitting class. Runs :meth:`~.ConvTcmModel.resolve_model_name` for validation, and returns the appropriate function. :param 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. .. seealso:: * :func:`gen_tac_1tcm_cpet_from_tac` * :func:`gen_tac_2tcm_with_k4zero_cpet_from_tac` * :func:`gen_tac_2tcm_cpet_from_tac` * :class:`~.TACFitter` .. py:method:: run_analysis() Runs the fitting analysis given the file-paths and method. :meth:`calculate_fit` and :meth:`calculate_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. .. py:method:: 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. .. py:method:: 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. :param fit_results: Tuple containing (fit_params, fit_covariances) from the fitting process. :type fit_results: tuple :param fit_props_dict: Dictionary to update with formatted fit values and errors. :type fit_props_dict: dict Side Effects: Updates the FitProperties section of fit_props_dict with formatted FitValues, FitStdErr, and Bounds. .. py:method:: 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. .. py:method:: 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: 1. Loads TAC files using the :func:`safe_load_tac` method, specific to the paths stored in instance variables. 2. Creates a fitting object with the relevant parameters and TACs. 3. Runs the fit using the fitting object's ``run_fit`` method. 4. Stores the results of the fit in the ``fit_results`` instance variable. As a result of this method, ``fit_results`` instance variable will hold the results of the fit, that can be used for further analysis or calculations. .. seealso:: * :class:`TACFitter` * :class:`TACFitterWithoutBloodVolume` .. py:method:: _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. :param results: The array of fitting results. :type results: np.ndarray :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'. .. py:method:: _generate_pretty_bounds(bounds: Union[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 :meth:`_generate_pretty_params` method. :param bounds: The array of parameter bounds. :type bounds: np.ndarray :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}} .. py:method:: __call__()