### Forward Projection Logic (Example) Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Demonstrates the forward projection process for the Example Scanner. It involves summing the object along specific axes (x for 0 degrees, y for 90 degrees) and applying the detector's sensitivity factor. ```python sample_object = torch.rand(object_meta.shape) # Sum object along x to get projection at 0 degrees sample_projection_0degrees = sample_object.sum(dim=0) * proj_meta.sensitivity_factor # Sum object along y to get projection at 90 degrees sample_projection_90degrees = sample_object.sum(dim=1) * proj_meta.sensitivity_factor # Concatenate to get the full set of projections sample_projections = torch.stack([sample_projection_0degrees, sample_projection_90degrees], dim=0) sample_projections.shape ``` -------------------------------- ### EXSSystemMatrix Usage Example Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Instantiates the EXSSystemMatrix and demonstrates forward and backward projections for subsets. ```python system_matrix = EXSSystemMatrix(object_meta=object_meta, proj_meta=proj_meta) FP_subset0 = system_matrix.forward(sample_object, subset_idx=0) FP_subset1 = system_matrix.forward(sample_object, subset_idx=1) BP_subset0 = system_matrix.backward(FP_subset0, subset_idx=0) BP_subset1 = system_matrix.backward(FP_subset0, subset_idx=1) ``` -------------------------------- ### Open Multiple Simind Regions / Energy Windows Source: https://github.com/qurit/pytomography/blob/main/docs/source/usage/usage_spect.rst Use this example to open multiple simind regions or energy windows simultaneously. Ensure the notebook path is correct. ```python from pytomography.utils.simind import Simind from pytomography.utils.math import gaussian_1d import numpy as np # Define parameters for the first region region1_params = { "name": "region1", "shape": "gaussian", "center": [0, 0], "width": 5, "amplitude": 100, "background": 10 } # Define parameters for the second region region2_params = { "name": "region2", "shape": "gaussian", "center": [10, 10], "width": 3, "amplitude": 50, "background": 5 } # Define energy windows energy_windows = { "window1": [50, 70], "window2": [80, 100] } # Create a Simind object with multiple regions and energy windows simind_obj = Simind([region1_params, region2_params], energy_windows) # Generate projection data for the first energy window proj_data1 = simind_obj.generate_projections(energy_window="window1") # Generate projection data for the second energy window proj_data2 = simind_obj.generate_projections(energy_window="window2") # You can also generate data for all energy windows at once all_proj_data = simind_obj.generate_projections() print("Projection data for window1 shape:", proj_data1.shape) print("Projection data for window2 shape:", proj_data2.shape) print("Projection data for all windows shape:", all_proj_data.shape) ``` -------------------------------- ### Install PyTomography via Pip Source: https://github.com/qurit/pytomography/blob/main/docs/source/install.rst After activating your conda environment, install the PyTomography package using pip. ```bash pip install pytomography ``` -------------------------------- ### Setup PET Listmode Reconstruction System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_scat_lmTOF.ipynb Configures the object and projection space metadata, loads the attenuation map and PSF transform, and creates the PET listmode system matrix. This setup is crucial for accurate reconstruction, especially when including attenuation and blurring. ```python # Specify object space for reconstruction object_meta = ObjectMeta( dr=(2,2,2), #mm shape=(128,128,96) #voxels ) # Get projection space metadata from PET geometry information dictionary proj_meta = PETLMProjMeta( detector_ids, info, tof_meta=tof_meta, weights_sensitivity=normalization_weights ) # Get attenuation map and PSF transform from the associated phantom atten_map = gate.get_aligned_attenuation_map(os.path.join(path, 'gate_simulation/simple_phantom/umap_mMR_brainSimplePhantom.hv'), object_meta).to(pytomography.device) psf_transform = GaussianFilter(3.) # 4mm gaussian blurring # Create system matrix. system_matrix = PETLMSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [psf_transform], attenuation_map = atten_map, N_splits=8, ) # Create likelihood. For listmode reconstruction, projections don't need to be provided, since all detection events are stored in proj_meta likelihood = PoissonLogLikelihood( system_matrix, ) # Initialize reconstruction algorithm recon_algorithm = OSEM(likelihood) # Reconstruct recon_primaryonly = recon_algorithm(n_iters=4, n_subsets=14) ``` -------------------------------- ### Setup Likelihood and Reconstruction Algorithm Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Creates a NegativeMSELikelihood function using the system matrix and sample projections, then initializes an OSEM reconstruction algorithm. This prepares for the iterative reconstruction process. ```python system_matrix = EXSSystemMatrix(object_meta=object_meta, proj_meta=proj_meta) likelihood = NegativeMSELikelihood(system_matrix, projections=sample_projections, scaling_constant=0.01) reconstruction_algorithm = OSEM(likelihood) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_DIP.ipynb Imports all required libraries for PET data processing, reconstruction, and visualization. Ensure 'monai' is installed. ```python import torch import torch.nn as nn from torch.optim import LBFGS import pytomography from pytomography.metadata import ObjectMeta from pytomography.metadata.PET import PETLMProjMeta, PETTOFMeta from pytomography.projectors.PET import PETLMSystemMatrix from pytomography.algorithms import OSEM, DIPRecon from pytomography.io.PET import gate from pytomography.likelihoods import PoissonLogLikelihood from pytomography.transforms.shared import GaussianFilter from pytomography.utils import sss import matplotlib.pyplot as plt import gc import os import numpy as np import numpy as np from monai.transforms import ScaleIntensityd, CropForeground, Compose, DivisiblePadd, SpatialCropd, ThresholdIntensityd ``` -------------------------------- ### Import Libraries for PyTomography Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_CardiacReorientation.ipynb Imports essential libraries for SPECT image processing, reconstruction, and visualization. Ensure all listed libraries are installed. ```python import os from pytomography.io.SPECT import dicom from pytomography.transforms.SPECT import SPECTPSFTransform from pytomography.algorithms import OSEM from pytomography.projectors.SPECT import SPECTSystemMatrix from pytomography.likelihoods import PoissonLogLikelihood import pytomography import matplotlib.pyplot as plt import torch ``` -------------------------------- ### Setup Data Storage Callback for Uncertainty Calculation Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_uncertainty_spect.ipynb Creates a DataStorageCallback to store intermediate reconstruction results. This is essential for calculating uncertainties in specific regions later. ```python data_storage_callback = DataStorageCallback(likelihood, torch.clone(recon_algorithm.object_prediction)) ``` -------------------------------- ### Import necessary libraries for SPECT reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_spect_mc.ipynb Imports all required modules from pytomography and other libraries for SPECT reconstruction tasks. Ensure pytomography and its dependencies are installed. ```python import os import torch from pytomography.io.SPECT import simind from pytomography.projectors.SPECT import SPECTSystemMatrix, MonteCarloHybridSPECTSystemMatrix from pytomography.transforms.SPECT import SPECTAttenuationTransform, SPECTPSFTransform from pytomography.algorithms import OSEM from pytomography.likelihoods import PoissonLogLikelihood, MonteCarloHybridSPECTPoissonLogLikelihood from pytomography.utils import simind_mc import matplotlib.pyplot as plt ``` -------------------------------- ### Import necessary PyTomography modules Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Imports core PyTomography classes for algorithms, metadata, projectors, and likelihoods, along with matplotlib for plotting and torch for tensor operations. Ensure PyTomography is installed. ```python import pytomography from pytomography.algorithms import OSEM, MLEM from pytomography.metadata import ObjectMeta, ProjMeta from pytomography.projectors import SystemMatrix from pytomography.likelihoods import NegativeMSELikelihood import matplotlib.pyplot as plt import torch ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_quantitative.ipynb Imports all required libraries for data manipulation, image processing, and reconstruction. Ensure these are installed before running. ```python import os import torch import numpy as np from skimage.transform import resize import matplotlib.pyplot as plt from pytomography.algorithms import OSEM from pytomography.transforms.SPECT import SPECTAttenuationTransform, SPECTPSFTransform from pytomography.projectors.SPECT import SPECTSystemMatrix from pytomography.callbacks import Callback from pytomography.io.SPECT import simind ``` -------------------------------- ### Initialize TOF Metadata Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_LM.ipynb Sets up metadata for Time-of-Flight (TOF) reconstruction, including the number of TOF bins, TOF range, and the full width at half maximum (FWHM) of the TOF resolution. This is a one-time setup. ```python speed_of_light = 0.3 #mm/ps fwhm_tof_resolution = 550 * speed_of_light / 2 #ps to position along LOR TOF_range = 1000 * speed_of_light #ps to position along LOR (full range) num_tof_bins = 5 tof_meta = PETTOFMeta(num_tof_bins, TOF_range, fwhm_tof_resolution, n_sigmas=3) ``` -------------------------------- ### Setup Analytical Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_spect_mc.ipynb Configures the system matrix and likelihood function for analytical SPECT reconstruction. This involves defining transformations, metadata, and the noise model. ```python system_matrix = SPECTSystemMatrix( obj2obj_transforms=[att_transform, psf_transform], proj2proj_transforms=[], object_meta=object_meta, proj_meta=proj_meta, ) likelihood = PoissonLogLikelihood(system_matrix, photopeak, additive_TEW) algorithm = OSEM(likelihood) recon_analytical = algorithm(n_iters=1, n_subsets=16) ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/qurit/pytomography/blob/main/docs/source/index2.md Creates a new conda environment named 'pytomography_env' with Python 3.11 and activates it. This is the first step for installing PyTomography. ```bash conda create --name pytomography_env -c conda-forge python=3.11 ``` ```bash conda activate pytomography_env ``` -------------------------------- ### SPECT DICOM Data Loading and Inspection Source: https://context7.com/qurit/pytomography/llms.txt Example demonstrating loading SPECT DICOM data, inspecting energy windows, and retrieving metadata and projections for reconstruction. ```python import glob import pytomography from pytomography.io.SPECT.dicom import ( get_metadata, get_projections, get_attenuation_map_from_CT_slices, get_energy_window_scatter_estimate, get_psfmeta_from_scanner_params, save_dcm, print_energy_window_info ) from pytomography.transforms.SPECT import SPECTAttenuationTransform, SPECTPSFTransform from pytomography.projectors.SPECT import SPECTSystemMatrix from pytomography.likelihoods import PoissonLogLikelihood from pytomography.algorithms import OSEM file_NM = "/data/patient01/spect.dcm" files_CT = sorted(glob.glob("/data/patient01/ct/*.dcm")) # 1. Inspect energy windows to find peak and scatter indices print_energy_window_info(file_NM) # Index 0: Lower Scatter [113,129 keV] # Index 1: Photopeak [129,154 keV] # Index 2: Upper Scatter [154,171 keV] # 2. Load metadata and projections object_meta, proj_meta = get_metadata(file_NM, index_peak=1) projections = get_projections(file_NM, index_peak=1) ``` -------------------------------- ### Back Projection Logic (Example) Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Illustrates the back projection process. It involves adjusting the projections by the sensitivity factor and then duplicating them along the appropriate object axes (z for angle 0, z for angle 90) before summing. ```python # First adjust projections by sensitivity factor sample_projections_angle_0_sensitivity_adjusted = sample_projections[0]*proj_meta.sensitivity_factor # Back project at angle 0 by duplication sample_object_BP_angle0 = sample_projections_angle_0_sensitivity_adjusted.unsqueeze(0).repeat(object_meta.shape[0],1,1) # Back project at angle 90 by duplication sample_projections_angle_90_sensitivity_adjusted = sample_projections[1]*proj_meta.sensitivity_factor sample_object_BP_angle90 = sample_projections_angle_90_sensitivity_adjusted.unsqueeze(1).repeat(1,object_meta.shape[0],1) # Back projected object is sum of each sample_object_BP = sample_object_BP_angle0 + sample_object_BP_angle90 ``` -------------------------------- ### PET Listmode Reconstruction Setup and Execution Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_scat_lm.ipynb Sets up the system matrix and likelihood for PET listmode reconstruction, incorporating object and projection metadata, attenuation maps, and PSF transforms. It then initializes and runs the OSEM algorithm to reconstruct the image from primary events. ```python # Specify object space for reconstruction # Specify object space for reconstruction object_meta = ObjectMeta( dr=(2,2,2), #mm shape=(128,128,96) #voxels ) # Get projection space metadata from PET geometry information dictionary proj_meta = PETLMProjMeta( detector_ids = detector_ids, # list of all detected event detector ID pairs info = info, weights_sensitivity=normalization_weights ) # Get attenuation map and PSF transform from the associated phantom atten_map = gate.get_aligned_attenuation_map(os.path.join(path, 'gate_simulation/simple_phantom/umap_mMR_brainSimplePhantom.hv'), object_meta).to(pytomography.device) psf_transform = GaussianFilter(3.) # 3mm gaussian blurring # Create system matrix system_matrix = PETLMSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [psf_transform], attenuation_map = atten_map, N_splits=8, ) # Create likelihood. For listmode reconstruction, projections don't need to be provided, since all detection events are stored in proj_meta likelihood = PoissonLogLikelihood( system_matrix ) # Initialize reconstruction algorithm recon_algorithm = OSEM(likelihood) # Reconstruct recon_primaryonly = recon_algorithm(n_iters=4, n_subsets=14) ``` -------------------------------- ### Setup PET System Matrix for Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_scat_sinoTOF.ipynb Configures the PET system matrix with object and projection metadata, including attenuation maps and PSF transforms. Use this for setting up the reconstruction pipeline. ```python object_meta = ObjectMeta( dr=(2,2,2), #mm shape=(128,128,96) #voxels ) # Get projection space metadata from PET geometry information dictionary and TOF metadata proj_meta = PETSinogramPolygonProjMeta(info, tof_meta=tof_meta) # Get attenuation map and PSF transform from the associated phantom atten_map = gate.get_aligned_attenuation_map(os.path.join(path, 'gate_simulation/simple_phantom/umap_mMR_brainSimplePhantom.hv'), object_meta).to(pytomography.device) psf_transform = GaussianFilter(3.) # 2mm gaussian blurring # Create system matrix. system_matrix = PETSinogramSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [psf_transform], sinogram_sensitivity = normalization_sinogram, N_splits=10, attenuation_map=atten_map, device='cpu' # projections output on cpu, computation is still on GPU ) # Create likelihood likelihood = PoissonLogLikelihood( system_matrix, sinogram, ) # Reconstruct recon_algorithm = OSEM(likelihood) recon_primaryonly = recon_algorithm(n_iters=4, n_subsets=14) # delete to save memory del(sinogram) del(system_matrix) del(likelihood) del(recon_algorithm) gc.collect() ``` -------------------------------- ### Setup projection metadata for non-TOF and TOF Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETSIRD.ipynb Initializes PETLMProjMeta objects for both non-TOF and TOF reconstruction. The non-TOF version uses only the first two detector ID indices, while the TOF version includes the TOF bin information. ```python weights_sensitivity = torch.tensor(np.load(eta_path)) proj_meta_nonTOF = PETLMProjMeta( detector_ids=detector_ids[:,:2], scanner_LUT=scanner_LUT, weights_sensitivity=weights_sensitivity) proj_meta_TOF = PETLMProjMeta( detector_ids=detector_ids, scanner_LUT=scanner_LUT, tof_meta=tof_meta, weights_sensitivity=weights_sensitivity) ``` -------------------------------- ### SPECT System Matrix Setup Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_quantitative.ipynb Configures the SPECT system matrix by defining attenuation and point spread function transforms. Ensure the correct paths for attenuation maps and header files are provided. ```python attenuation_map = simind.get_attenuation_map(os.path.join(path, 'multi_projections', 'mu208.hct')) att_transform = SPECTAttenuationTransform(attenuation_map) psf_meta = simind.get_psfmeta_from_header(headerfiles[0]) psf_transform = SPECTPSFTransform(psf_meta) system_matrix = SPECTSystemMatrix( obj2obj_transforms = [att_transform,psf_transform], proj2proj_transforms = [], object_meta = object_meta, proj_meta = proj_meta) ``` -------------------------------- ### Import Core Libraries for PET Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_LM.ipynb Imports all necessary libraries from pytomography and other common Python packages for PET reconstruction tasks. Ensure these libraries are installed before running. ```python import torch import os import pytomography from pytomography.metadata import ObjectMeta from pytomography.metadata.PET import PETLMProjMeta, PETTOFMeta from pytomography.projectors.PET import PETLMSystemMatrix from pytomography.algorithms import OSEM from pytomography.io.PET import gate from pytomography.likelihoods import PoissonLogLikelihood import os from pytomography.transforms.shared import GaussianFilter import numpy as np import nibabel as nib import matplotlib.pyplot as plt ``` -------------------------------- ### Setup Likelihood and Prior for BSREM Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETSIRD.ipynb Sets up PoissonLogLikelihood for both TOF and non-TOF system matrices and initializes a RelativeDifferencePrior. The `projections` argument for PET LM data must be a tensor containing only the element 1. ```python likelihood_tof = PoissonLogLikelihood(system_matrix_tof, torch.tensor([1.]).to(pytomography.device)) likelihood_nontof = PoissonLogLikelihood(system_matrix_nontof, torch.tensor([1.]).to(pytomography.device)) prior_rdp = RelativeDifferencePrior(beta=75, gamma=2) recon_algorithm_nontof = BSREM( likelihood_nontof, prior=prior_rdp, ) recon_algorithm_tof = BSREM( likelihood_tof, prior=prior_rdp, ) ``` -------------------------------- ### Initialize StarGuide System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_starguide.ipynb Constructs the system matrix for the StarGuide system, incorporating attenuation and PSF transforms. ```python system_matrix = StarGuideSystemMatrix( object_meta=object_meta, proj_meta=proj_meta, obj2obj_transforms=[attenuation_transform, psf_transform], proj2proj_transforms=[] ) ``` -------------------------------- ### Set up Reconstruction Algorithm Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Initialize the system matrix, define a likelihood function (e.g., `NegativeMSELikelihood`), and set up a reconstruction algorithm like MLEM. ```python # Define system matrix system_matrix = EXSSystemMatrix(object_meta=object_meta, proj_meta=proj_meta) # Define likelihood that characterizes measured data (for SPECT/PET, this is PoissonLog, but here we'll use NegativeMSE) likelihood = NegativeMSELikelihood(system_matrix, projections=sample_projections, scaling_constant=0.01) # Define reconstruction_algorithm = MLEM(likelihood) ``` -------------------------------- ### Install Parallelproj and CuPy for PET/CT Source: https://github.com/qurit/pytomography/blob/main/docs/source/install.rst To enable PET/CT reconstruction, activate your environment and install the 'parallelproj' library along with 'libparallelproj' and 'cupy' from conda-forge. CuPy is required for GPU operations. ```bash conda activate pytomography_env conda install -c conda-forge libparallelproj parallelproj cupy ``` -------------------------------- ### Set path to tutorial data Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_spect_mc.ipynb Specifies the directory where the tutorial data is stored. Update this path to match your system's configuration. ```python # change this to where the tutorial data is saved PATH = '/ac225listmode/pytomography_tutorial_data/SPECT/SIMIND-Jaszak' ``` -------------------------------- ### Get Projection Data Shape Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_siminddata.ipynb Prints the shape of the loaded projection data tensor. ```python photopeak.shape ``` -------------------------------- ### Instantiate and Use System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Create an instance of the custom `EXSSystemMatrix` and perform forward and backward projections using sample data. ```python system_matrix = EXSSystemMatrix(object_meta=object_meta, proj_meta=proj_meta) FP = system_matrix.forward(sample_object) BP = system_matrix.forward(sample_object) ``` -------------------------------- ### Set save path for tutorial data Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_plotting.ipynb Specifies the directory where the tutorial data is stored. Ensure this path is correct for your system. ```python save_path = '/disk1/pytomography_tutorial_data' ``` -------------------------------- ### Import Libraries for SPECT Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_ac225_dicom_recon.ipynb Imports necessary libraries for SPECT data processing, reconstruction, and visualization. Ensure SPECTPSFToolbox is installed. ```python import matplotlib.pyplot as plt import torch # needed for kernels import pytomography from pytomography.projectors.SPECT import SPECTSystemMatrix from pytomography.io.SPECT import dicom from pytomography.algorithms import OSEM from pytomography.likelihoods import PoissonLogLikelihood from pytomography.transforms.SPECT import SPECTAttenuationTransform, SPECTPSFTransform from pytomography.transforms.shared import GaussianFilter from pytomography.io.SPECT.shared import subsample_projections_and_modify_metadata import dill import os from pytomography.utils import plot_utils ``` -------------------------------- ### Set data path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_algorithms.ipynb Define the base path where the tutorial data is stored. Ensure this path is updated to reflect your local directory structure. ```python # CHANGE THIS TO WHERE YOU DOWNLOADED THE TUTORIAL DATA PATH = '/mnt/mydisk2/pytomo_tutorial_data/SPECT' ``` -------------------------------- ### Set data save path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicommultibed.ipynb Specifies the directory where the tutorial data is saved. Ensure this path is updated to your local download location. ```python # change this to where you downloaded the data save_path = '/mnt/mydisk2/pytomo_tutorial_data/SPECT' ``` -------------------------------- ### Get PET scanner geometry information Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_GE_HDF5.ipynb Retrieves the detector geometry information for a specified scanner name. Currently supports 'discovery_MI'. ```python scanner_name = 'discovery_MI' info = clinical.get_detector_info(scanner_name) ``` -------------------------------- ### Resample Projection Data Before Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/usage/usage_spect.rst This example demonstrates how to resample projection data before performing reconstruction. It's useful for adjusting data resolution. ```python from pytomography.utils.sampling import subsample_projections import numpy as np # Assume you have some projection data (e.g., a numpy array) # For demonstration, let's create a dummy projection data array num_projections = 100 num_views = 180 projection_data = np.random.rand(num_projections, num_views) # Define the new number of projections and views new_num_projections = 50 new_num_views = 90 # Resample the projection data resampled_data = subsample_projections(projection_data, new_num_projections, new_num_views) print("Original projection data shape:", projection_data.shape) print("Resampled projection data shape:", resampled_data.shape) ``` -------------------------------- ### Initialize SPECT System Matrix and Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_CardiacReorientation.ipynb Sets up the system matrix with PSF transforms and initializes the OSEM reconstruction algorithm. Requires scanner parameters and projection metadata. ```python psf_meta = dicom.get_psfmeta_from_scanner_params('SY-LEHR', energy_keV=140.5) psf_transform = SPECTPSFTransform(psf_meta) system_matrix = SPECTSystemMatrix( obj2obj_transforms = [psf_transform], proj2proj_transforms = [], object_meta = object_meta, proj_meta = proj_meta) likelihood = PoissonLogLikelihood(system_matrix, photopeak) reconstruction_algorithm = OSEM(likelihood) recon = reconstruction_algorithm(n_iters=4, n_subsets=8) ``` -------------------------------- ### Initialize Reconstruction System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_scat_lm.ipynb Sets up the system matrix for reconstruction, including attenuation map, normalization weights, and PSF transform. This is a prerequisite for scatter estimation. ```python atten_map = gate.get_aligned_attenuation_map(os.path.join(path, 'gate_simulation/simple_phantom/umap_mMR_brainSimplePhantom.hv'), object_meta).to(pytomography.device) normalization_weights = torch.load(os.path.join(path, 'normalization_weights.pt')) proj_meta = PETLMProjMeta( detector_ids[:,:2], info, weights_sensitivity=normalization_weights ) psf_transform = GaussianFilter(3.) system_matrix = PETLMSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [psf_transform], N_splits=10, attenuation_map=atten_map.to(pytomography.device), ) ``` -------------------------------- ### Retrieve Locations for Multiple Detector IDs Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Shows how to efficiently get the spatial coordinates for a subset of detector IDs, such as the first few measured events. ```python scanner_LUT[detector_ids[0:5]] ``` -------------------------------- ### Get SPECT PSF Metadata Source: https://context7.com/qurit/pytomography/llms.txt Creates an SPECTPSFMeta object from collimator parameters and radionuclide energy. Collimator parameters are retrieved from a bundled database. ```python from pytomography.io.SPECT.dicom import get_psfmeta_from_scanner_params psf_meta = get_psfmeta_from_scanner_params( collimator_name="MEGP", # medium energy general purpose energy_keV=208.0, # Lu-177 photopeak min_sigmas=3, material="lead", intrinsic_resolution_140keV=3.8, # mm FWHM at 140 keV ) print(psf_meta.sigma_fit_params) # [slope, intercept, intrinsic_sigma] ``` -------------------------------- ### Initialize Dual Peak System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dualpeak.ipynb Create a system matrix that combines multiple energy peaks by scaling individual system matrices with their respective calibration factors. ```python calib208 = 10.2419 # CPS/MBq calib113 = 11.3 # CPS/MBq system_matrix = ExtendedSystemMatrix( system_matrices= [ calib113*system_matrix113, calib208*system_matrix208 ] ) ``` -------------------------------- ### Define SIMIND Data Paths Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_siminddata.ipynb Set the base path for tutorial data and construct specific paths for SIMIND header files for different energy windows. ```python PATH = '/mnt/mydisk2/pytomo_tutorial_data/SPECT' data_path = os.path.join(PATH, 'SIMIND-Jaszak', 'lu177_SYME_jaszak') ``` -------------------------------- ### Set Data Path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_quantitative.ipynb Specifies the local directory where the SIMIND tutorial data is stored. Modify this path to match your system's configuration. ```python path = '/disk1/pytomography_tutorial_data/simind_tutorial/' ``` -------------------------------- ### Perform Non-TOF Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETSIRD.ipynb Reconstructs the non-TOF PET data for a specified number of iterations and subsets. This example uses 100 iterations and 1 subset. ```python recon_nontof = recon_algorithm_nontof(n_iters=100, n_subsets=1) ``` -------------------------------- ### Initialize EXSSystemMatrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Initializes the EXSSystemMatrix with object and projection metadata. This is a prerequisite for forward and backward projection operations. ```python system_matrix = EXSSystemMatrix(object_meta=object_meta, proj_meta=proj_meta) ``` -------------------------------- ### Set Data Path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_ac225_simind_recon.ipynb Defines the file path where the SIMIND tutorial data is stored. Ensure this path is updated to your local data directory. ```python # change to where you saved the data PATH = '/mnt/mydisk2/pytomo_tutorial_data/SPECT/SIMIND-Jaszak' ``` -------------------------------- ### Get SPECT Metadata Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicommultibed.ipynb Retrieves metadata for SPECT reconstruction from a given file and peak energy index. This metadata is crucial for building the system matrix. ```python object_meta, proj_meta = dicom.get_metadata(files_NM[0], index_peak=1) ``` -------------------------------- ### Initialize PoissonLogLikelihood Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_siminddata.ipynb Sets up the PoissonLogLikelihood function for SPECT/PET reconstruction. It requires the system matrix, measured projections, and an optional scatter estimate. ```python likelihood = PoissonLogLikelihood( system_matrix = system_matrix, projections = photopeak_realization, additive_term = scatter_estimate_TEW ) ``` -------------------------------- ### Initialize PET System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_scat_sino.ipynb Sets up the PET system matrix, including attenuation map, normalization sinogram, and PSF transform. Ensure the path to the attenuation map and normalization sinogram are correct. ```python atten_map = gate.get_aligned_attenuation_map(os.path.join(path, 'gate_simulation/simple_phantom/umap_mMR_brainSimplePhantom.hv'), object_meta).to(pytomography.device) normalization_sinogram = torch.load(os.path.join(path, 'normalization_sinogram.pt')) # assumes this has been saved from the intro tutorial proj_meta = PETSinogramPolygonProjMeta(info) psf_transform = GaussianFilter(3) system_matrix = PETSinogramSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [psf_transform], sinogram_sensitivity = normalization_sinogram, N_splits=10, attenuation_map=atten_map, device='cpu' # projections output on cpu, rest is GPU ) ``` -------------------------------- ### Get Actual Frame Duration Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dualpeak.ipynb Read the actual frame duration from a DICOM file, which is used to convert image units from MBq*seconds to MBq. ```python pydicom.dcmread(file_NM).RotationInformationSequence[0].ActualFrameDuration / 1000 ``` -------------------------------- ### Initialize Image Preprocessing Pipeline Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_DIP.ipynb Sets up a pipeline for preprocessing MRI and PET images, including spatial cropping, padding, and intensity thresholding. Ensure 'mri_aligned' is loaded and on the correct device. ```python mri_crop_above = 250 mri_crop_below = 120 roi_start, roi_end = CropForeground().compute_bounding_box(mri_aligned.unsqueeze(0)) pipeline = Compose([ SpatialCropd(['MR', 'NM'], roi_start=roi_start, roi_end=roi_end, allow_missing_keys=True), DivisiblePadd(['MR', 'NM'], 16, allow_missing_keys=True), ThresholdIntensityd(['MR'], mri_crop_above, above=False, cval=mri_crop_above), ThresholdIntensityd(['MR'], mri_crop_below, above=True, cval=mri_crop_below), ScaleIntensityd(['MR'], 0, 1) ]) ``` -------------------------------- ### Initialize Projection Metadata Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Creates an instance of the custom EXSProjMeta class. It uses the object's dimension M and generates a random sensitivity factor for the detector grid. ```python M = object_meta.shape[0] # Note: the sensitivty factor is the same for each projection angle, a single detector is "rotating" between angle 0 and 90 sensitivity_factor = torch.ones((M,M))+0.3*torch.rand((M,M)) proj_meta = EXSProjMeta(M, sensitivity_factor) ``` -------------------------------- ### Initialize PET System Matrix and Likelihood for TOF Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_scat_sinoTOF.ipynb Sets up the PET system matrix with attenuation map, normalization, and PSF, then defines the Poisson log-likelihood function for reconstruction. Requires `os`, `torch`, `PETSinogramPolygonProjMeta`, `GaussianFilter`, `PETSinogramSystemMatrix`, `PoissonLogLikelihood`, and `OSEM`. ```python atten_map = gate.get_aligned_attenuation_map(os.path.join(path, 'gate_simulation/simple_phantom/umap_mMR_brainSimplePhantom.hv'), object_meta).to(pytomography.device) normalization_sinogram = torch.load(os.path.join(path, 'normalization_sinogram.pt')) # assumes this has been saved from the intro tutorial proj_meta = PETSinogramPolygonProjMeta(info, tof_meta) psf_transform = GaussianFilter(3.) system_matrix = PETSinogramSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [psf_transform], sinogram_sensitivity = normalization_sinogram, N_splits=10, attenuation_map=atten_map, device='cpu' # projections output on cpu, rest is GPU ) additive_term = sinogram_randoms_estimate.unsqueeze(-1) / system_matrix._compute_sensitivity_sinogram().cpu() likelihood = PoissonLogLikelihood( system_matrix, sinogram, additive_term = additive_term ) recon_algorithm = OSEM(likelihood) recon_without_scatter_estimation = recon_algorithm(4,14) ``` -------------------------------- ### Initialize PET System Matrix and Likelihood Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_DIP.ipynb Sets up the PET system matrix without PSF modeling and defines the Poisson log-likelihood function with additive terms for reconstruction. ```python system_matrix = PETLMSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [], N_splits=10, attenuation_map=atten_map.to(pytomography.device), ) additive_term = (lm_scatter_estimate + lm_randoms_estimate) / lm_norm additive_term[additive_term.isnan()] = 0 likelihood = PoissonLogLikelihood( system_matrix, additive_term = additive_term ) ``` -------------------------------- ### Set SPECT Tutorial Data Path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicomdata.ipynb Configure the base path to your downloaded SPECT tutorial data. This is crucial for accessing the DICOM files. ```python # change this to where you downloaded the SPECT tutorial data PATH = '/mnt/mydisk2/pytomo_tutorial_data/SPECT' PATH = os.path.join(PATH, 'Lu177-NEMA-SymT2') ``` -------------------------------- ### Define Custom Projection Metadata Class Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Subclasses PyTomography's ProjMeta to define metadata for the Example Scanner. It includes the detector grid size (M) and a sensitivity factor tensor. ```python class EXSProjMeta(ProjMeta): def __init__(self, M, sensitivity_factor): self.M = M self.sensitivity_factor = sensitivity_factor if (sensitivity_factor.shape[0]!=M)*(sensitivity_factor.shape[1]!=M): raise ValueError("sensitivity_factor should have side dimensions M") ``` -------------------------------- ### Perform TOF Reconstruction Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETSIRD.ipynb Reconstructs the TOF PET data for a specified number of iterations and subsets. This example uses 100 iterations and 1 subset due to noisy data. ```python recon_tof = recon_algorithm_tof(n_iters=100, n_subsets=1) ``` -------------------------------- ### Define Data Save Path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_uncertainty_spect.ipynb Specifies the directory where tutorial data will be saved. ```python save_path = '/mnt/mydisk2/pytomo_tutorial_data/SPECT' ``` -------------------------------- ### Get Detector Information Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_LM.ipynb Retrieves information about the scanner's detectors. Requires specifying the path to the macro file and optionally mean interaction depth and minimum sector difference. ```python info = gate.get_detector_info(path = macro_path, mean_interaction_depth=9, min_rsector_difference=0) ``` -------------------------------- ### Set Data Path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_ac225_dicom_recon.ipynb Specifies the base directory for tutorial data. Ensure this path points to your downloaded SPECT data. ```python path = '/mnt/mydisk2/pytomo_tutorial_data/SPECT' ``` -------------------------------- ### Configure and Get Attenuation Map Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicomdata.ipynb Configures the attenuation transform to align CT data with SPECT projections and convert CT data to attenuation coefficients. Retrieves the resulting attenuation map. ```python att_transform.configure(object_meta, proj_meta) attenuation_map = att_transform.attenuation_map ``` -------------------------------- ### Instantiate and Use List Mode System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Instantiates the EXSListmodeSystemMatrix with provided metadata and performs a forward projection on a sample object. This demonstrates the basic usage of the system matrix for list mode data. ```python system_matrix = EXSListmodeSystemMatrix(object_meta=object_meta, proj_meta=proj_meta_listmode) sample_object = torch.rand(object_meta.shape) # object has batch dimension sample_projections = system_matrix.forward(sample_object) sample_projections ``` -------------------------------- ### Get affine matrices and open images Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_plotting.ipynb Retrieves the affine transformation matrices and opens the DICOM images for both CT and SPECT. Affine matrices are crucial for correct spatial alignment during plotting. ```python affine_SPECT = dicom._get_affine_single_file(file_SPECT) affine_CT = dicom._get_affine_multifile(files_CT) SPECT = dicom.open_singlefile(file_SPECT) CT = dicom.open_multifile(files_CT) ``` -------------------------------- ### Specify isotope and detector information Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_spect_mc2.ipynb Configures isotope names, ratios, collimator type, and other detector-specific parameters required for MC simulation. This configuration must be adjusted for different isotopes and scanner setups. ```python isotope_names = ['lu177'] # isotope we want to simulate isotope_ratios = [1] # ratio of isotopes (in this case only 1) collimator_type = 'SY-ME' # collimator type to use cover_thickness = 0.1 # cover thickness in cm (aluminum assumed) backscatter_thickness = 6.6 # backscatter thickness in cm (pyrex) advanced_energy_resolution_model='siemens' # if the energy resolution model above is not used, then # the energy resolution needs to be provided at 140keV in ``` -------------------------------- ### Visualize Projection Data and Attenuation Map Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicomdata.ipynb Compares a slice of the projection data with a slice from the attenuation map derived from CT data. Helps verify alignment and correctness of the attenuation correction setup. ```python sample_slice = attenuation_map.cpu()[:,70].T ``` ```python plt.subplots(1,2,figsize=(7,3)) plt.subplot(121) plt.title('Projection Data') plt.imshow(photopeak[0].cpu().T, cmap='nipy_spectral', origin='lower') plt.axis('off') plt.colorbar(label='Counts') plt.subplot(122) plt.title('From CT Slices') plt.imshow(sample_slice, cmap='Greys_r', origin='lower', interpolation='Gaussian') plt.axis('off') plt.colorbar() ``` -------------------------------- ### Import PyTomography Modules for FBP Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_fbp.ipynb Imports all necessary classes and functions from the PyTomography library for implementing FBP in SPECT. This includes algorithms, projectors, metadata, transforms, and utilities. ```python from pytomography.algorithms import FilteredBackProjection from pytomography.projectors.SPECT import SPECTSystemMatrix from pytomography.metadata.SPECT import SPECTObjectMeta, SPECTProjMeta from pytomography.transforms.SPECT import SPECTAttenuationTransform, SPECTPSFTransform from pytomography.utils import HammingFilter import numpy as np import matplotlib.pyplot as plt import torch from pytomography.io.SPECT import dicom ``` -------------------------------- ### Set Data Path Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dualpeak.ipynb Set the PATH variable to the directory where the PyTomography tutorial data is downloaded. ```python PATH = '/mnt/mydisk2/pytomo_tutorial_data/SPECT' ``` -------------------------------- ### DICOM data processing and system matrix setup Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicom_algorithms.ipynb Processes DICOM CT and projection data, estimates scatter, and configures SPECT transforms and system matrix. This is used when TYPE is set to 'DICOM'. ```python if TYPE=='DICOM': path_CT = os.path.join(data_path, 'CT') files_CT = [os.path.join(path_CT, file) for file in os.listdir(path_CT)] file_NM = os.path.join(data_path, 'projection_data.dcm') object_meta, proj_meta = dicom.get_metadata(file_NM, index_peak=0) photopeak = dicom.get_projections(file_NM, index_peak=0) scatter = dicom.get_energy_window_scatter_estimate(file_NM, index_peak=0, index_lower=1, index_upper=2) att_transform = SPECTAttenuationTransform(filepath=files_CT) collimator_name = 'SY-ME' energy_kev = 208 #keV intrinsic_resolution=0.38 #mm psf_meta = dicom.get_psfmeta_from_scanner_params( collimator_name, energy_kev, intrinsic_resolution=intrinsic_resolution ) psf_transform = SPECTPSFTransform(psf_meta) system_matrix = SPECTSystemMatrix( obj2obj_transforms = [att_transform,psf_transform], proj2proj_transforms = [], object_meta = object_meta, proj_meta = proj_meta) likelihood = PoissonLogLikelihood(system_matrix, photopeak, scatter) elif TYPE=='SIMIND' ``` -------------------------------- ### Get Attenuation Map from CT Slices Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicommultibed.ipynb Retrieves the attenuation map from CT slices for a given SPECT file and peak energy index. This is useful for aligning SPECT data with CT data. ```python attenuation_map1 = dicom.get_attenuation_map_from_CT_slices(files_CT, files_NM[0], index_peak=1) attenuation_map2 = dicom.get_attenuation_map_from_CT_slices(files_CT, files_NM[1], index_peak=1) ``` -------------------------------- ### Initialize OSMAPOSL Reconstruction Algorithm Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_algorithms.ipynb Initializes the OSMAPOSL reconstruction algorithm with a specified likelihood and prior. The prior can be configured with custom weights. ```python prior_rdp = RelativeDifferencePrior(beta=0.3, gamma=2) recon_algorithm_osmaposl = OSMAPOSL( likelihood = likelihood, prior = prior_rdpap) recon_osmaposl = recon_algorithm_osmaposl(n_iters = 40, n_subsets = 8) ``` -------------------------------- ### Initialize PET Reconstruction System Matrix Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_scat_sino.ipynb Sets up the system matrix for PET reconstruction, including object and projection metadata, attenuation map, PSF transform, and normalization sensitivity. Uses OSEM algorithm. ```python # Specify object space for reconstruction object_meta = ObjectMeta( dr=(2,2,2), #mm shape=(128,128,96) #voxels ) # Get projection space metadata from PET geometry information dictionary proj_meta = PETSinogramPolygonProjMeta(info) # Get attenuation map and PSF transform from the associated phantom atten_map = gate.get_aligned_attenuation_map(os.path.join(path, 'gate_simulation/simple_phantom/umap_mMR_brainSimplePhantom.hv'), object_meta).to(pytomography.device) psf_transform = GaussianFilter(3) # 3mm gaussian blurring # Create system matrix system_matrix = PETSinogramSystemMatrix( object_meta, proj_meta, obj2obj_transforms = [psf_transform], sinogram_sensitivity = normalization_sinogram, N_splits=10, # Split FP/BP into 10 loops to save memory attenuation_map=atten_map, device='cpu' # projections are output on the CPU, but internal computation is on GPU ) # Create likelihood likelihood = PoissonLogLikelihood( system_matrix, sinogram, ) # Initialize reconstruction algorithm recon_algorithm = OSEM(likelihood) ``` -------------------------------- ### Get StarGuide metadata and projection data Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_starguide.ipynb Extracts object and projection metadata, along with the actual projection data, from the specified DICOM files. Handles multiple energy windows and discrete projection bins. ```python object_meta, proj_meta = dicom.get_starguide_metadata(files_NM, nearest_theta=0.1) projections = dicom.get_starguide_projections(files_NM) print(projections.shape) ``` -------------------------------- ### Get Reconstruction Metadata Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_siminddata_multiorgan.ipynb Retrieve metadata required for image reconstruction, such as pixel size and projection angles, using `simind.get_metadata`. This function takes a header file path as input and returns object and projection metadata. ```python object_meta, proj_meta = simind.get_metadata(headerfiles[0]) ``` -------------------------------- ### Initialize Poisson Log Likelihood Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_dicomdata.ipynb Sets up the Poisson Log Likelihood for the reconstruction process. This requires the `system_matrix`, `photopeak` (measured data), and `scatter` (scattered data). ```python likelihood = PoissonLogLikelihood(system_matrix, photopeak, scatter) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_algorithms.ipynb Imports all required libraries for SPECT reconstruction, including PyTomography modules for I/O, projectors, transforms, likelihoods, and algorithms. ```python import inspect import matplotlib.pyplot as plt import torch from pytomography.io.SPECT import simind, dicom from pytomography.projectors.SPECT import SPECTSystemMatrix from pytomography.transforms.SPECT import SPECTAttenuationTransform, SPECTPSFTransform from pytomography.algorithms import OSEM from pytomography.likelihoods import PoissonLogLikelihood from pytomography.algorithms import OSEM, OSMAPOSL, BSREM, KEM import matplotlib.pyplot as plt import torch from pytomography.priors import RelativeDifferencePrior from pytomography.priors import TopNAnatomyNeighbourWeight from pytomography.likelihoods import PoissonLogLikelihood from pytomography.transforms.shared import KEMTransform from pytomography.projectors.shared import KEMSystemMatrix import os ``` -------------------------------- ### Load StarGuide projection files Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_starguide.ipynb Constructs a list of file paths for the 12 projection DICOM files, each corresponding to a head on the StarGuide system. ```python path_NM = os.path.join(PATH, 'NEMA-Starguide', 'NM_files') files_NM = [os.path.join(path_NM, f) for f in os.listdir(path_NM)][:12] ``` -------------------------------- ### Get Sensitivity Factor for List Mode Events Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_examplesystemmatrix.ipynb Calculates the sensitivity factor for each list mode event by indexing into the sensitivity data using the derived detector coordinates. This requires the detector coordinates to be formatted correctly for indexing. ```python sensitivity_factor[*scanner_LUT[detector_ids][:,:2].T] ``` -------------------------------- ### Set up Likelihood and Reconstruction Algorithm Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_PETGATE_SINO.ipynb Defines the Poisson log-likelihood function using the system matrix and the sinogram data, then initializes the OSEM reconstruction algorithm. The sinogram is moved to the appropriate device (CPU/GPU). ```python likelihood = PoissonLogLikelihood(system_matrix, sinogram.to(pytomography.device)) recon_algorithm = OSEM(likelihood) recon = recon_algorithm(2,28) ``` -------------------------------- ### Get PSF Metadata and Sigma Fit Function Source: https://github.com/qurit/pytomography/blob/main/docs/source/notebooks/t_siminddata.ipynb Retrieves point spread function (PSF) metadata from a header file and extracts the source code for the sigma fit function. This is used for modeling collimator detector response. ```python psf_meta = simind.get_psfmeta_from_header(photopeak_path) # Below is optional to print details about psf_meta sigma_fit_func_code = inspect.getsource(psf_meta.sigma_fit) print(psf_meta) print(sigma_fit_func_code) ```