Registration scripts

class library.registration.volume_registration.VolumeRegistration(moving, channel=1, xy_um=16, z_um=16, scaling_factor=32.0, fixed='Allen', orientation='sagittal', bspline=False, debug=False)

Bases: object

check_status()

Starter method to check for existing directories and files

create_average_volume()
create_average_volumeXXX()

Instructions for creating an average volume

  1. Create a volume for each brain using the create_volume method with the same um and orientation.

  2. Run the create_brain_coms method to generate COM files for each brain.

  3. Copy each volume from the above step to the AtlasV8/AtlasV8_10um_sagittal.tif. You are basically creating a copy of the volume for each brain in the AtlasV8 directory and registering it to itself with the new COM coordinates created in the create_atlas script. cp -vi MD585/MD585_10um_sagittal.tif ./AtlasV8/AtlasV8_10um_sagittal.tif python src/registration/scripts/create_registration.py –moving MD585 –fixed AtlasV8 –um 10 –task register_volume cp -vi MD589/MD589_10um_sagittal.tif ./AtlasV8/AtlasV8_10um_sagittal.tif python src/registration/scripts/create_registration.py –moving MD589 –fixed AtlasV8 –um 10 –task register_volume cp -vi MD594/MD594_10um_sagittal.tif ./AtlasV8/AtlasV8_10um_sagittal.tif python src/registration/scripts/create_registration.py –moving MD594 –fixed AtlasV8 –um 10 –task register_volume

  4. Run the register_volume method to register each brain to the AtlasV8 volume.

Using just a rigid transform on the above 3 brains works well in aligned the COMs, but the spinal cord and ocular are off a bit.

create_brain_coms()

Creates brain center of mass (COM) files for a set of brains and validates their consistency. This method performs the following steps:

  1. Validates that the number of COM files for each brain is consistent.

  2. Generates a .pts file for each brain containing the COM points.

The method uses the following attributes:

  • self.registration_path: Path to the registration directory.

  • self.um: Unit scaling factor for coordinates.

  • self.orientation: Orientation of the brain data.

The method processes a predefined list of brains and assumes the COM files are stored in a specific directory structure. :raises SystemExit: If the number of COM files is inconsistent across brains.

Outputs:
  • Prints the number of COM files for each brain.

  • Prints an error message and exits if the number of COM files is inconsistent.

  • Writes .pts files containing the COM points for each brain.

Note

If a COM file contains “SC” in its path, the corresponding coordinates are printed to the console for debugging purposes.

create_moving_fixed_points()
create_precomputed()
create_unregistered_pointfile()
create_volume()

Create a 3D volume e.g., to get to 10um isotropic with a 0.325x0.325x20 typical brain whose images (thumbnail_aligned) are downsampled by 1/32 do: xy change = 0.325 * 32 / 10um z change = 20 * 32 / 10um

crop_volume()
downsample_stack()
fill_contours()
group_volume()
insert_points()

This method will take the pickle file of COMs and insert them. The COMs in the pickle files are in pixel coordinates. For typical COMs, the full scaled xy version gets multiplied by 0.325 then inserted Upon retrieval, xy gets: divided by 0.325. Here we scale by our downsampling factor when we created the volume, then multiple by the scan run resolution which is hard coded below.

pad_volume()
points_within_polygons()
register_volume()
register_volume_elastix()

Registers a moving volume to a fixed volume using elastix and saves the resulting registered volume. This method performs the following steps:

  1. Removes the existing elastix output directory if it exists.

  2. Checks if the fixed and moving volume paths are provided; exits if not.

  3. Creates the elastix output directory if it does not exist.

  4. Sets up the registration process using the provided fixed and moving volume paths.

  5. Executes the registration and processes the resulting image.

  6. Saves the registered volume to the specified output path.

self.elastix_output

Path to the directory where elastix output will be stored.

Type:

str

self.fixed_path

Path to the fixed volume image.

Type:

str

self.moving_path

Path to the moving volume image.

Type:

str

self.fixed

Identifier for the fixed volume.

Type:

str

self.moving

Identifier for the moving volume.

Type:

str

self.um

Resolution of the images in micrometers.

Type:

int

self.orientation

Orientation of the images.

Type:

str

self.registered_volume

Path to save the registered volume.

Type:

str

Raises:

SystemExit – If either self.fixed_path or self.moving_path is None.

Outputs:
  • The registered volume is saved to the path specified by self.registered_volume.

  • Prints status messages to indicate progress and output paths.

register_volume_with_fiducials()

Registers two 3D numpy volumes using affine transformation based on fiducials.

Parameters:
  • fixed_volume_np (np.ndarray) – The fixed/reference 3D volume.

  • moving_volume_np (np.ndarray) – The moving 3D volume.

  • fixed_fiducials (np.ndarray) – Nx3 array of fiducials for the fixed volume.

  • moving_fiducials (np.ndarray) – Nx3 array of fiducials for the moving volume.

Returns:

The transformed moving image. transform (sitk.Transform): The computed affine transformation.

Return type:

registered_moving_image (sitk.Image)

report_status()

Prints the current status of the volume registration process with its settings.

This method outputs a formatted summary of the key parameters used in the volume registration process, including the preparation ID, unit of measurement, orientation, debug mode status, number of resolutions, and rigid iterations.

animal

The preparation ID or identifier for the subject.

Type:

str

um

The unit of measurement used in the registration process.

Type:

float

orientation

The orientation setting for the volume registration.

Type:

str

debug

Indicates whether debug mode is enabled.

Type:

bool

number_of_resolutions

The number of resolutions used in the registration.

Type:

int

affineIterations

The number of iterations for rigid affine transformations.

Type:

int

reverse_register_volume()

This method also uses an affine and a bspline registration process, but it does it in reverse. The fixed and moving images get switched so we can get the transformation for the points to get registered to the atlas.

setup_registration(fixed_path, moving_path, moving_point_path, fixed_point_path, fixed_basename, moving_basename)
setup_transformix(outputpath)

Method used to transform volumes and points

tif2zarr()

Downsample a folder of large TIFFs by (z, y, x) scale and write to Zarr.

Parameters: - input_folder: str, path to folder with TIFFs (assumed to be Z-stack) - output_zarr: str, path to output Zarr directory - scale_factors: tuple of (scale_z, scale_y, scale_x), e.g., (0.5, 0.5, 0.5) - chunk_size: tuple of (z, y, x) chunk size - multichannel: whether the TIFFs are RGB

transformix_com()

Helper method when you want to rerun the transform on a set of points. Get the pickle file and transform it. It is in full resolution pixel size. The points in the pickle file need to be translated from full res pixel to the current resolution of the downsampled volume. Points are inserted in the DB in micrometers from the full resolution images

The points.pts file takes THIS format: point 3 102.8 -33.4 57.0 178.1 -10.9 14.5 180.4 -18.1 78.9

transformix_coms()
transformix_coms_db()
transformix_points()

Helper method when you want to rerun the transform on a set of points. Get the pickle file and transform it. It is in full resolution pixel size. The points in the pickle file need to be translated from full res pixel to the current resolution of the downsampled volume. Points are inserted in the DB in micrometers from the full resolution images The TransformParameter.1.txt file is the one that contains the transformation from the affine registration

The points.pts file takes THIS format: point 3 102.8 -33.4 57.0 178.1 -10.9 14.5 180.4 -18.1 78.9

transformix_polygons()

id for ALLEN771602, cerebellum test is 8357

transformix_volume()

Helper method when you want to rerun the same transform on another volume

volume2tif()
volume_origin_creation()
zarr2tif()
library.registration.volume_registration.apply_affine_to_points(points, affine)

Applies a 4x4 affine transformation to a list of (x, y, z) points.

Parameters:
  • affine – np.ndarray of shape (4, 4)

  • points – tuple (x,y,z)

Returns:

np.ndarray of shape (N, 3)

Return type:

transformed points

library.registration.volume_registration.create_affine_matrix_from_mat(filepath)
library.registration.volume_registration.dice(im1, im2)

Computes the Dice coefficient, a measure of set similarity. :param im1: Any array of arbitrary size. If not boolean, will be converted. :type im1: array-like, bool :param im2: Any other array of identical size. If not boolean, will be converted. :type im2: array-like, bool

Returns:

dice – Dice coefficient as a float on range [0,1]. Maximum similarity = 1 No similarity = 0

Return type:

float

Notes

The order of inputs for dice is irrelevant. The result will be identical if im1 and im2 are switched.

library.registration.volume_registration.elastix_to_affine_4x4(filepath)

Converts an Elastix TransformParameters.0.txt affine file into a 4x4 numpy matrix in ZYX order.

library.registration.volume_registration.linear_stretch(old_min, old_max, x, stretch)
library.registration.volume_registration.pad_volume(volume, padto)
library.registration.volume_registration.point_in_polygon(x, y, points)

Check if a point (x, y) is inside a polygon defined by polygon_points.

Parameters:
  • x (float) – X coordinate of the point.

  • y (float) – Y coordinate of the point.

  • polygon_points (list of tuple) – List of (x, y) tuples defining the polygon.

Returns:

True if the point is inside the polygon, False otherwise.

Return type:

bool

library.registration.volume_registration.sort_from_center(polygon: list) list

Get the center of the unique points in a polygon and then use math.atan2 to get the angle from the x-axis to the x,y point. Use that to sort. This only works with convex shaped polygons.

Parameters:

polygon

library.registration.volume_registration.transform_points(points_xyz, transform)

Apply a SimpleITK transform to a list of (x, y, z) points.

Parameters:
  • points_xyz – Nx3 numpy array of points

  • transform – SimpleITK.Transform object

Returns:

Nx3 numpy array of transformed points