miblab-dl 0.0.0__tar.gz

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: miblab-dl
3
+ Version: 0.0.0
4
+ Summary: Python API for miblab's trained deep-learning models
5
+ Author-email: Steven Sourbron <s.sourbron@sheffield.ac.uk>, Joao Periquito <j.s.periquito@sheffield.ac.uk>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://miblab.org/
8
+ Project-URL: Source Code, https://github.com/openmiblab/miblab-dl
9
+ Keywords: python,medical imaging,MRI,deep learning
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: importlib-resources>=1.1.0
20
+ Requires-Dist: numpy
21
+ Requires-Dist: nibabel
22
+ Requires-Dist: nnunetv2
23
+ Provides-Extra: dev
24
+ Requires-Dist: dbdicom; extra == "dev"
25
+ Requires-Dist: miblab[data]; extra == "dev"
26
+ Requires-Dist: pytest; extra == "dev"
27
+ Requires-Dist: pytest-cov; extra == "dev"
28
+ Requires-Dist: build; extra == "dev"
29
+ Requires-Dist: twine; extra == "dev"
30
+ Requires-Dist: autopep8; extra == "dev"
31
+ Requires-Dist: pycodestyle; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # miblab-dl
35
+
36
+ Python API for miblab's trained deep-learning models
37
+
38
+ ## Installation in a working environment
39
+
40
+ If you are working in an existing environment with pytorch already installed,
41
+ then all you need is this:
42
+
43
+ ```bash
44
+ pip install miblab-dl
45
+ ```
46
+
47
+ ## Installation from scratch
48
+
49
+ If you start from scratch, first create a virtual environment, activate it
50
+ and make sure you have the latest pip version.
51
+
52
+ On Windows:
53
+
54
+ ```bash
55
+ python -m venv myenv
56
+ myenv/Scripts/activate
57
+ python -m pip install --upgrade pip
58
+ ```
59
+
60
+ On Mac or Linux:
61
+
62
+ ```bash
63
+ python -m venv myenv
64
+ source myenv/bin/activate
65
+ python -m pip install --upgrade pip
66
+ ```
67
+
68
+ Now install pytorch in your environment:
69
+
70
+ ```bash
71
+ pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
72
+ ```
73
+
74
+ Then install the `miblab-dl` package:
75
+
76
+ ```bash
77
+ pip install miblab-dl
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ You can import `miblab-dl` functionality in a python script like this:
83
+
84
+ ```python
85
+ import miblab_dl as dl
86
+ ```
87
+
88
+ Then to compute fat and water maps from numpy arrays representing
89
+ `in_phase` and `opposed_phase` Dixon images:
90
+
91
+ ```python
92
+ fat, water = dl.fatwater(opposed_phase, in_phase)
93
+ ```
@@ -0,0 +1,60 @@
1
+ # miblab-dl
2
+
3
+ Python API for miblab's trained deep-learning models
4
+
5
+ ## Installation in a working environment
6
+
7
+ If you are working in an existing environment with pytorch already installed,
8
+ then all you need is this:
9
+
10
+ ```bash
11
+ pip install miblab-dl
12
+ ```
13
+
14
+ ## Installation from scratch
15
+
16
+ If you start from scratch, first create a virtual environment, activate it
17
+ and make sure you have the latest pip version.
18
+
19
+ On Windows:
20
+
21
+ ```bash
22
+ python -m venv myenv
23
+ myenv/Scripts/activate
24
+ python -m pip install --upgrade pip
25
+ ```
26
+
27
+ On Mac or Linux:
28
+
29
+ ```bash
30
+ python -m venv myenv
31
+ source myenv/bin/activate
32
+ python -m pip install --upgrade pip
33
+ ```
34
+
35
+ Now install pytorch in your environment:
36
+
37
+ ```bash
38
+ pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
39
+ ```
40
+
41
+ Then install the `miblab-dl` package:
42
+
43
+ ```bash
44
+ pip install miblab-dl
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ You can import `miblab-dl` functionality in a python script like this:
50
+
51
+ ```python
52
+ import miblab_dl as dl
53
+ ```
54
+
55
+ Then to compute fat and water maps from numpy arrays representing
56
+ `in_phase` and `opposed_phase` Dixon images:
57
+
58
+ ```python
59
+ fat, water = dl.fatwater(opposed_phase, in_phase)
60
+ ```
@@ -0,0 +1,71 @@
1
+ # https://packaging.python.org/en/latest/specifications/pyproject-toml/#pyproject-toml-spec
2
+
3
+ [build-system]
4
+ build-backend = 'setuptools.build_meta'
5
+ requires = ['setuptools>=61.2']
6
+
7
+ [project]
8
+ name = "miblab-dl"
9
+ version = "0.0.0"
10
+ dependencies = [
11
+ 'importlib-resources>=1.1.0',
12
+ 'numpy',
13
+ 'nibabel',
14
+ 'nnunetv2',
15
+ ]
16
+ # optional information
17
+ description = "Python API for miblab's trained deep-learning models"
18
+ readme = "README.md"
19
+ authors = [
20
+ { name = "Steven Sourbron", email = "s.sourbron@sheffield.ac.uk" },
21
+ { name = "Joao Periquito", email = "j.s.periquito@sheffield.ac.uk" },
22
+ ]
23
+ license = "Apache-2.0"
24
+ classifiers = [
25
+ # How mature is this project? Common values are
26
+ # 3 - Alpha
27
+ # 4 - Beta
28
+ # 5 - Production/Stable
29
+ 'Development Status :: 3 - Alpha',
30
+
31
+ # Indicate who your project is intended for
32
+ 'Intended Audience :: Developers',
33
+ 'Intended Audience :: Science/Research',
34
+ 'Topic :: Scientific/Engineering',
35
+ 'Operating System :: OS Independent',
36
+ "Programming Language :: Python",
37
+ "Programming Language :: Python :: 3"
38
+ ]
39
+ keywords = [
40
+ 'python',
41
+ "medical imaging",
42
+ "MRI",
43
+ "deep learning",
44
+ ]
45
+
46
+
47
+ [project.urls]
48
+ "Homepage" = "https://miblab.org/"
49
+ "Source Code" = "https://github.com/openmiblab/miblab-dl"
50
+
51
+ [project.optional-dependencies]
52
+ dev = [
53
+ 'dbdicom',
54
+ 'miblab[data]',
55
+ 'pytest',
56
+ 'pytest-cov',
57
+ 'build',
58
+ 'twine',
59
+ 'autopep8',
60
+ 'pycodestyle',
61
+ ]
62
+
63
+ [tool.setuptools]
64
+ # ...
65
+ # By default, include-package-data is true in pyproject.toml, so you do
66
+ # NOT have to specify this line.
67
+ include-package-data = true
68
+
69
+
70
+ [tool.setuptools.packages.find]
71
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from miblab_dl.fatwatermap import fatwater
2
+
3
+
File without changes
@@ -0,0 +1,183 @@
1
+ """
2
+ Compute water-dominance masks from data that have fat and water maps
3
+ """
4
+
5
+ import os
6
+ import sys
7
+ import subprocess
8
+ import tempfile
9
+
10
+ import numpy as np
11
+ import nibabel as nib
12
+ from miblab import zenodo_fetch
13
+
14
+ if sys.version_info < (3, 9):
15
+ # importlib.resources either doesn't exist or lacks the files()
16
+ # function, so use the PyPI version:
17
+ import importlib_resources
18
+ else:
19
+ # importlib.resources has files(), so use that:
20
+ import importlib.resources as importlib_resources
21
+
22
+
23
+ def fatwater(op_phase, in_phase, te_o=None, te_i=None, t2s_w=15, t2s_f=10):
24
+ """Compute fat and water maps from opposed-phase and in-phase arrays
25
+
26
+ Args:
27
+ op_phase (np.ndarray): opposed phase data
28
+ in_phase (np.ndarray): in-phase data
29
+ model (str): path to the model files
30
+
31
+ Returns:
32
+ fat, water: numpy arrays of the same shape and type as the input arrays.
33
+ """
34
+ print('Downloading model..')
35
+
36
+ temp_dir = importlib_resources.files('miblab_dl.datafiles')
37
+ model = zenodo_fetch("FatWaterPredictor.zip", temp_dir, "17791059", extract=True)
38
+
39
+ print('Predicting fat and water images..')
40
+
41
+ waterdom = _predict_mask_numpy(model, op_phase, in_phase)
42
+ fat, water = _compute_fatwater(waterdom, op_phase, in_phase, te_o, te_i, t2s_w, t2s_f)
43
+ fat[fat < 0] = 0
44
+ water[water < 0] = 0
45
+ return fat, water
46
+
47
+
48
+
49
+ def _predict_mask_numpy(model, op_phase, in_phase):
50
+
51
+ with tempfile.TemporaryDirectory() as input_folder:
52
+
53
+ # Save numpy arrays as nifti
54
+ case_id = "dixon"
55
+ file_op = os.path.join(input_folder, f"{case_id}_0000.nii.gz")
56
+ file_ip = os.path.join(input_folder, f"{case_id}_0001.nii.gz")
57
+ nifti_op = nib.Nifti1Image(op_phase, np.eye(4))
58
+ nifti_ip = nib.Nifti1Image(in_phase, np.eye(4))
59
+ nib.save(nifti_op, file_op)
60
+ nib.save(nifti_ip, file_ip)
61
+
62
+ with tempfile.TemporaryDirectory() as output_folder:
63
+
64
+ # Create predictions in a temporary output_folder
65
+ _predict_mask_folder(model, input_folder, output_folder)
66
+
67
+ # Return result as binary numpy array
68
+ mask_file = os.path.join(output_folder, f"{case_id}.nii.gz")
69
+ waterdom = nib.load(mask_file).get_fdata().astype(np.int8)
70
+ return waterdom
71
+
72
+
73
+ def _predict_mask_folder(model, input_folder, output_folder):
74
+
75
+ # These two variables are not used but we are setting to a
76
+ # dummy value to silence the warnings
77
+ os.environ["nnUNet_raw"] = os.getcwd()
78
+ os.environ["nnUNet_preprocessed"] = os.getcwd()
79
+
80
+ # Folder containing the model weights
81
+ os.environ["nnUNet_results"] = model
82
+
83
+ with tempfile.TemporaryDirectory() as predictions:
84
+
85
+ # Predict and save results in a temporary folder
86
+ cmd = f"nnUNetv2_predict -d Dataset001_FatWaterPredictor -i {input_folder} -o {predictions} -f 0 1 2 3 4 -tr nnUNetTrainer -c 3d_fullres -p nnUNetPlans"
87
+
88
+ process = subprocess.Popen(
89
+ cmd,
90
+ stdout=subprocess.PIPE,
91
+ stderr=subprocess.STDOUT,
92
+ text=True,
93
+ encoding="utf-8", # <-- force UTF-8 decoding
94
+ errors="replace" # <-- avoids crash if weird bytes appear
95
+ )
96
+
97
+ # Stream logs in real-time
98
+ for line in process.stdout:
99
+ print(line, end="")
100
+
101
+ process.wait() # wait for completion
102
+
103
+ # Run post-processing
104
+ os.makedirs(output_folder, exist_ok=True)
105
+ source = os.path.join(model, 'Dataset001_FatWaterPredictor', 'nnUNetTrainer__nnUNetPlans__3d_fullres', "crossval_results_folds_0_1_2_3_4")
106
+ pproc = os.path.join(source, 'postprocessing.pkl')
107
+ plans = os.path.join(source, 'plans.json')
108
+ cmd = f"nnUNetv2_apply_postprocessing -i {predictions} -o {output_folder} -pp_pkl_file {pproc} -np 8 -plans_json {plans}"
109
+
110
+ process = subprocess.Popen(
111
+ cmd,
112
+ stdout=subprocess.PIPE,
113
+ stderr=subprocess.STDOUT,
114
+ text=True,
115
+ encoding="utf-8", # <-- force UTF-8 decoding
116
+ errors="replace" # <-- avoids crash if weird bytes appear
117
+ )
118
+
119
+ # Stream logs in real-time
120
+ for line in process.stdout:
121
+ print(line, end="")
122
+
123
+ process.wait() # wait for completion
124
+
125
+
126
+ def _compute_fatwater(waterdom, op_phase, in_phase, te_o, te_i, t2s_w, t2s_f):
127
+
128
+ if te_o is None:
129
+ Eof, Eif, Eow, Eiw = 1, 1, 1, 1
130
+ else:
131
+ Eof = np.exp(-te_o/t2s_f)
132
+ Eif = np.exp(-te_i/t2s_f)
133
+ Eow = np.exp(-te_o/t2s_w)
134
+ Eiw = np.exp(-te_i/t2s_w)
135
+
136
+ Efatdom = np.array([[Eof, -Eow], [Eif, Eiw]])
137
+ Ewatdom = np.array([[-Eof, Eow], [Eif, Eiw]])
138
+
139
+ Efatdom_inv = np.linalg.inv(Efatdom)
140
+ Ewatdom_inv = np.linalg.inv(Ewatdom)
141
+
142
+ fat, water = _apply_pixelwise_matrix(op_phase, in_phase, waterdom, Efatdom_inv, Ewatdom_inv)
143
+
144
+ return fat, water
145
+
146
+
147
+ def _apply_pixelwise_matrix(a, b, mask, M0, M1) -> np.ndarray:
148
+ """
149
+ For each pixel/voxel combine [a, b] as a 2-vector v and compute:
150
+ result = M0 @ v if mask == 0/False
151
+ result = M1 @ v if mask == 1/True
152
+ Returns arrays c, d of same shape and type
153
+
154
+ Parameters
155
+ ----------
156
+ a, b : np.ndarray
157
+ Input 3D arrays of the same shape (spatial).
158
+ mask : np.ndarray
159
+ Boolean/0-1 array same shape as `a`/`b`. True selects M1.
160
+ M0, M1 : array-like (2x2)
161
+ Two 2x2 matrices.
162
+
163
+ Returns
164
+ -------
165
+ np.ndarray
166
+ Output 3D arrays of the same shape (spatial).
167
+ """
168
+
169
+ # stack components into last axis: shape (..., 2)
170
+ v = np.stack((a, b), axis=-1).astype(float) # shape (Z, Y, X, 2)
171
+
172
+ # compute results for both matrices: result = v @ M.T (vector @ M.T => M @ v per-voxel)
173
+ res0 = v @ M0.T # shape (..., 2)
174
+ res1 = v @ M1.T
175
+
176
+ # Select based on mask; expand mask to last axis
177
+ mask_bool = np.asarray(mask, dtype=bool)
178
+ mask_expanded = mask_bool[..., None] # shape (..., 1)
179
+
180
+ result = np.where(mask_expanded, res1, res0) # shape (..., 2)
181
+
182
+ return result[...,0], result[...,1]
183
+
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: miblab-dl
3
+ Version: 0.0.0
4
+ Summary: Python API for miblab's trained deep-learning models
5
+ Author-email: Steven Sourbron <s.sourbron@sheffield.ac.uk>, Joao Periquito <j.s.periquito@sheffield.ac.uk>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://miblab.org/
8
+ Project-URL: Source Code, https://github.com/openmiblab/miblab-dl
9
+ Keywords: python,medical imaging,MRI,deep learning
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: importlib-resources>=1.1.0
20
+ Requires-Dist: numpy
21
+ Requires-Dist: nibabel
22
+ Requires-Dist: nnunetv2
23
+ Provides-Extra: dev
24
+ Requires-Dist: dbdicom; extra == "dev"
25
+ Requires-Dist: miblab[data]; extra == "dev"
26
+ Requires-Dist: pytest; extra == "dev"
27
+ Requires-Dist: pytest-cov; extra == "dev"
28
+ Requires-Dist: build; extra == "dev"
29
+ Requires-Dist: twine; extra == "dev"
30
+ Requires-Dist: autopep8; extra == "dev"
31
+ Requires-Dist: pycodestyle; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # miblab-dl
35
+
36
+ Python API for miblab's trained deep-learning models
37
+
38
+ ## Installation in a working environment
39
+
40
+ If you are working in an existing environment with pytorch already installed,
41
+ then all you need is this:
42
+
43
+ ```bash
44
+ pip install miblab-dl
45
+ ```
46
+
47
+ ## Installation from scratch
48
+
49
+ If you start from scratch, first create a virtual environment, activate it
50
+ and make sure you have the latest pip version.
51
+
52
+ On Windows:
53
+
54
+ ```bash
55
+ python -m venv myenv
56
+ myenv/Scripts/activate
57
+ python -m pip install --upgrade pip
58
+ ```
59
+
60
+ On Mac or Linux:
61
+
62
+ ```bash
63
+ python -m venv myenv
64
+ source myenv/bin/activate
65
+ python -m pip install --upgrade pip
66
+ ```
67
+
68
+ Now install pytorch in your environment:
69
+
70
+ ```bash
71
+ pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
72
+ ```
73
+
74
+ Then install the `miblab-dl` package:
75
+
76
+ ```bash
77
+ pip install miblab-dl
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ You can import `miblab-dl` functionality in a python script like this:
83
+
84
+ ```python
85
+ import miblab_dl as dl
86
+ ```
87
+
88
+ Then to compute fat and water maps from numpy arrays representing
89
+ `in_phase` and `opposed_phase` Dixon images:
90
+
91
+ ```python
92
+ fat, water = dl.fatwater(opposed_phase, in_phase)
93
+ ```
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/miblab_dl/__init__.py
5
+ src/miblab_dl/fatwatermap.py
6
+ src/miblab_dl.egg-info/PKG-INFO
7
+ src/miblab_dl.egg-info/SOURCES.txt
8
+ src/miblab_dl.egg-info/dependency_links.txt
9
+ src/miblab_dl.egg-info/requires.txt
10
+ src/miblab_dl.egg-info/top_level.txt
11
+ src/miblab_dl/datafiles/__init__.py
12
+ tests/test_fatwater.py
@@ -0,0 +1,14 @@
1
+ importlib-resources>=1.1.0
2
+ numpy
3
+ nibabel
4
+ nnunetv2
5
+
6
+ [dev]
7
+ dbdicom
8
+ miblab[data]
9
+ pytest
10
+ pytest-cov
11
+ build
12
+ twine
13
+ autopep8
14
+ pycodestyle
@@ -0,0 +1 @@
1
+ miblab_dl
@@ -0,0 +1,56 @@
1
+ import os
2
+ import shutil
3
+
4
+ import dbdicom as db
5
+ import numpy as np
6
+
7
+ from miblab import zenodo_fetch
8
+ import miblab_dl as dl
9
+
10
+ from plot import volume_to_mosaic
11
+
12
+
13
+ def test_fatwater():
14
+
15
+ tmp_dir = os.path.join(os.getcwd(), 'tmp')
16
+ os.makedirs(tmp_dir, exist_ok=True)
17
+
18
+ testdata = 'test_data_post_contrast_dixon.zip'
19
+ testdatadoi = '15489381'
20
+
21
+ # Download ZIP file to temp directory
22
+ folder = zenodo_fetch(testdata, tmp_dir, testdatadoi, extract=True)
23
+
24
+ # Read DICOM data
25
+ series_op = db.series(folder, contains='out_phase')[0]
26
+ series_ip = db.series(folder, contains='in_phase')[0]
27
+
28
+ op_phase = db.volume(series_op).values
29
+ in_phase = db.volume(series_ip).values
30
+
31
+ fat_recon, wat_recon = dl.fatwater(op_phase, in_phase)
32
+
33
+ series_fat = db.series(folder, contains='fat')[0]
34
+ series_water = db.series(folder, contains='water')[0]
35
+
36
+ fat = db.volume(series_fat).values
37
+ wat = db.volume(series_water).values
38
+
39
+ fat_recon_err = 100 * np.linalg.norm(fat_recon-fat)/np.linalg.norm(fat)
40
+ wat_recon_err = 100 * np.linalg.norm(wat_recon-wat)/np.linalg.norm(wat)
41
+
42
+ assert np.round(fat_recon_err) == 9
43
+ assert np.round(wat_recon_err) == 16
44
+
45
+ # w_clip = [0, 0.6*min([wat.max(), wat_recon.max()])]
46
+ # volume_to_mosaic(wat, save_as=os.path.join(tmp_dir, f'water.png'), clip=w_clip)
47
+ # volume_to_mosaic(wat_recon, save_as=os.path.join(tmp_dir, f'water_recon.png'), clip=w_clip)
48
+ # f_clip = [0, 0.6*min([fat.max(), fat_recon.max()])]
49
+ # volume_to_mosaic(fat, save_as=os.path.join(tmp_dir, f'fat.png'), clip=f_clip)
50
+ # volume_to_mosaic(fat_recon, save_as=os.path.join(tmp_dir, f'fat_recon.png'), clip=f_clip)
51
+
52
+
53
+
54
+ if __name__=='__main__':
55
+ test_fatwater()
56
+ print('fatwater passed all tests..')