### Train Custom uniGradICON Model (Python) Source: https://context7.com/uncbiag/unigradicon/llms.txt Outlines the process for training a two-stage registration network using the uniGradICON model. It covers dataset loading, data augmentation, and experiment setup with checkpointing, utilizing the footsteps library for experiment management. ```python from training.train import train_two_stage, get_dataset, augment from torch.utils.data import DataLoader import footsteps # Configuration input_shape = [1, 1, 175, 175, 175] BATCH_SIZE = 4 GPUS = 4 device_ids = [0, 1, 2, 3] epochs = [801, 201] # [stage1_epochs, stage2_epochs] eval_period = 20 save_period = 20 # Initialize experiment directory footsteps.initialize(output_root="./results/my_unigradicon/") # Load combined dataset dataset = get_dataset() # Returns ConcatDataset of COPD, OAI, HCP, L2R-Abdomen # Further training logic would follow here, e.g.: # train_two_stage(dataset, input_shape, BATCH_SIZE, GPUS, device_ids, epochs, eval_period, save_period) ``` -------------------------------- ### PyTorch DataLoader Setup for Training and Validation Source: https://context7.com/uncbiag/unigradicon/llms.txt This snippet initializes PyTorch DataLoaders for training and validation datasets, enabling batched data loading with shuffling and multi-worker support. It requires a pre-defined dataset object and constants like BATCH_SIZE and GPUS. Inputs are the dataset and hyperparameters; outputs are iterable DataLoader objects for model training. Limitations include fixed worker count and drop_last behavior, which may affect small datasets. ```Python # Create dataloader dataloader = DataLoader( dataset, batch_size=BATCH_SIZE * GPUS, shuffle=True, num_workers=4, drop_last=True ) val_dataloader = DataLoader( dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, drop_last=True ) ``` -------------------------------- ### Build Custom Registration Networks (Python) Source: https://context7.com/uncbiag/unigradicon/llms.txt Illustrates the creation of custom GradICON registration networks with configurable architectures and loss functions. Examples include standard 2-stage networks, networks with final refinement, label-based similarity, and intensity conservation loss. ```python import unigradicon import icon_registration as icon # Define input shape [batch, channels, height, width, depth] input_shape = [1, 1, 175, 175, 175] # Build standard 2-stage network without final refinement step net = unigradicon.make_network( input_shape, include_last_step=False, lmbda=1.5, loss_fn=icon.LNCC(sigma=5) ) # Build 3-stage network with final refinement step net_with_refinement = unigradicon.make_network( input_shape, include_last_step=True, lmbda=1.5, loss_fn=icon.LNCC(sigma=5) ) # Build network with label-based similarity net_with_labels = unigradicon.make_network( input_shape, include_last_step=True, lmbda=1.5, loss_fn=icon.LNCC(sigma=5), use_label=True ) # Build network with intensity conservation loss for CT net_with_conservation = unigradicon.make_network( input_shape, include_last_step=True, lmbda=1.5, loss_fn=icon.LNCC(sigma=5), apply_intensity_conservation_loss=True ) # Assign identity map and move to GPU net.assign_identity_map(input_shape) net.cuda() net.eval() ``` -------------------------------- ### Train Two-Stage Model from Scratch or Resume Checkpoint in PyTorch Source: https://context7.com/uncbiag/unigradicon/llms.txt This function call trains the uniGradICON two-stage model using provided data loaders, input shape, and hyperparameters. It supports training from scratch by setting resume_from to an empty string or resuming from a checkpoint path. Inputs include data loaders, GPU count, epochs, evaluation/save periods, and optional checkpoint; outputs are trained model weights saved to specified directories. Limitations: Requires pre-defined input_shape and custom train_two_stage function; assumes multi-GPU setup with GPUS > 1. ```Python # Train two-stage model from scratch train_two_stage( input_shape, dataloader, val_dataloader, GPUS, epochs, eval_period, save_period, resume_from="" # Empty string for training from scratch ) # Resume training from checkpoint train_two_stage( input_shape, dataloader, val_dataloader, GPUS, epochs, eval_period, save_period, resume_from="results/my_unigradicon/checkpoints/network_weights_400" ) # Final weights saved at: # - results/my_unigradicon/checkpoints/Step_1_final.trch # - results/my_unigradicon/2nd_step/checkpoints/Step_2_final.trch ``` -------------------------------- ### Register Two Images CLI (uniGradICON/multiGradICON) Source: https://context7.com/uncbiag/unigradicon/llms.txt Performs deformable image registration between fixed and moving images using uniGradICON or multiGradICON models via the command line. Supports instance optimization and configurable similarity measures like LNCC and squared LNCC. Requires input image files and modality specifications. ```bash # Download sample images wget https://www.hgreer.com/assets/slicer_mirror/RegLib_C01_1.nrrd wget https://www.hgreer.com/assets/slicer_mirror/RegLib_C01_2.nrrd # Register MRI brain images with default settings (50 IO iterations, LNCC similarity) unigradicon-register \ --fixed=RegLib_C01_2.nrrd \ --fixed_modality=mri \ --moving=RegLib_C01_1.nrrd \ --moving_modality=mri \ --transform_out=trans.hdf5 \ --warped_moving_out=warped_C01_1.nrrd # Register without instance optimization (faster, inference only) unigradicon-register \ --fixed=RegLib_C01_2.nrrd \ --fixed_modality=mri \ --moving=RegLib_C01_1.nrrd \ --moving_modality=mri \ --transform_out=trans.hdf5 \ --warped_moving_out=warped_C01_1.nrrd \ --io_iterations None # Use multiGradICON model with squared LNCC similarity unigradicon-register \ --fixed=RegLib_C01_2.nrrd \ --fixed_modality=mri \ --moving=RegLib_C01_1.nrrd \ --moving_modality=mri \ --transform_out=trans.hdf5 \ --warped_moving_out=warped_C01_1.nrrd \ --model multigradicon \ --io_iterations 50 \ --io_sim lncc2 ``` -------------------------------- ### Load Pretrained Models in Python Source: https://context7.com/uncbiag/unigradicon/llms.txt Python code for loading pretrained uniGradICON or multiGradICON models. Allows configuration of similarity measures, including Squared LNCC, MIND-SSC, and enables intensity conservation loss. Models can also be loaded from custom weight locations. ```python import unigradicon import icon_registration as icon # Load uniGradICON with default LNCC similarity net = unigradicon.get_unigradicon() # Load multiGradICON with squared LNCC similarity net = unigradicon.get_multigradicon(loss_fn=icon.losses.SquaredLNCC(sigma=5)) # Load with MIND-SSC similarity measure net = unigradicon.get_unigradicon(loss_fn=icon.losses.MINDSSC(radius=2, dilation=2)) # Load with intensity conservation loss enabled net = unigradicon.get_unigradicon( loss_fn=icon.LNCC(sigma=5), apply_intensity_conservation_loss=True ) # Load model from custom weights location net = unigradicon.get_unigradicon( weights_location="path/to/custom_weights.trch" ) ``` -------------------------------- ### PyTorch Dataset Classes for Medical Imaging (Python) Source: https://context7.com/uncbiag/unigradicon/llms.txt Provides PyTorch dataset classes for loading and preprocessing medical imaging data from multiple sources like COPD, OAI, HCP, and L2R Abdomen. It demonstrates combining datasets and creating dataloaders for multi-dataset training. ```python from training.dataset import COPDDataset, HCPDataset, OAIDataset, L2rAbdomenDataset from torch.utils.data import DataLoader, ConcatDataset # Load COPD lung CT dataset (intra-patient pairs) copd_dataset = COPDDataset( phase="train", desired_shape=(175, 175, 175), device="cuda:0", ROI_only=True, data_num=1000 ) # Load OAI knee MRI dataset (inter-patient) oai_dataset = OAIDataset( phase="train", desired_shape=(175, 175, 175), device="cuda:0", data_num=1000 ) # Load HCP brain MRI dataset (inter-patient) hcp_dataset = HCPDataset( phase="train", desired_shape=(175, 175, 175), device="cuda:0", data_num=1000 ) # Load L2R Abdomen CT dataset (inter-patient) abdomen_dataset = L2rAbdomenDataset( desired_shape=(175, 175, 175), device="cuda:0", data_num=1000 ) # Combine all datasets for multi-dataset training combined_dataset = ConcatDataset([ copd_dataset, oai_dataset, hcp_dataset, abdomen_dataset ]) # Create dataloader dataloader = DataLoader( combined_dataset, batch_size=4, shuffle=True, num_workers=4, drop_last=True ) # Iterate through batches for moving_image, fixed_image in dataloader: # moving_image and fixed_image are torch tensors [B, 1, H, W, D] print(f"Batch shapes: {moving_image.shape}, {fixed_image.shape}") break ``` -------------------------------- ### Apply Transformation to Warp Images CLI Source: https://context7.com/uncbiag/unigradicon/llms.txt Applies a computed transformation to warp input images or label maps using the command line. Supports different interpolation methods like linear and nearest neighbor. Requires the fixed image, moving image/segmentation, transformation file, and output path. ```bash # Warp an image using linear interpolation unigradicon-warp \ --fixed fixed_image.nii.gz \ --moving moving_image.nii.gz \ --transform trans.hdf5 \ --warped_moving_out warped.nii.gz \ --linear # Warp a segmentation label map using nearest neighbor interpolation unigradicon-warp \ --fixed fixed_image.nii.gz \ --moving moving_segmentation.nii.gz \ --transform trans.hdf5 \ --warped_moving_out warped_seg.nii.gz \ --nearest_neighbor ``` -------------------------------- ### Register with Segmentation Masking CLI Source: https://context7.com/uncbiag/unigradicon/llms.txt Performs image registration using segmentation masks to focus on specific regions of interest or mask out background. Supports both masking the input images and applying loss function masking during instance optimization. Requires fixed/moving images and their corresponding segmentation files. ```bash # Mask out background before registration unigradicon-register \ --fixed=fixed_image.nrrd \ --fixed_modality=mri \ --fixed_segmentation=fixed_seg.nrrd \ --moving=moving_image.nrrd \ --moving_modality=mri \ --moving_segmentation=moving_seg.nrrd \ --transform_out=trans.hdf5 \ --warped_moving_out=warped.nrrd \ --io_iterations None # Apply loss function masking during instance optimization unigradicon-register \ --fixed=fixed_image.nrrd \ --fixed_modality=mri \ --fixed_segmentation=fixed_seg.nrrd \ --moving=moving_image.nrrd \ --moving_modality=mri \ --moving_segmentation=moving_seg.nrrd \ --transform_out=trans.hdf5 \ --warped_moving_out=warped.nrrd \ --io_iterations 50 \ --io_sim lncc2 \ --loss_function_masking ``` -------------------------------- ### Create Custom Similarity Measures (Python) Source: https://context7.com/uncbiag/unigradicon/llms.txt Demonstrates how to create various custom similarity measures using the unigradicon library, including LNCC, squared LNCC, and MIND. It also shows how to load a model with a custom similarity measure and handles potential ValueErrors for unsupported measures. ```python import unigradicon # Create LNCC (Local Normalized Cross Correlation) similarity lncc_sim = unigradicon.make_sim("lncc") # Create squared LNCC similarity (more robust to outliers) lncc2_sim = unigradicon.make_sim("lncc2") # Create MIND-SSC (Modality Independent Neighbourhood Descriptor) mind_sim = unigradicon.make_sim("mind") # Load model with custom similarity measure net = unigradicon.get_unigradicon(loss_fn=lncc2_sim) # Attempting to use unsupported similarity raises ValueError try: invalid_sim = unigradicon.make_sim("invalid_measure") except ValueError as e: print(f"Error: {e}") # Output: Similarity measure invalid_measure not recognized. # Choose from [lncc, lncc2, mind]. ``` -------------------------------- ### Compute Log of Jacobian Determinant Map from Transformation using ITK Source: https://github.com/uncbiag/unigradicon/wiki/uniGradICON-Howto Computes the logarithmic Jacobian determinant map from an ITK transformation. It first calculates the Jacobian determinant map and then applies a logarithmic filter to it. Both the original Jacobian determinant map and its logarithm are saved as NIfTI files. Requires the ITK library. ```python import itk transform_file = "" fixed_img_file = "" transform = itk.transformread(transform_file)[0] jacob = itk.displacement_field_jacobian_determinant_filter( itk.transform_to_displacement_field_filter( transform, reference_image=itk.imread(fixed_img_file), use_reference_image=True ) ) log_jacob = itk.LogImageFilter.New(jacob) log_jacob.Update() log_jacob = log_jacob.GetOutput() itk.imwrite(jacob, "transform_jacob.nii.gz") itk.imwrite(log_jacob, "transform_log_jacob.nii.gz") ``` -------------------------------- ### Load Transform, Compute Jacobian, and Save Results (Python) Source: https://context7.com/uncbiag/unigradicon/llms.txt Loads a transformation and reference image using ITK, computes the Jacobian determinant and its logarithm, and saves the results to NIfTI files. This process is crucial for analyzing deformation fields in image registration. ```python import itk # Load transformation and reference image transform_file = "transform.hdf5" fixed_img_file = "fixed_image.nii.gz" transform = itk.transformread(transform_file)[0] reference_image = itk.imread(fixed_img_file) # Compute Jacobian determinant jacob = itk.displacement_field_jacobian_determinant_filter( itk.transform_to_displacement_field_filter( transform, reference_image=reference_image, use_reference_image=True ) ) # Compute log-Jacobian log_jacob = itk.LogImageFilter.New(jacob) log_jacob.Update() log_jacob = log_jacob.GetOutput() # Save results itk.imwrite(jacob, "jacobian_determinant.nii.gz") itk.imwrite(log_jacob, "log_jacobian_determinant.nii.gz") ``` -------------------------------- ### Register with Segmentation Mask in Python Source: https://context7.com/uncbiag/unigradicon/llms.txt Python code demonstrating image registration using segmentation masks with the unigradicon API. It shows two options: masking out background regions before registration or applying loss function masking during instance optimization. Requires ITK images and segmentation masks. ```python import itk import icon_registration.itk_wrapper import unigradicon # Load model and images net = unigradicon.get_unigradicon() fixed = itk.imread("fixed_image.nii.gz") moving = itk.imread("moving_image.nii.gz") fixed_seg = itk.imread("fixed_segmentation.nii.gz") moving_seg = itk.imread("moving_segmentation.nii.gz") # Option 1: Mask out background before registration fixed_masked = unigradicon.preprocess(fixed, modality="mri", segmentation=fixed_seg) moving_masked = unigradicon.preprocess(moving, modality="mri", segmentation=moving_seg) phi_AB, phi_BA = icon_registration.itk_wrapper.register_pair( net, moving_masked, fixed_masked, finetune_steps=None ) # Option 2: Apply loss function masking during instance optimization phi_AB, phi_BA = icon_registration.itk_wrapper.register_pair_with_mask( net, unigradicon.preprocess(moving, modality="mri"), unigradicon.preprocess(fixed, modality="mri"), moving_seg, fixed_seg, finetune_steps=50 ) itk.transformwrite([phi_AB], "transform_with_mask.hdf5") ``` -------------------------------- ### Compute Jacobian Determinant Map from Transformation using ITK Source: https://github.com/uncbiag/unigradicon/wiki/uniGradICON-Howto Computes the Jacobian determinant map from a given ITK transformation. This involves converting the transformation to a displacement field and then applying the Jacobian determinant filter. The result is saved as a NIfTI file. Requires the ITK library. ```python import itk transform_file = "" fixed_img_file = "" transform = itk.transformread(transform_file)[0] jacob = itk.displacement_field_jacobian_determinant_filter( itk.transform_to_displacement_field_filter( transform, reference_image=itk.imread(fixed_img_file), use_reference_image=True ) ) itk.imwrite(jacob, "transform_jacob.nii.gz") ``` -------------------------------- ### Register Image Pair Using Python API Source: https://context7.com/uncbiag/unigradicon/llms.txt Python code to perform image registration using the unigradicon API with ITK images. It includes loading models, images, preprocessing, registration with and without instance optimization, and saving/applying transformations. The output includes transformation objects. ```python import itk import icon_registration.itk_wrapper import unigradicon # Load pretrained model net = unigradicon.get_unigradicon() # Load images fixed = itk.imread("fixed_image.nii.gz") moving = itk.imread("moving_image.nii.gz") # Preprocess images (normalizes intensity based on modality) fixed_preprocessed = unigradicon.preprocess(fixed, modality="mri") moving_preprocessed = unigradicon.preprocess(moving, modality="mri") # Register without instance optimization phi_AB, phi_BA = icon_registration.itk_wrapper.register_pair( net, moving_preprocessed, fixed_preprocessed, finetune_steps=None ) # Register with 50 iterations of instance optimization phi_AB, phi_BA = icon_registration.itk_wrapper.register_pair( net, moving_preprocessed, fixed_preprocessed, finetune_steps=50 ) # Save transformation itk.transformwrite([phi_AB], "transform.hdf5") # Apply transformation to warp moving image interpolator = itk.LinearInterpolateImageFunction.New(moving) warped = itk.resample_image_filter( moving, transform=phi_AB, interpolator=interpolator, use_reference_image=True, reference_image=fixed ) itk.imwrite(warped, "warped_moving.nii.gz") ``` -------------------------------- ### Compute Jacobian Determinant Map CLI Source: https://context7.com/uncbiag/unigradicon/llms.txt Computes the Jacobian determinant of a deformation field from a transformation file to analyze local volume changes. Can also compute the log-Jacobian map. Requires the transformation file and the fixed image. Outputs the Jacobian map(s). ```bash # Compute Jacobian determinant map unigradicon-jacobian \ --transform trans.hdf5 \ --fixed fixed_image.nii.gz \ --jacob jacobian_map.nii.gz # Compute both Jacobian and log-Jacobian maps unigradicon-jacobian \ --transform trans.hdf5 \ --fixed fixed_image.nii.gz \ --jacob jacobian_map.nii.gz \ --log_jacob log_jacobian_map.nii.gz ``` -------------------------------- ### Preprocess Medical Images in Python Source: https://context7.com/uncbiag/unigradicon/llms.txt Python code for preprocessing medical images using the unigradicon library. It normalizes intensities based on modality (CT or MRI) and can optionally apply segmentation masks to focus on specific regions. Outputs are saved as ITK images. ```python import itk import torch import unigradicon # Load image image = itk.imread("brain_mri.nii.gz") # Preprocess MRI (clips to 0-99th percentile, normalizes to [0,1]) preprocessed_mri = unigradicon.preprocess(image, modality="mri") # Preprocess CT (clips to [-1000, 1000] HU, normalizes to [0,1]) ct_image = itk.imread("lung_ct.nii.gz") preprocessed_ct = unigradicon.preprocess(ct_image, modality="ct") # Preprocess with segmentation mask (masks out background) segmentation = itk.imread("brain_segmentation.nii.gz") preprocessed_masked = unigradicon.preprocess( image, modality="mri", segmentation=segmentation ) itk.imwrite(preprocessed_mri, "preprocessed_mri.nii.gz") ``` -------------------------------- ### Compute Jacobian Determinant in Python Source: https://context7.com/uncbiag/unigradicon/llms.txt Python snippet for computing the Jacobian determinant and log-Jacobian maps from ITK transformations. This is used for analyzing deformation fields resulting from image registration. Requires the ITK library. ```python import itk ``` -------------------------------- ### Enable Intensity Conservation Loss for CT Registration Source: https://context7.com/uncbiag/unigradicon/llms.txt Command-line tool to register CT images with intensity conservation loss enabled. Requires fixed and moving images, their segmentations, and specifies output files and registration settings. This option is useful for preserving intensity relationships between images during registration. ```bash unigradicon-register \ --fixed=fixed_ct.nrrd \ --fixed_modality=ct \ --fixed_segmentation=fixed_seg.nrrd \ --moving=moving_ct.nrrd \ --moving_modality=ct \ --moving_segmentation=moving_seg.nrrd \ --transform_out=trans.hdf5 \ --warped_moving_out=warped.nrrd \ --io_iterations 50 \ --io_sim lncc2 \ --intensity_conservation_loss ``` -------------------------------- ### Register with Intensity Conservation Loss CLI Source: https://context7.com/uncbiag/unigradicon/llms.txt Enables mass-conserving registration for CT images using a determinant-based intensity correction. This is particularly useful for CT scans where HU values represent density. The command requires standard registration inputs and potentially specific parameters for intensity conservation. ```bash # Example command for intensity conservation (specific flags might vary based on implementation) # unigradicon-register \ # --fixed=fixed_ct.nrrd \ # --moving=moving_ct.nrrd \ # --transform_out=trans_ct.hdf5 \ # --warped_moving_out=warped_ct.nrrd \ # --intensity_conservation # The actual command structure for intensity conservation is not fully detailed in the provided text. # This is a placeholder based on the description. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.