aind-registration-utils 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ """Init package"""
2
+ __version__ = "0.0.1"
@@ -0,0 +1,271 @@
1
+ import ants
2
+ import numpy as np
3
+
4
+ # import SimpleITK as sitk
5
+ import pandas as pd
6
+
7
+
8
+ def apply_ants_transforms_to_point_dict(pts_dict, transformlist, **kwargs):
9
+ """
10
+ Apply ANTs spatial transforms to a dictionary of points.
11
+
12
+ This function takes a dictionary of labeled points, applies a series of
13
+ spatial transformations provided in `transformlist` using ANTs, and returns
14
+ the transformed points in a new dictionary with the same labels.
15
+
16
+ Parameters
17
+ ----------
18
+ pts_dict : dict
19
+ Dictionary where the keys are point labels and the values are 3D points
20
+ as (x, y, z) sequences. Example: {'pt1': [10, 20, 30], 'pt2': [40, 50,
21
+ 60]}
22
+ transformlist : list
23
+ List of spatial transformation filenames to apply to the points. The
24
+ transformations are applied in the order they are provided.
25
+ **kwargs :
26
+ Additional keyword arguments passed to
27
+ `ants.apply_transforms_to_points`.
28
+
29
+ Returns
30
+ -------
31
+ dict
32
+ A dictionary containing the transformed points, maintaining the
33
+ original labels.
34
+
35
+ Examples
36
+ --------
37
+ >>> points = {'pt1': [10, 20, 30], 'pt2': [40, 50, 60]}
38
+ >>> transforms = ['path/to/transform1.nii.gz', 'path/to/transform2.nii.gz']
39
+ >>> transformed_points = apply_ants_transforms_to_point_dict(points,
40
+ ... transforms)
41
+ """
42
+ pt_arr = np.vstack(list(pts_dict.values()))
43
+ pt_df = pd.DataFrame(
44
+ {
45
+ "x": pt_arr[:, 0],
46
+ "y": pt_arr[:, 1],
47
+ "z": pt_arr[:, 2],
48
+ }
49
+ )
50
+ tx_pt_df = ants.apply_transforms_to_points(
51
+ 3, pt_df, transformlist, **kwargs
52
+ )
53
+ tx_pts_dict = {
54
+ k: tx_pt_df.iloc[i, :].values for i, k in enumerate(pts_dict.keys())
55
+ }
56
+ return tx_pts_dict
57
+
58
+
59
+ def ants_register_syn(
60
+ fixed_img,
61
+ moving_img,
62
+ rigid_kwargs=dict(),
63
+ affine_kwargs=dict(),
64
+ syn_kwargs=dict(
65
+ aff_metric="CC",
66
+ syn_metric="CC",
67
+ syn_sampling=2,
68
+ reg_iterations=(500, 200, 10),
69
+ ),
70
+ syn_save_prefix="",
71
+ ):
72
+ """
73
+ Perform SyN registration using ANTs with a two-stage initialization (rigid
74
+ followed by affine).
75
+
76
+ This function performs registration of the moving image to the fixed image
77
+ using the Symmetric Normalization (SyN) method implemented in ANTs
78
+ (Advanced Normalization Tools). Before the SyN registration, it employs a
79
+ two-stage initialization approach: first, it computes a rigid
80
+ transformation, followed by an affine transformation. The final SyN
81
+ registration is initialized with the affine transformation.
82
+
83
+ Parameters
84
+ ----------
85
+ fixed_img : ants.ANTsImage
86
+ Target image for the registration.
87
+ moving_img : ants.ANTsImage
88
+ Source image that will be aligned to the `fixed_img`.
89
+ syn_save_prefix : str, optional
90
+ Prefix for the output files of the SyN registration. If not specified,
91
+ no prefix is added.
92
+
93
+ Returns
94
+ -------
95
+ dict
96
+ A dictionary containing the results of the SyN registration, including
97
+ forward and inverse transformations, warp fields, and other
98
+ registration details.
99
+
100
+ Examples
101
+ --------
102
+ >>> fixed = ants.image_read('path/to/fixed_image.nii.gz')
103
+ >>> moving = ants.image_read('path/to/moving_image.nii.gz')
104
+ >>> syn_results = ants_register_syn_cc(fixed, moving, 'output_prefix_')
105
+ """
106
+
107
+ tx_rigid = ants.registration(
108
+ fixed=fixed_img,
109
+ moving=moving_img,
110
+ type_of_transform="Rigid",
111
+ **rigid_kwargs,
112
+ )
113
+ tx_affine = ants.registration(
114
+ fixed=fixed_img,
115
+ moving=moving_img,
116
+ initial_transform=tx_rigid["fwdtransforms"][0],
117
+ type_of_transform="Affine",
118
+ **affine_kwargs,
119
+ )
120
+ tx_syn = ants.registration(
121
+ fixed=fixed_img,
122
+ moving=moving_img,
123
+ initial_transform=tx_affine["fwdtransforms"][0],
124
+ outprefix=str(syn_save_prefix),
125
+ type_of_transform="SyN",
126
+ **syn_kwargs,
127
+ )
128
+ return tx_syn
129
+
130
+
131
+ def combine_syn_txs(
132
+ fixed_img,
133
+ moving_img,
134
+ tx_syn,
135
+ fwd_prefix,
136
+ rev_prefix,
137
+ ):
138
+ """
139
+ Combine transformations for mouse-to-in vivo registrations.
140
+
141
+ This function applies a series of spatial transformations to align the
142
+ masked mouse image to the in vivo image. The combined transformations are
143
+ returned for both alignments.
144
+
145
+ Parameters
146
+ ----------
147
+ invivo_img : ants.ANTsImage
148
+ The in vivo image used as a target or source for the registrations.
149
+ mouse_img_masked : ants.ANTsImage
150
+ The masked mouse image to be aligned.
151
+ mouse_invivo_tx_syn : dict
152
+ Dictionary containing the forward and inverse transformations between the
153
+ mouse image and the in vivo image.
154
+ mouse_invivo_prefix : str
155
+ Prefix for the output files of the mouse-to-in vivo combined
156
+ transformation.
157
+ invivo_mouse_prefix : str
158
+ Prefix for the output files of the in vivo-to-mouse combined
159
+ transformation.
160
+
161
+ Returns
162
+ -------
163
+ tuple
164
+ A tuple containing the combined transformations for:
165
+ - mouse-to-in vivo
166
+ - in vivo-to-mouse
167
+
168
+ Examples
169
+ --------
170
+ >>> invivo = ants.image_read('path/to/invivo_image.nii.gz')
171
+ >>> mouse_masked = ants.image_read('path/to/mouse_masked_image.nii.gz')
172
+ >>> mouse_tx = {
173
+ ... 'fwdtransforms': ['path/to/fwd_transform.nii.gz'],
174
+ ... 'invtransforms': ['path/to/inv_transform.nii.gz']
175
+ ... }
176
+ >>> combined_txs = combine_mouse_invivo_txs(
177
+ ... invivo, mouse_masked, mouse_tx, 'mouse_invivo_prefix_',
178
+ ... 'invivo_mouse_prefix_'
179
+ ... )
180
+ """
181
+ fwd_tx_cmb = ants.apply_transforms(
182
+ fixed=fixed_img,
183
+ moving=moving_img,
184
+ transformlist=tx_syn["fwdtransforms"],
185
+ compose=str(fwd_prefix),
186
+ )
187
+ rev_tx_cmb = ants.apply_transforms(
188
+ fixed=moving_img,
189
+ moving=fixed_img,
190
+ transformlist=tx_syn["invtransforms"],
191
+ whichtoinvert=[True, False],
192
+ compose=str(rev_prefix),
193
+ )
194
+ return fwd_tx_cmb, rev_tx_cmb
195
+
196
+
197
+ def combine_syn_and_second_transform(
198
+ fixed_img,
199
+ moving_img,
200
+ fwd_tx_syn,
201
+ invivo_ccf_path,
202
+ other_fwd_path,
203
+ other_rev_path,
204
+ combined_prefix,
205
+ ):
206
+ """
207
+ Combine transformations for mouse-to-CCF (Common Coordinate Framework)
208
+ registrations.
209
+
210
+ This function applies a series of spatial transformations to align the
211
+ masked mouse image with the CCF image. These transformations encompass
212
+ mouse-to-in vivo and in vivo-to-CCF alignments. The combined
213
+ transformations for both alignments are returned.
214
+
215
+ Parameters
216
+ ----------
217
+ invivo_img : ants.ANTsImage
218
+ The in vivo image used as an intermediate reference for the
219
+ registrations.
220
+ mouse_img_masked : ants.ANTsImage
221
+ The masked mouse image to be aligned.
222
+ mouse_invivo_tx_syn : dict
223
+ Dictionary containing the forward and inverse transformations between
224
+ the mouse image and the in vivo image.
225
+ invivo_ccf_path : str or pathlib.Path
226
+ Path to the transformation from in vivo to CCF image.
227
+ ccf_invivo_path : str or pathlib.Path
228
+ Path to the transformation from CCF to in vivo image.
229
+ mouse_ccf_prefix : str or pathlib.Path
230
+ Prefix for the output files of the mouse-to-CCF combined
231
+ transformation.
232
+ ccf_mouse_prefix : str or pathlib.Path
233
+ Prefix for the output files of the CCF-to-mouse combined
234
+ transformation.
235
+
236
+ Returns
237
+ -------
238
+ tuple
239
+ A tuple containing the combined transformations for:
240
+ - mouse-to-CCF
241
+ - CCF-to-mouse
242
+
243
+ Examples
244
+ --------
245
+ >>> invivo = ants.image_read('path/to/invivo_image.nii.gz')
246
+ >>> mouse_masked = ants.image_read('path/to/mouse_masked_image.nii.gz')
247
+ >>> mouse_tx = {
248
+ ... 'fwdtransforms': ['path/to/fwd_transform.nii.gz'],
249
+ ... 'invtransforms': ['path/to/inv_transform.nii.gz']
250
+ ... }
251
+ >>> combined_txs = combine_mouse_invivo_and_invivo_ccf_txs(
252
+ ... invivo, mouse_masked, mouse_tx,
253
+ ... 'path/to/invivo_ccf_tx.nii.gz', 'path/to/ccf_invivo_tx.nii.gz',
254
+ ... 'mouse_ccf_prefix_', 'ccf_mouse_prefix_'
255
+ ... )
256
+ """
257
+ fwd_tx_cmb = ants.apply_transforms(
258
+ fixed=fixed_img,
259
+ moving=moving_img,
260
+ transformlist=[str(invivo_ccf_path)] + fwd_tx_syn["fwdtransforms"],
261
+ compose=str(other_rev_path),
262
+ )
263
+ rev_tx_cmb = ants.apply_transforms(
264
+ fixed=moving_img,
265
+ moving=fixed_img,
266
+ transformlist=fwd_tx_syn["invtransforms"] + [str(other_fwd_path)],
267
+ whichtoinvert=[True, False, False],
268
+ compose=str(combined_prefix),
269
+ )
270
+
271
+ return fwd_tx_cmb, rev_tx_cmb
@@ -0,0 +1,61 @@
1
+ """
2
+ Code for handling manual keypoints transforms using vtk
3
+ """
4
+
5
+ import numpy as np
6
+ import vtk
7
+
8
+
9
+ def define_transform(source_landmarks, target_landmarks):
10
+ """
11
+ Defines a non-linear warp between a set of source and target landmarks
12
+
13
+ Parameters
14
+ ==========
15
+ source_landmarks - np.ndarray (N x 3)
16
+ target_landmarks - np.ndarray (N x 3)
17
+
18
+ Returns
19
+ =======
20
+ transform - vtkThinPlateSplineTransform
21
+
22
+ """
23
+
24
+ transform = vtk.vtkThinPlateSplineTransform()
25
+ source_points = vtk.vtkPoints()
26
+ target_points = vtk.vtkPoints()
27
+
28
+ for i in range(source_landmarks.shape[0]):
29
+ source_points.InsertNextPoint(source_landmarks[i, :])
30
+
31
+ for i in range(target_landmarks.shape[0]):
32
+ target_points.InsertNextPoint(target_landmarks[i, :])
33
+
34
+ transform.SetBasisToR() # for 3D transform
35
+ transform.SetSourceLandmarks(source_points)
36
+ transform.SetTargetLandmarks(target_points)
37
+ transform.Update()
38
+
39
+ return transform
40
+
41
+
42
+ def apply_transform(transform, points):
43
+ """
44
+ Applies a non-linear warp to a set of points
45
+
46
+ Parameters
47
+ ==========
48
+ transform - vtkThinPlateSplineTransform
49
+ points - np.ndarray (N x 3)
50
+
51
+ Returns
52
+ =======
53
+ warped_points - np.ndarray (N x 3)
54
+
55
+ """
56
+
57
+ warped_points = np.zeros(points.shape)
58
+ for i in range(points.shape[0]):
59
+ warped_points[i, :] = transform.TransformPoint(points[i, :])
60
+
61
+ return warped_points
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Allen Institute for Neural Dynamics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.1
2
+ Name: aind-registration-utils
3
+ Version: 0.0.1
4
+ Summary: Generated from aind-library-template
5
+ Author: Allen Institute for Neural Dynamics
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Requires-Python: >=3.7
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: antspyx >=0.5
12
+ Requires-Dist: numpy
13
+ Requires-Dist: pandas
14
+ Requires-Dist: SimpleITK
15
+ Requires-Dist: vtk <10,>=9
16
+ Provides-Extra: dev
17
+ Requires-Dist: black ; extra == 'dev'
18
+ Requires-Dist: coverage ; extra == 'dev'
19
+ Requires-Dist: flake8 ; extra == 'dev'
20
+ Requires-Dist: interrogate ; extra == 'dev'
21
+ Requires-Dist: isort ; extra == 'dev'
22
+ Requires-Dist: Sphinx ; extra == 'dev'
23
+ Requires-Dist: furo ; extra == 'dev'
24
+
25
+ # aind-registration-utils
26
+
27
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
28
+ ![Code Style](https://img.shields.io/badge/code%20style-black-black)
29
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
30
+ ![Interrogate](https://img.shields.io/badge/interrogate-73.9%25-red)
31
+ ![Coverage](https://img.shields.io/badge/coverage-61%25-red?logo=codecov)
32
+ ![Python](https://img.shields.io/badge/python->=3.7-blue?logo=python)
33
+
34
+
35
+
36
+ ## Usage
37
+ - To use this template, click the green `Use this template` button and `Create new repository`.
38
+ - After github initially creates the new repository, please wait an extra minute for the initialization scripts to finish organizing the repo.
39
+ - To enable the automatic semantic version increments: in the repository go to `Settings` and `Collaborators and teams`. Click the green `Add people` button. Add `svc-aindscicomp` as an admin. Modify the file in `.github/workflows/tag_and_publish.yml` and remove the if statement in line 65. The semantic version will now be incremented every time a code is committed into the main branch.
40
+ - To publish to PyPI, enable semantic versioning and uncomment the publish block in `.github/workflows/tag_and_publish.yml`. The code will now be published to PyPI every time the code is committed into the main branch.
41
+ - The `.github/workflows/test_and_lint.yml` file will run automated tests and style checks every time a Pull Request is opened. If the checks are undesired, the `test_and_lint.yml` can be deleted. The strictness of the code coverage level, etc., can be modified by altering the configurations in the `pyproject.toml` file and the `.flake8` file.
42
+
43
+ ## Installation
44
+ To use the software, in the root directory, run
45
+ ```bash
46
+ pip install -e .
47
+ ```
48
+
49
+ To develop the code, run
50
+ ```bash
51
+ pip install -e .[dev]
52
+ ```
53
+
54
+ ## Contributing
55
+
56
+ ### Linters and testing
57
+
58
+ There are several libraries used to run linters, check documentation, and run tests.
59
+
60
+ - Please test your changes using the **coverage** library, which will run the tests and log a coverage report:
61
+
62
+ ```bash
63
+ coverage run -m unittest discover && coverage report
64
+ ```
65
+
66
+ - Use **interrogate** to check that modules, methods, etc. have been documented thoroughly:
67
+
68
+ ```bash
69
+ interrogate .
70
+ ```
71
+
72
+ - Use **flake8** to check that code is up to standards (no unused imports, etc.):
73
+ ```bash
74
+ flake8 .
75
+ ```
76
+
77
+ - Use **black** to automatically format the code into PEP standards:
78
+ ```bash
79
+ black .
80
+ ```
81
+
82
+ - Use **isort** to automatically sort import statements:
83
+ ```bash
84
+ isort .
85
+ ```
86
+
87
+ ### Pull requests
88
+
89
+ For internal members, please create a branch. For external members, please fork the repository and open a pull request from the fork. We'll primarily use [Angular](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit) style for commit messages. Roughly, they should follow the pattern:
90
+ ```text
91
+ <type>(<scope>): <short summary>
92
+ ```
93
+
94
+ where scope (optional) describes the packages affected by the code changes and type (mandatory) is one of:
95
+
96
+ - **build**: Changes that affect build tools or external dependencies (example scopes: pyproject.toml, setup.py)
97
+ - **ci**: Changes to our CI configuration files and scripts (examples: .github/workflows/ci.yml)
98
+ - **docs**: Documentation only changes
99
+ - **feat**: A new feature
100
+ - **fix**: A bugfix
101
+ - **perf**: A code change that improves performance
102
+ - **refactor**: A code change that neither fixes a bug nor adds a feature
103
+ - **test**: Adding missing tests or correcting existing tests
104
+
105
+ ### Semantic Release
106
+
107
+ The table below, from [semantic release](https://github.com/semantic-release/semantic-release), shows which commit message gets you which release type when `semantic-release` runs (using the default configuration):
108
+
109
+ | Commit message | Release type |
110
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
111
+ | `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release, Default release |
112
+ | `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
113
+ | `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release <br /> (Note that the `BREAKING CHANGE: ` token must be in the footer of the commit) |
114
+
115
+ ### Documentation
116
+ To generate the rst files source files for documentation, run
117
+ ```bash
118
+ sphinx-apidoc -o doc_template/source/ src
119
+ ```
120
+ Then to create the documentation HTML files, run
121
+ ```bash
122
+ sphinx-build -b html doc_template/source/ doc_template/build/html
123
+ ```
124
+ More info on sphinx installation can be found [here](https://www.sphinx-doc.org/en/master/usage/installation.html).
@@ -0,0 +1,8 @@
1
+ aind_registration_utils/__init__.py,sha256=_b3QC6Y7NboP73RjV4irH9taFd2HaRADfzFUkRDgcbk,41
2
+ aind_registration_utils/ants.py,sha256=grqRYBWfC_sFatnGanJCEkh77808Pc8KiRoz98OSXrk,8682
3
+ aind_registration_utils/vtk.py,sha256=S5-NhZ9FIhRSmJ3kxLItwEUx8XNsTXFcfgWtiHA4CDM,1419
4
+ aind_registration_utils-0.0.1.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
5
+ aind_registration_utils-0.0.1.dist-info/METADATA,sha256=jI8edRk0Op-ROXBlkL177jyE8ZJ-XKDTfGK_eiiq0yM,6473
6
+ aind_registration_utils-0.0.1.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
7
+ aind_registration_utils-0.0.1.dist-info/top_level.txt,sha256=6FpFq4IENJ0P5eRRC4yrQE2e-nmlQzldaKuil8jYbw0,24
8
+ aind_registration_utils-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ aind_registration_utils