### SPDHG Usage Example Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/SPDHG Example demonstrating how to set up and run the SPDHG algorithm with partitioned data. ```python >>> data = dataexample.SIMULATED_PARALLEL_BEAM_DATA.get() >>> data.reorder('astra') >>> data = data.get_slice(vertical='centre') >>> ig = ag.get_ImageGeometry() >>> data_partitioned = data.partition(num_batches=10, mode='staggered') >>> A_partitioned = ProjectionOperator(ig, data_partitioned.geometry, device = "cpu") >>> F = BlockFunction(*[L2NormSquared(b=data_partitioned[i]) for i in range(10)]) >>> alpha = 0.025 >>> G = alpha * TotalVariation() >>> spdhg = SPDHG(f=F, g=G, operator=A_partitioned, sampler=Sampler.sequential(len(A)), initial=A.domain_geometry().allocate(1), update_objective_interval=10) >>> spdhg.run(100) ``` -------------------------------- ### Setup Preconditioning Weights Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/SIRT Calculates the preconditioning arrays M and D. ```python def _set_up_weights(self): """Set up the preconditioning arrays M and D""" self.M = 1. / self.operator.direct( self.operator.domain_geometry().allocate(value=1.0)) self._Dscaled = 1. / self.operator.adjoint( self.operator.range_geometry().allocate(value=1.0)) for arr in [self.M, self._Dscaled]: self._remove_nan_or_inf(arr, replace_with=1.0) ``` -------------------------------- ### Download example dataset Source: https://tomographicimaging.github.io/CIL/nightly/demos/ZeissDataReader Downloads the WALNUT dataset to a local directory. ```python from cil.utilities import dataexample dataexample.WALNUT.download_data(data_dir='../data', prompt=False) ``` -------------------------------- ### Define SumFunction examples Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/functions/Function Examples demonstrating how to instantiate SumFunction with specific functions or a list of functions. ```python >>> from cil.optimisation.functions import L2NormSquared >>> from cil.framework import ImageGeometry >>> f1 = L2NormSquared() >>> f2 = 0.5 * L2NormSquared(b = ig.allocate(1)) >>> F = SumFunction(f1, f2) ``` ```python >>> F = SumFunction(*[L2NormSquared(b=i) for i in range(50)]) ``` -------------------------------- ### ZEISSDataReader ROI Examples Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/io/ZEISSDataReader Examples demonstrating equivalent ROI configurations for the ZEISSDataReader using negative indexing. ```python >>> reader1 = ZeissDataReader(file_name, roi={'horizontal': (10, -10)}) >>> reader2 = ZeissDataReader(file_name, roi={'horizontal': (10, 1990)}) ``` -------------------------------- ### Install memory-profiler Source: https://tomographicimaging.github.io/CIL/nightly/demos/memory_profiling_sandstone Command to install the memory-profiler package via pip. ```bash pip install -U memory_profiler ``` -------------------------------- ### Install build tools on WSL Source: https://tomographicimaging.github.io/CIL/nightly/developer_guide Install necessary C++ build tools within a Windows Subsystem for Linux environment. ```bash apt install build-essential ``` -------------------------------- ### Initialize ZEISSDataReader with ROI Source: https://tomographicimaging.github.io/CIL/nightly/io Examples demonstrating equivalent ROI configurations using negative indexing and explicit slicing. ```python >>> reader1 = ZeissDataReader(file_name, roi={'horizontal': (10, -10)}) ``` ```python >>> reader2 = ZeissDataReader(file_name, roi={'horizontal': (10, 1990)}) ``` -------------------------------- ### Setup image geometry and data Source: https://tomographicimaging.github.io/CIL/nightly/demos/controlledWaveletSparsity_2d Configures the image geometry and creates the AcquisitionData object. ```python # Setup image geometry n = num_pixels - 1 ig = ag.get_ImageGeometry() ig.voxel_num_x = n ig.voxel_num_y = n print(ig) # Setup data data = AcquisitionData(sinogram, deep_copy=False, geometry=ag) show2D(data); ``` -------------------------------- ### Setup Processor Configuration Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/processors/Padder Configures internal parameters and dimensions based on the input data and padding settings. ```python def _set_up(self): data = self.get_input() offset = 4-data.ndim #set defaults self._labels_in = [None]*4 self._labels_in[offset::] = data.dimension_labels self._shape_in = [1]*4 self._shape_in[offset::] = data.shape self._shape_out_full = self._shape_in.copy() self._processed_dims = [0,0,0,0] self._pad_width_param = [(0,0)]*4 self._pad_values_param = [(0,0)]*4 # if pad_width or set_values is passed a dictionary these keys specify the axes to run over if isinstance(self.pad_width, dict) and isinstance(self.pad_values, dict): if self.pad_width.keys() != self.pad_values.keys(): raise ValueError('Dictionaries must contain the same axes') dimensions = self._get_dimensions_from_dict(self.pad_width) elif isinstance(self.pad_width, dict): dimensions = self._get_dimensions_from_dict(self.pad_width) elif isinstance(self.pad_values, dict): dimensions = self._get_dimensions_from_dict(self.pad_values) else: spatial_dimensions =[ 'vertical', 'horizontal', 'horizontal_y', 'horizontal_x' ] dimensions = list(set(spatial_dimensions) & set(self._labels_in)) # get pad_widths for these dimensions for dim in dimensions: try: values = self.pad_width[dim] except TypeError: values = self.pad_width ``` -------------------------------- ### FISTA.__init__ Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/FISTA Initializes the FISTA algorithm instance with the starting point, objective functions, and optional step size or preconditioner. ```APIDOC ## FISTA(initial, f, g, step_size=None, preconditioner=None, **kwargs) ### Description Initializes the FISTA algorithm. The algorithm solves the minimization problem by iteratively applying a gradient step followed by a proximal operator. ### Parameters - **initial** (DataContainer) - Required - Starting point of the algorithm. - **f** (Function) - Required - Differentiable function. If None, uses ZeroFunction. - **g** (Function or None) - Required - Convex function with simple proximal operator. If None, uses ZeroFunction. - **step_size** (float or StepSizeRule) - Optional - Step size for the gradient step. Defaults to 1/L. - **preconditioner** (object) - Optional - A class with an apply method to modify the gradient update. ``` -------------------------------- ### Configure processor setup Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/processors/Slicer Parses the ROI and configures the processor dimensions and output shapes. ```python def _set_up(self): """ This parses the input roi generically and then configures the processor according to its class. """ #read input data = self.get_input() self._parse_roi(data.ndim, data.shape, data.dimension_labels) #processor specific configurations self._configure() # set boolean of dimensions to process self._processed_dims = [0 if self._shape_out_full[i] == self._shape_in[i] else 1 for i in range(4)] self._shape_out = tuple([i for i in self._shape_out_full if i > 1]) self._labels_out = [self._labels_in[i] for i,x in enumerate(self._shape_out_full) if x > 1] ``` -------------------------------- ### Compare FGP_TV and TotalVariation Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/plugins/ccpi_regularisation/functions/regularisers Example showing how to rescale FGP_TV parameters to match TotalVariation results. ```python >>> G1 = (alpha/ig.voxel_size_x) * FGP_TV(max_iteration=100, device='gpu') >>> G2 = alpha * TotalVariation(max_iteration=100, lower=0.) ``` -------------------------------- ### Binning Geometry with Binner Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/processors/Binner Example showing how to apply the Binner processor to a geometry object. ```python >>> from cil.processors import Binner >>> roi = {'horizontal':(None,None,2),'vertical':(None,None,2)} >>> processor = Binner(roi) >>> processor.set_input(data.geometry) >>> geometry_binned = processor.get_output() ``` -------------------------------- ### Initialize NikonDataReader with ROI Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/io/NikonDataReader Examples demonstrating equivalent ways to specify a horizontal region of interest using the NikonDataReader. ```python >>> reader1 = NikonDataReader(file_name, roi={'horizontal': (10, -10)}) ``` ```python >>> reader2 = NikonDataReader(file_name, roi={'horizontal': (10, 1990)}) ``` -------------------------------- ### Setup Acquisition Geometry Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/io/ZEISSDataReader Configures the AcquisitionData container based on beam geometry. ```python def _setup_acq_geometry(self): ''' Setup AcquisitionData container ''' if self._metadata['beam geometry'] == 'cone': self._geometry = AcquisitionGeometry.create_Cone3D( [0,-self._metadata['dist_source_center'],0],[0,self._metadata['dist_center_detector'],0] \ ) \ .set_panel([self._metadata['image_width'], self._metadata['image_height']],\ pixel_size=[self._metadata['detector_pixel_size']/1000,self._metadata['detector_pixel_size']/1000])\ .set_angles(self._metadata['thetas'],angle_unit=AngleUnit.RADIAN) else: self._geometry = AcquisitionGeometry.create_Parallel3D()\ .set_panel([self._metadata['image_width'], self._metadata['image_height']])\ .set_angles(self._metadata['thetas'],angle_unit=AngleUnit.RADIAN) self._geometry.dimension_labels = ['angle', 'vertical', 'horizontal'] ``` -------------------------------- ### Initialize SPDHG Algorithm Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/SPDHG Constructor for the SPDHG class, handling initial parameters and calling the setup method. ```python def __init__(self, f=None, g=None, operator=None, tau=None, sigma=None, initial=None, sampler=None, prob_weights=None, **kwargs): update_objective_interval = kwargs.pop('update_objective_interval', 1) super(SPDHG, self).__init__( update_objective_interval=update_objective_interval) self.set_up(f=f, g=g, operator=operator, sigma=sigma, tau=tau, initial=initial, sampler=sampler, prob_weights=prob_weights) ``` -------------------------------- ### FBP Reconstruction Usage Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/plugins/astra/processors/FBP Example demonstrating how to initialize the FBP processor, set the input data, and retrieve the reconstructed image. ```python >>> from cil.plugins.astra import FBP >>> fbp = FBP(image_geometry, data.geometry) >>> fbp.set_input(data) >>> reconstruction = fbp.get_output() ``` -------------------------------- ### Binning Data with Binner Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/processors/Binner Example showing how to define a region-of-interest and apply the Binner processor to data. ```python >>> from cil.processors import Binner >>> roi = {'horizontal':(10,-10,2),'vertical':(10,-10,2)} >>> processor = Binner(roi) >>> processor.set_input(data) >>> data_binned = processor.get_output() ``` -------------------------------- ### Demonstrate ImageGeometry resolution scaling Source: https://tomographicimaging.github.io/CIL/nightly/demos/00_CIL_geometry Full example showing the creation of an AcquisitionGeometry and subsequent ImageGeometry objects at different resolutions. ```python ag = AcquisitionGeometry.create_Cone3D(source_position=[0,-500,0],detector_position=[0,500,0])\ .set_panel(num_pixels=[2048,2048], pixel_size = 0.2)\ .set_angles(angles=range(0,180)) print("ImageGeometry - default") ig = ag.get_ImageGeometry() print(ig) print("ImageGeometry - 0.5x resolution") ig = ag.get_ImageGeometry(resolution=0.5) print(ig) print("ImageGeometry - 2x resolution") ig = ag.get_ImageGeometry(resolution=2) print(ig) ``` -------------------------------- ### Initialize SIRT Algorithm Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/SIRT Example of initializing the SIRT algorithm with an initial guess, operator, and data. ```python >>> sirt = SIRT(initial = ig.allocate(0), operator = A, data = d) ``` -------------------------------- ### Build and Serve CIL Documentation Source: https://tomographicimaging.github.io/CIL/nightly/developer_guide Commands to clone the repository, set up the development environment, and build the documentation locally. ```bash git clone git@github.com:TomographicImaging/CIL cd CIL conda env create -f ./scripts/cil_development.yml conda activate ENVIRONMENT_NAME pip install -e . cd docs conda update -n base -c defaults conda conda env update -f docs_environment.yml # with the name field set to ENVIRONMENT_NAME make web-deps # install dependencies (requires ruby 3.2) make dirhtml web serve ``` -------------------------------- ### Warm Start Approximate Gradients Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/functions/SAGFunction Initializes all gradients at a specific point to warm start the algorithm. ```python def warm_start_approximate_gradients(self, initial): r"""A function to warm start SAG or SAGA algorithms by initialising all the gradients at an initial point. Equivalently setting :math:`g_i^0 = \nabla f_i(x_0)` for initial point :math:`x_0`. Parameters ---------- initial: DataContainer, The initial point to warmstart the calculation Note ------ When using SAG or SAGA with a deterministic algorithm, you should warm start the SAG-SAGA Function with the same initial point that you initialise the algorithm """ self._list_stored_gradients = [ fi.gradient(initial) for fi in self.functions] self._full_gradient_at_iterate = np.sum(self._list_stored_gradients) self._update_data_passes_indices(list(range(self.num_functions))) self._sampled_grad = initial.copy() self._stochastic_grad_difference = initial.copy() ``` -------------------------------- ### set_up(initial, operator, data) Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/LSQR Configures the LSQR algorithm with the problem definition, including the initial guess, forward operator, and measured data. ```APIDOC ## LSQR.set_up ### Description Sets up the LSQR algorithm with the problem definition and performs the initial Golub-Kahan bidiagonalisation. ### Parameters - **initial** (DataContainer) - Initial guess for the solution. - **operator** (Operator) - Linear operator representing the forward model. - **data** (DataContainer) - Measured data. ``` -------------------------------- ### Configure SPDHG Algorithm Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/SPDHG The set_up method initializes the algorithm parameters, operators, and variables required for execution. ```python [docs] def set_up(self, f, g, operator, sigma=None, tau=None, initial=None, sampler=None, prob_weights=None): '''set-up of the algorithm ''' log.info("%s setting up", self.__class__.__name__) # algorithmic parameters self.f = f self.g = g self.operator = operator if not isinstance(operator, BlockOperator): raise TypeError("operator should be a BlockOperator") self._ndual_subsets = len(self.operator) self._prob_weights = getattr(sampler, 'prob_weights', prob_weights) if self._prob_weights is None: self._prob_weights = [1/self._ndual_subsets]*self._ndual_subsets if prob_weights is not None and self._prob_weights != prob_weights: raise ValueError( ' You passed a `prob_weights` argument and a sampler with a different attribute `prob_weights`, please remove the `prob_weights` argument.') if sampler is None: self._sampler = Sampler.random_with_replacement( len(operator), prob=self._prob_weights) else: self._sampler = sampler # Set the norms of the operators self._norms = operator.get_norms_as_list() self.set_step_sizes(sigma=sigma, tau=tau) # initialize primal variable if initial is None: self.x = self.operator.domain_geometry().allocate(0) else: self.x = initial.copy() self._x_tmp = self.operator.domain_geometry().allocate(0) # initialize dual variable to 0 self._y_old = operator.range_geometry().allocate(0) # This can be removed once #1863 is fixed if not isinstance(self._y_old, BlockDataContainer): self._y_old = BlockDataContainer(self._y_old) # initialize variable z corresponding to back-projected dual variable self._z = operator.domain_geometry().allocate(0) self._zbar = operator.domain_geometry().allocate(0) # relaxation parameter self._theta = 1 self.configured = True logging.info("{} configured".format(self.__class__.__name__, )) ``` -------------------------------- ### set_up(file_name=None) Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/io/NEXUSDataReader Initializes the reader by validating the file path and ensuring the h5py dependency is available. ```APIDOC ## set_up(file_name=None) ### Description Configures the reader with the specified file path and performs validation checks. ### Parameters - **file_name** (str) - Required - Full path to the NeXus file. ``` -------------------------------- ### Initialize and use a sequential sampler Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/utilities/sampler Demonstrates creating a sequential sampler and tracking previous samples. ```python >>> sampler = Sampler.sequential(10) >>> print(sampler.get_previous_samples()) [] >>> print(sampler.view_samples(5)) [0 1 2 3 4] >>> print(next(sampler)) 0 >>> print(sampler.next()) 1 >>> print(sampler.get_current_sample()) 1 >>> print(sampler.get_previous_samples()) [0 1] ``` -------------------------------- ### CentreOfRotationCorrector xcorrelation usage examples Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/processors/CentreOfRotationCorrector Examples demonstrating how to initialize and run the cross-correlation based centre of rotation correction processor. ```python >>> from cil.processors import CentreOfRotationCorrector >>> processor = CentreOfRotationCorrector.xcorrelation('centre') >>> processor.set_input(data) >>> data_centred = processor.get_ouput() ``` ```python >>> from cil.processors import CentreOfRotationCorrector >>> processor = CentreOfRotationCorrector.xcorrelation(slice_index=120) >>> processor.set_input(data) >>> processor.get_ouput(out=data) ``` ```python >>> from cil.processors import CentreOfRotationCorrector >>> import logging >>> logging.basicConfig(level=logging.WARNING) >>> cil_log_level = logging.getLogger('cil.processors') >>> cil_log_level.setLevel(logging.DEBUG) >>> processor = CentreOfRotationCorrector.xcorrelation(slice_index=120) >>> processor.set_input(data) >>> data_centred = processor.get_output() ``` -------------------------------- ### Initialize and run FBP reconstruction Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/plugins/tigre/FBP Demonstrates the basic workflow for configuring the FBP processor, setting the input data, and retrieving the reconstructed output. ```python >>> from cil.plugins.tigre import FBP >>> fbp = FBP(image_geometry, data.geometry) >>> fbp.set_input(data) >>> reconstruction = fbp.get_output() ``` -------------------------------- ### Initialize and use a random sampler with replacement Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/utilities/sampler Demonstrates creating a random sampler with replacement and retrieving samples. ```python >>> sampler = Sampler.random_with_replacement(5) >>> print(sampler.view_samples(20)) [3 4 0 0 2 3 3 2 2 1 1 4 4 3 0 2 4 4 2 4] >>> print(next(sampler)) 3 >>> print(sampler.next()) 4 >>> print(sampler.get_current_sample()) 4 ``` -------------------------------- ### set_up Source: https://tomographicimaging.github.io/CIL/nightly/io Configures the reader with a file name and optional ROI. ```APIDOC ## set_up(file_name, roi=None) ### Description Set up the reader with the specified file and region of interest. ### Parameters - **file_name** (str) - Required - file name to read - **roi** (dict) - Optional - dictionary with roi to load for each axis. ``` -------------------------------- ### Check CIL Version Source: https://tomographicimaging.github.io/CIL/nightly/demos/deriv2_cgls Verify the installed version of the CIL library. ```python import cil print(cil.__version__) ``` -------------------------------- ### Instantiate BlockDataContainer Source: https://tomographicimaging.github.io/CIL/nightly/framework Example of creating a BlockDataContainer from multiple DataContainer objects. ```python bdc = BlockDataContainer(DataContainer0, DataContainer1) ``` -------------------------------- ### Initialize and run VolumeShrinker Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/utilities/shrink_volume Demonstrates how to instantiate the VolumeShrinker and execute the volume reduction process using the 'otsu' method. ```python >>> cil_log_level = logging.getLogger() >>> cil_log_level.setLevel(logging.DEBUG) >>> vs = VolumeShrinker(data, recon_backend='astra') >>> ig_reduced = vs.run(method='otsu', otsu_classes=3) ``` -------------------------------- ### get(data_dir) Source: https://tomographicimaging.github.io/CIL/nightly/utilities Loads a dataset from the specified local data directory. ```APIDOC ## get(data_dir) ### Description Loads a dataset that has been previously downloaded to the specified data directory. ### Parameters - **data_dir** (string) - Required - The directory path containing the dataset to be loaded. ``` -------------------------------- ### Get Algorithm Output Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/algorithms/FISTA Returns the current solution stored in the algorithm. ```python [docs] def get_output(self): " Returns the current solution. " return self.x_old ``` -------------------------------- ### Import CIL and profiling dependencies Source: https://tomographicimaging.github.io/CIL/nightly/demos/memory_profiling_sandstone Initializes the environment by appending local paths and importing necessary CIL modules, algorithms, and profiling utilities. ```python import sys sys.path.append("./Algorithms") sys.path.append("./Scripts") from LSQR import * from LSQR_Tikhonov import * from LSQRLP import * from LSQRMP import * from CGLSLP import * from CGLSMP import * # CIL core components needed from cil.processors import Normaliser, TransmissionAbsorptionConverter, Padder, CentreOfRotationCorrector from cil.framework import AcquisitionGeometry, AcquisitionData, BlockDataContainer # CIL optimisation algorithms and linear operators from cil.optimisation.algorithms import CGLS from cil.optimisation.operators import BlockOperator, IdentityOperator # CIL example synthetic test image from cil.utilities import dataexample # CIL display tools from cil.utilities.display import show2D # CIL FBP from cil.recon import FBP # Forward/backprojector from CIL ASTRA plugin from cil.plugins.astra import ProjectionOperator # Utility functions for this dataset & notebook from Utilities import timed_iterations, mem_prof_process, line_prof_process, line_peak_process, plot_mem, print_output_subset from IPython.display import display, HTML # Third-party imports import numpy as np import scipy import matplotlib.pyplot as plt import os MB = 1/(1024*1024) dtypeSize = 4 ``` -------------------------------- ### CIL version output Source: https://tomographicimaging.github.io/CIL/nightly/demos/stempo2d_v2_1 Displays the installed version of the Core Imaging Library. ```text 23.0.1 ``` -------------------------------- ### Initialize Reconstruction Source: https://tomographicimaging.github.io/CIL/nightly/demos/dynamic_mr_recon Compute the starting image using the adjoint of the block operator. ```python # Starting image x_init = A.adjoint(acq_dyn_block) ``` -------------------------------- ### Setup Image Geometry Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/io/ZEISSDataReader Configures the ImageGeometry container using metadata parameters. ```python def _setup_image_geometry(self): ''' Setup ImageData container ''' slices = self._metadata['number_of_images'] width = self._metadata['image_width'] height = self._metadata['image_height'] voxel_size = self._metadata['pixel_size'] self._geometry = ImageGeometry(voxel_num_x=width, voxel_size_x=voxel_size, voxel_num_y=height, voxel_size_y=voxel_size, voxel_num_z=slices, voxel_size_z=voxel_size) ``` -------------------------------- ### Get Slice Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/framework/acquisition_geometry Returns a new AcquisitionGeometry of a single slice in the requested direction. ```python def get_slice(self, *args, **kwargs): ''' Returns a new AcquisitionGeometry of a single slice in the requested direction. ``` -------------------------------- ### Initialize and use a Herman-Meyer sampler Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/utilities/sampler Demonstrates creating a Herman-Meyer sampler. ```python >>> sampler = Sampler.herman_meyer(12) >>> print(sampler.view_samples(16)) [ 0 6 3 9 1 7 4 10 2 8 5 11 0 6 3 9] ``` -------------------------------- ### Get individual norms Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/operators/BlockOperator Returns a list containing the norms of all operators in the block. ```python def get_norms_as_list(self, ): '''Returns a list of the individual norms of the Operators in the BlockOperator ''' return [op.norm() for op in self.operators] ``` -------------------------------- ### Apply RingRemover processor Source: https://tomographicimaging.github.io/CIL/nightly/demos/bruker2cil Example usage for removing ring artefacts from projection data. ```python #processor = RingRemover(decNum=4, wname='db35', sigma=1.5, info=True) #processor.set_input(proj) #proj = processor.get_output() ``` -------------------------------- ### Initialize FBP reconstructor Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/recon/FBP Example usage of the FBP class for parallel-beam data reconstruction. ```python >>> from cil.utilities.dataexample import SIMULATED_PARALLEL_BEAM_DATA >>> from cil.recon import FBP >>> data = SIMULATED_PARALLEL_BEAM_DATA.get() >>> fbp = FBP(data) >>> out = fbp.run() ``` -------------------------------- ### Build CIL using Docker Source: https://tomographicimaging.github.io/CIL/nightly/developer_guide Initialize submodules and build the CIL Docker image from the repository root. ```bash git submodule update --init --recursive docker build . -t ghcr.io/tomographicimaging/cil ``` -------------------------------- ### Memory Profiler output for LSQR set_up Source: https://tomographicimaging.github.io/CIL/nightly/demos/memory_profiling_sandstone Detailed memory usage report for the set_up method of the LSQR algorithm. ```text Dataset folder already exists in .. Filename: /home/efv97572/cil-showcase/CIL-User-Showcase/015_Memory_Profiling_LSQR_CGLS/Algorithms/LSQRMP.py Line # Mem usage Increment Occurrences Line Contents ============================================================= 92 681.6 MiB 681.6 MiB 1 @profile 93 def set_up(self, initial, operator, data): 94 r'''Initialisation of the algorithm 95 Parameters 96 ------------ 97 operator : Operator 98 Linear operator for the inverse problem 99 initial : (optional) DataContainer in the domain of the operator, default is a DataContainer filled with zeros. 100 Initial guess 101 data : DataContainer in the range of the operator 102 Acquired data to reconstruct 103 104 ''' 105 106 681.6 MiB 0.0 MiB 1 log.info("%s setting up", self.__class__.__name__) 107 735.3 MiB 53.7 MiB 1 self.x = initial.copy() #1 domain 108 735.3 MiB 0.0 MiB 1 self.operator = operator 109 110 # Initialise Golub-Kahan bidiagonalisation (GKB) 111 112 #self.u = data - self.operator.direct(self.x) 113 758.2 MiB 22.9 MiB 1 self.u = self.operator.direct(self.x) #1 range 114 758.2 MiB 0.0 MiB 1 self.u.sapyb(-1, data, 1, out=self.u) 115 758.3 MiB 0.0 MiB 1 self.beta = self.u.norm() 116 758.4 MiB 0.1 MiB 1 self.u /= self.beta 117 118 813.2 MiB 54.9 MiB 1 self.v = self.operator.adjoint(self.u) #2 domain 119 813.2 MiB 0.0 MiB 1 self.alpha = self.v.norm() 120 813.2 MiB 0.0 MiB 1 self.v /= self.alpha 121 122 813.2 MiB 0.0 MiB 1 self.rhobar = self.alpha 123 813.2 MiB 0.0 MiB 1 self.phibar = self.beta 124 813.2 MiB 0.0 MiB 1 self.normr = self.beta 125 813.2 MiB 0.0 MiB 1 self.regalphasq = self.regalpha**2 126 127 866.9 MiB 53.7 MiB 1 self.d = self.v.copy() #3 domain 128 888.5 MiB 21.6 MiB 1 self.tmp_range = data.geometry.allocate(None) #2 range 129 888.5 MiB 0.0 MiB 1 self.tmp_domain = self.x.geometry.allocate(None) #4 domain 130 131 888.5 MiB 0.0 MiB 1 self.res2 = 0 132 133 888.5 MiB 0.0 MiB 1 self.configured = True 134 888.5 MiB 0.0 MiB 1 log.info("%s configured", self.__class__.__name__) run 1 Filename: /home/efv97572/cil-showcase/CIL-User-Showcase/015_Memory_Profiling_LSQR_CGLS/Algorithms/LSQRMP.py ``` -------------------------------- ### Initialize FDK Reconstructor Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/recon/FBP Example usage of the FDK reconstructor with simulated cone-beam data. ```python >>> from cil.utilities.dataexample import SIMULATED_CONE_BEAM_DATA >>> from cil.recon import FDK >>> data = SIMULATED_CONE_BEAM_DATA.get() >>> fdk = FDK(data) >>> out = fdk.run() ``` -------------------------------- ### Run CIL unit tests Source: https://tomographicimaging.github.io/CIL/nightly/developer_guide Execute the test suite to verify the installation. Optionally enable GPU testing by setting the environment variable. ```bash export TESTS_FORCE_GPU=1 # optional, makes GPU test failures noisy python -m unittest discover -v ./Wrappers/Python/test ``` -------------------------------- ### FBP Usage Example Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/plugins/astra/processors/FBP Standard workflow for using the FBP processor to reconstruct data. ```APIDOC from cil.plugins.astra import FBP # Initialize the processor fbp = FBP(image_geometry, data.geometry) # Set the input dataset fbp.set_input(data) # Retrieve the reconstruction reconstruction = fbp.get_output() ``` -------------------------------- ### Build CIL from source Source: https://tomographicimaging.github.io/CIL/nightly/developer_guide Install the package in editable mode. Use the second variant to specify custom paths for optional libraries like IPP or OpenMP. ```bash pip install -e . ``` ```bash pip install -e . -Ccmake.define.IPP_ROOT="" -Ccmake.define.OpenMP_ROOT="" -Ccmake.define.CMAKE_BUILD_TYPE=RelWithDebInfo ``` -------------------------------- ### Initialize L2NormSquared Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/functions/L2NormSquared Examples of initializing the L2NormSquared function with or without a translation parameter b. ```python >>> F = L2NormSquared() >>> F = L2NormSquared(b=b) >>> F = L2NormSquared().centered_at(b) ``` -------------------------------- ### Initialize and use a staggered sampler Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/optimisation/utilities/sampler Demonstrates creating a staggered sampler with a specific stride. ```python >>> sampler = Sampler.staggered(num_indices=21, stride=4) >>> print(next(sampler)) 0 >>> print(sampler.next()) 4 >>> print(sampler.view_samples(5)) [ 0 4 8 12 16] >>> print(sampler.get_previous_samples()) [0 4] ``` -------------------------------- ### Setup and Run CGLS Reconstruction Source: https://tomographicimaging.github.io/CIL/nightly/demos/stempo2d_v2_1 Initializes and executes the CGLS algorithm for image reconstruction. ```python # initialisation of the optimisation algorithm - zero array in this case initial = ig.allocate(0) # setup CGLS cgls = CGLS(initial=initial, operator=A, data=stempoData, max_iteration = 100, update_objective_interval = 10 ) ``` ```python cgls.run(50,verbose=True) # get and visualise the results recon_cgls = cgls.solution ``` -------------------------------- ### Configure and Run FISTA Optimisation Source: https://tomographicimaging.github.io/CIL/nightly/demos/dynamic_mr_recon Sets up the objective function with LeastSquares, initializes the FGP_TV_BDC regulariser, and executes the FISTA algorithm for reconstruction. ```python # Set up optimisation x_init_zero = x_init.copy() # Objective function f = LeastSquares(A, acq_dyn_block, c=1) f.calculate_Lipschitz() alpha = 2e-5 G = FGP_TV_BDC(x_init_zero, alpha) # Set up FISTA for least squares fista = FISTA(initial=x_init_zero, f=f, g=G) fista.max_iteration = 50 fista.update_objective_interval = 10 # Run FISTA fista.run(verbose=True) # Get result im_fista_tv = fista.get_output() ``` -------------------------------- ### Setup Image Geometry Source: https://tomographicimaging.github.io/CIL/nightly/demos/controlledWaveletSparsity_3d Configures the image geometry based on the processed data dimensions. ```python # Setup image geometry (_, nz, nx) = data.shape ig = data.geometry.get_ImageGeometry() ig.voxel_num_x = nx ig.voxel_num_y = nx ig.voxel_num_z = nz print(ig) ``` -------------------------------- ### Initialize and use ProjectionOperator Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/plugins/astra/operators/ProjectionOperator Demonstrates basic instantiation of the ProjectionOperator and execution of direct and adjoint projections. ```python >>> from cil.plugins.astra import ProjectionOperator >>> PO = ProjectionOperator(image.geometry, data.geometry) >>> forward_projection = PO.direct(image) >>> backward_projection = PO.adjoint(data) ``` -------------------------------- ### Get Dimensions from Dictionary Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/processors/Padder Extracts dimension labels from a dictionary and validates them against the input geometry. ```python def _get_dimensions_from_dict(self, dict): dimensions = [] for k in dict.keys(): if k not in self._labels_in: raise ValueError('Dimension label not found in data. Expected labels from {0}. Got {1}'.format(self._geometry.dimension_labels, k)) dimensions.append(k) return dimensions ``` -------------------------------- ### Correct Laminography Geometry Source: https://tomographicimaging.github.io/CIL/nightly/processors Example of fitting tilt and center-of-rotation for parallel beam laminography data. ```python >>> processor = LaminographyGeometryCorrector(parameter_bounds=(tilt_bounds, CoR_bounds), parameter_tolerance=(tilt_tol, CoR_tol)) >>> processor.set_input(data) >>> data_corrected = processor.get_output() ``` -------------------------------- ### CentreOfRotationCorrector Usage Source: https://tomographicimaging.github.io/CIL/nightly/processors Examples of using the CentreOfRotationCorrector to adjust image sharpness using different backends. ```python from cil.processors import CentreOfRotationCorrector processor = CentreOfRotationCorrector.image_sharpness(‘centre’, ‘tigre’) processor.set_input(data) data_centred = processor.get_output() ``` ```python from cil.processors import CentreOfRotationCorrector processor = CentreOfRotationCorrector.image_sharpness(slice_index=120, ‘astra’) processor.set_input(data) processor.get_output(out=data) ``` -------------------------------- ### ZEISSDataReader.set_up Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/io/ZEISSDataReader Configures the reader with a specific file and ROI, validating the file existence and type. ```APIDOC ## set_up(file_name, roi=None) ### Description Sets up the reader by validating the provided file path and ensuring the file extension is either .txrm or .txm. ### Parameters - **file_name** (str) - Required - The path to the file to read. - **roi** (dict) - Optional - A dictionary defining the region of interest for each axis. ``` -------------------------------- ### Compute Proximal Operator with FGP_TV Source: https://tomographicimaging.github.io/CIL/nightly/_modules/cil/plugins/ccpi_regularisation/functions/regularisers Example of initializing the FGP_TV regulariser and computing the proximal operator. ```python >>> G = alpha * FGP_TV(max_iteration=100, device='gpu') >>> sol = G.proximal(b) ``` -------------------------------- ### Import CIL and Numerical Dependencies Source: https://tomographicimaging.github.io/CIL/nightly/demos/deriv2_cgls Initializes the environment by importing necessary libraries for optimization, operators, and data handling. ```python import numpy as np import matplotlib.pyplot as plt from cil.optimisation.algorithms import CGLS from cil.optimisation.operators import MatrixOperator from cil.framework import VectorData, BlockDataContainer from deriv2 import deriv2 from cil.optimisation.operators import BlockOperator,IdentityOperator from cil.optimisation.utilities import callbacks ```