mipcandy 1.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.
- mipcandy-1.0.0/.gitignore +7 -0
- mipcandy-1.0.0/LICENSE +201 -0
- mipcandy-1.0.0/PKG-INFO +44 -0
- mipcandy-1.0.0/README.md +21 -0
- mipcandy-1.0.0/mipcandy/__init__.py +13 -0
- mipcandy-1.0.0/mipcandy/common/__init__.py +2 -0
- mipcandy-1.0.0/mipcandy/common/module/__init__.py +2 -0
- mipcandy-1.0.0/mipcandy/common/module/conv.py +59 -0
- mipcandy-1.0.0/mipcandy/common/module/preprocess.py +179 -0
- mipcandy-1.0.0/mipcandy/common/optim/__init__.py +2 -0
- mipcandy-1.0.0/mipcandy/common/optim/loss.py +41 -0
- mipcandy-1.0.0/mipcandy/common/optim/lr_scheduler.py +34 -0
- mipcandy-1.0.0/mipcandy/data/__init__.py +6 -0
- mipcandy-1.0.0/mipcandy/data/convertion.py +20 -0
- mipcandy-1.0.0/mipcandy/data/dataset.py +180 -0
- mipcandy-1.0.0/mipcandy/data/geometric.py +24 -0
- mipcandy-1.0.0/mipcandy/data/io.py +40 -0
- mipcandy-1.0.0/mipcandy/data/visualization.py +117 -0
- mipcandy-1.0.0/mipcandy/evaluation.py +100 -0
- mipcandy-1.0.0/mipcandy/frontend/__init__.py +2 -0
- mipcandy-1.0.0/mipcandy/frontend/notion_fe.py +123 -0
- mipcandy-1.0.0/mipcandy/frontend/prototype.py +78 -0
- mipcandy-1.0.0/mipcandy/frontend/wandb_fe.py +34 -0
- mipcandy-1.0.0/mipcandy/inference.py +124 -0
- mipcandy-1.0.0/mipcandy/layer.py +67 -0
- mipcandy-1.0.0/mipcandy/metrics.py +122 -0
- mipcandy-1.0.0/mipcandy/preset/__init__.py +1 -0
- mipcandy-1.0.0/mipcandy/preset/segmentation.py +63 -0
- mipcandy-1.0.0/mipcandy/sanity_check.py +12 -0
- mipcandy-1.0.0/mipcandy/sliding_window.py +111 -0
- mipcandy-1.0.0/mipcandy/training.py +387 -0
- mipcandy-1.0.0/mipcandy/types.py +13 -0
- mipcandy-1.0.0/pyproject.toml +29 -0
mipcandy-1.0.0/LICENSE
ADDED
|
@@ -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.
|
mipcandy-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mipcandy
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A Candy for Medical Image Processing
|
|
5
|
+
Project-URL: Homepage, https://mipcandy.projectneura.org
|
|
6
|
+
Project-URL: Documentation, https://mipcandy-docs.projectneura.org
|
|
7
|
+
Project-URL: Repository, https://github.com/ProjectNeura/MIPCandy
|
|
8
|
+
Author-email: Project Neura <central@projectneura.org>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Requires-Dist: matplotlib
|
|
13
|
+
Requires-Dist: numpy
|
|
14
|
+
Requires-Dist: pandas
|
|
15
|
+
Requires-Dist: ptflops
|
|
16
|
+
Requires-Dist: requests
|
|
17
|
+
Requires-Dist: rich
|
|
18
|
+
Requires-Dist: simpleitk
|
|
19
|
+
Requires-Dist: torch
|
|
20
|
+
Provides-Extra: standard
|
|
21
|
+
Requires-Dist: pyvista; extra == 'standard'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# MIP Candy: A Candy for Medical Image Processing
|
|
25
|
+
|
|
26
|
+

|
|
27
|
+

|
|
28
|
+

|
|
29
|
+

|
|
30
|
+
|
|
31
|
+
MIP Candy is Project Neura's next-generation infrastructure framework for medical image processing. It integrates a
|
|
32
|
+
handful number of common network architectures with their corresponding training, inference, and evaluation pipelines
|
|
33
|
+
that are out-of-the-box ready to use. Additionally, it also provides adapters to popular frontend dashboards such as
|
|
34
|
+
Notion, WandB, and TensorBoard.
|
|
35
|
+
|
|
36
|
+
:link: [Docs](https://mipcandy-docs.projectneura.org)
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
Note that MIP Candy requires **Python >= 3.12**.
|
|
41
|
+
|
|
42
|
+
```shell
|
|
43
|
+
pip install "mipcandy[standard]"
|
|
44
|
+
```
|
mipcandy-1.0.0/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIP Candy: A Candy for Medical Image Processing
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+

|
|
5
|
+

|
|
6
|
+

|
|
7
|
+
|
|
8
|
+
MIP Candy is Project Neura's next-generation infrastructure framework for medical image processing. It integrates a
|
|
9
|
+
handful number of common network architectures with their corresponding training, inference, and evaluation pipelines
|
|
10
|
+
that are out-of-the-box ready to use. Additionally, it also provides adapters to popular frontend dashboards such as
|
|
11
|
+
Notion, WandB, and TensorBoard.
|
|
12
|
+
|
|
13
|
+
:link: [Docs](https://mipcandy-docs.projectneura.org)
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
Note that MIP Candy requires **Python >= 3.12**.
|
|
18
|
+
|
|
19
|
+
```shell
|
|
20
|
+
pip install "mipcandy[standard]"
|
|
21
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from mipcandy.common import *
|
|
2
|
+
from mipcandy.data import *
|
|
3
|
+
from mipcandy.evaluation import EvalCase, EvalResult, Evaluator
|
|
4
|
+
from mipcandy.frontend import *
|
|
5
|
+
from mipcandy.inference import parse_predictant, Predictor
|
|
6
|
+
from mipcandy.layer import batch_int_multiply, batch_int_divide, LayerT, HasDevice, WithPaddingModule
|
|
7
|
+
from mipcandy.metrics import do_reduction, dice_similarity_coefficient_binary, \
|
|
8
|
+
dice_similarity_coefficient_multiclass, soft_dice_coefficient, accuracy_binary, accuracy_multiclass, \
|
|
9
|
+
precision_binary, precision_multiclass, recall_binary, recall_multiclass, iou_binary, iou_multiclass
|
|
10
|
+
from mipcandy.preset import *
|
|
11
|
+
from mipcandy.sanity_check import num_trainable_params, sanity_check
|
|
12
|
+
from mipcandy.training import TrainerToolbox, Trainer, SWMetadata, SlidingTrainer
|
|
13
|
+
from mipcandy.types import Secret, Secrets, Params, Transform, SupportedPredictant, Colormap
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from typing import override
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import nn
|
|
5
|
+
|
|
6
|
+
from mipcandy.layer import LayerT
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AbstractConvBlock(nn.Module):
|
|
10
|
+
def __init__(self, in_ch: int, out_ch: int, kernel_size: int, *, stride: int = 1, padding: int = 0,
|
|
11
|
+
dilation: int = 1, groups: int = 1, bias: bool = True, padding_mode: str = "zeros",
|
|
12
|
+
conv: LayerT = ..., norm: LayerT = ..., act: LayerT = ...) -> None:
|
|
13
|
+
super().__init__()
|
|
14
|
+
self.conv: nn.Module = conv.assemble(in_ch, out_ch, kernel_size, stride, padding, dilation, groups, bias,
|
|
15
|
+
padding_mode)
|
|
16
|
+
self.norm: nn.Module = norm.assemble(in_ch=out_ch)
|
|
17
|
+
self.act: nn.Module = act.assemble()
|
|
18
|
+
|
|
19
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
20
|
+
return self.act(self.norm(self.conv(x)))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _conv_block(default_conv: LayerT, default_norm: LayerT, default_act: LayerT) -> type[AbstractConvBlock]:
|
|
24
|
+
class ConvBlock(AbstractConvBlock):
|
|
25
|
+
def __init__(self, *args, **kwargs) -> None:
|
|
26
|
+
if "conv" not in kwargs:
|
|
27
|
+
kwargs["conv"] = default_conv
|
|
28
|
+
if "norm" not in kwargs:
|
|
29
|
+
kwargs["norm"] = default_norm
|
|
30
|
+
if "act" not in kwargs:
|
|
31
|
+
kwargs["act"] = default_act
|
|
32
|
+
super().__init__(*args, **kwargs)
|
|
33
|
+
|
|
34
|
+
return ConvBlock
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
ConvBlock2d: type[AbstractConvBlock] = _conv_block(
|
|
38
|
+
LayerT(nn.Conv2d), LayerT(nn.BatchNorm2d, num_features="in_ch"), LayerT(nn.ReLU, inplace=True)
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
ConvBlock3d: type[AbstractConvBlock] = _conv_block(
|
|
42
|
+
LayerT(nn.Conv3d), LayerT(nn.BatchNorm3d, num_features="in_ch"), LayerT(nn.ReLU, inplace=True)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class WSConv2d(nn.Conv2d):
|
|
47
|
+
@override
|
|
48
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
49
|
+
w = self.weight
|
|
50
|
+
w = (w - w.mean(dim=(1, 2, 3), keepdim=True)) / (w.std(dim=(1, 2, 3), keepdim=True) + 1e-5)
|
|
51
|
+
return nn.functional.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class WSConv3d(nn.Conv3d):
|
|
55
|
+
@override
|
|
56
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
57
|
+
w = self.weight
|
|
58
|
+
w = (w - w.mean(dim=(1, 2, 3, 4), keepdim=True)) / (w.std(dim=(1, 2, 3, 4), keepdim=True) + 1e-5)
|
|
59
|
+
return nn.functional.conv3d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
from math import ceil
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn
|
|
6
|
+
|
|
7
|
+
from mipcandy.types import Colormap
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Pad(nn.Module):
|
|
11
|
+
def __init__(self, *, value: int = 0, mode: str = "constant", batch: bool = True) -> None:
|
|
12
|
+
super().__init__()
|
|
13
|
+
self._value: int = value
|
|
14
|
+
self._mode: str = mode
|
|
15
|
+
self.batch: bool = batch
|
|
16
|
+
self._paddings: tuple[int, int, int, int, int, int] | tuple[int, int, int, int] | None = None
|
|
17
|
+
self.requires_grad_(False)
|
|
18
|
+
|
|
19
|
+
@staticmethod
|
|
20
|
+
def _c_t(size: int, min_factor: int) -> int:
|
|
21
|
+
"""
|
|
22
|
+
Compute target on a single dimension
|
|
23
|
+
"""
|
|
24
|
+
return ceil(size / min_factor) * min_factor
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def _c_p(size: int, min_factor: int) -> tuple[int, int]:
|
|
28
|
+
"""
|
|
29
|
+
Compute padding on a single dimension
|
|
30
|
+
"""
|
|
31
|
+
excess = Pad._c_t(size, min_factor) - size
|
|
32
|
+
before = excess // 2
|
|
33
|
+
return before, excess - before
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Pad2d(Pad):
|
|
37
|
+
def __init__(self, min_factor: int | tuple[int, int], *, value: int = 0, mode: str = "constant",
|
|
38
|
+
batch: bool = True) -> None:
|
|
39
|
+
super().__init__(value=value, mode=mode, batch=batch)
|
|
40
|
+
self._min_factor: tuple[int, int] = (min_factor,) * 2 if isinstance(min_factor, int) else min_factor
|
|
41
|
+
|
|
42
|
+
def paddings(self) -> tuple[int, int, int, int] | None:
|
|
43
|
+
return self._paddings
|
|
44
|
+
|
|
45
|
+
def padded_shape(self, in_shape: tuple[int, int, ...]) -> tuple[int, int, ...]:
|
|
46
|
+
return *in_shape[:-2], Pad._c_t(in_shape[-2], self._min_factor[0]), Pad._c_t(in_shape[-1], self._min_factor[1])
|
|
47
|
+
|
|
48
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
49
|
+
if self.batch:
|
|
50
|
+
_, _, h, w = x.shape
|
|
51
|
+
suffix = (0,) * 4
|
|
52
|
+
else:
|
|
53
|
+
_, h, w = x.shape
|
|
54
|
+
suffix = (0,) * 2
|
|
55
|
+
self._paddings = Pad._c_p(h, self._min_factor[0]) + Pad._c_p(w, self._min_factor[1])
|
|
56
|
+
return nn.functional.pad(x, self._paddings[::-1] + suffix, self._mode, self._value)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Pad3d(Pad):
|
|
60
|
+
def __init__(self, min_factor: int | tuple[int, int, int], *, value: int = 0, mode: str = "constant",
|
|
61
|
+
batch: bool = True) -> None:
|
|
62
|
+
super().__init__(value=value, mode=mode, batch=batch)
|
|
63
|
+
self._min_factor: tuple[int, int, int] = (min_factor,) * 3 if isinstance(min_factor, int) else min_factor
|
|
64
|
+
|
|
65
|
+
def paddings(self) -> tuple[int, int, int, int, int, int] | None:
|
|
66
|
+
return self._paddings
|
|
67
|
+
|
|
68
|
+
def padded_shape(self, in_shape: tuple[int, int, int, ...]) -> tuple[int, int, int, ...]:
|
|
69
|
+
return (*in_shape[:-3], Pad._c_t(in_shape[-3], self._min_factor[0]), Pad._c_t(
|
|
70
|
+
in_shape[-2], self._min_factor[1]), Pad._c_t(in_shape[-1], self._min_factor[2]))
|
|
71
|
+
|
|
72
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
73
|
+
if self.batch:
|
|
74
|
+
_, _, d, h, w = x.shape
|
|
75
|
+
suffix = (0,) * 4
|
|
76
|
+
else:
|
|
77
|
+
_, d, h, w = x.shape
|
|
78
|
+
suffix = (0,) * 2
|
|
79
|
+
self._paddings = Pad._c_p(d, self._min_factor[2]) + Pad._c_p(h, self._min_factor[0]) + Pad._c_p(
|
|
80
|
+
w, self._min_factor[1])
|
|
81
|
+
return nn.functional.pad(x, self._paddings[::-1] + suffix, self._mode, self._value)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Restore2d(nn.Module):
|
|
85
|
+
def __init__(self, conjugate_padding: Pad2d) -> None:
|
|
86
|
+
super().__init__()
|
|
87
|
+
self.conjugate_padding: Pad2d = conjugate_padding
|
|
88
|
+
self.requires_grad_(False)
|
|
89
|
+
|
|
90
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
91
|
+
paddings = self.conjugate_padding.paddings()
|
|
92
|
+
if not paddings:
|
|
93
|
+
raise UserWarning("Paddings seem to be unset, did you forget to pad before restoring?")
|
|
94
|
+
pad_h0, pad_h1, pad_w0, pad_w1 = paddings
|
|
95
|
+
if self.conjugate_padding.batch:
|
|
96
|
+
_, _, h, w = x.shape
|
|
97
|
+
return x[:, :, pad_h0: h - pad_h1, pad_w0: w - pad_w1]
|
|
98
|
+
_, h, w = x.shape
|
|
99
|
+
return x[:, pad_h0: h - pad_h1, pad_w0: w - pad_w1]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Restore3d(nn.Module):
|
|
103
|
+
def __init__(self, conjugate_padding: Pad3d) -> None:
|
|
104
|
+
super().__init__()
|
|
105
|
+
self.conjugate_padding: Pad3d = conjugate_padding
|
|
106
|
+
self.requires_grad_(False)
|
|
107
|
+
|
|
108
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
109
|
+
paddings = self.conjugate_padding.paddings()
|
|
110
|
+
if not paddings:
|
|
111
|
+
raise UserWarning("Paddings seem to be unset, did you forget to pad before restoring?")
|
|
112
|
+
pad_h0, pad_h1, pad_w0, pad_w1, pad_d0, pad_d1 = paddings
|
|
113
|
+
if self.conjugate_padding.batch:
|
|
114
|
+
_, _, d, h, w = x.shape
|
|
115
|
+
return x[:, :, pad_d0: d - pad_d1, pad_h0: h - pad_h1, pad_w0: w - pad_w1]
|
|
116
|
+
_, d, h, w = x.shape
|
|
117
|
+
return x[:, pad_d0: d - pad_d1, pad_h0: h - pad_h1, pad_w0: w - pad_w1]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Normalize(nn.Module):
|
|
121
|
+
def __init__(self, *, domain: tuple[float | None, float | None] = (0, None), strict: bool = False,
|
|
122
|
+
method: Literal["linear", "intercept", "cut"] = "linear") -> None:
|
|
123
|
+
super().__init__()
|
|
124
|
+
self._domain: tuple[float | None, float | None] = domain
|
|
125
|
+
self._strict: bool = strict
|
|
126
|
+
self._method: Literal["linear", "intercept", "cut"] = method
|
|
127
|
+
|
|
128
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
129
|
+
left, right = self._domain
|
|
130
|
+
if left is None and right is None:
|
|
131
|
+
return x
|
|
132
|
+
r_l, r_r = x.min(), x.max()
|
|
133
|
+
match self._method:
|
|
134
|
+
case "linear":
|
|
135
|
+
if left is None or (left < r_l and not self._strict):
|
|
136
|
+
left = r_l
|
|
137
|
+
if right is None or (right > r_r and not self._strict):
|
|
138
|
+
right = r_r
|
|
139
|
+
numerator = right - left
|
|
140
|
+
if numerator == 0:
|
|
141
|
+
numerator = 1
|
|
142
|
+
denominator = r_r - r_l
|
|
143
|
+
if denominator == 0:
|
|
144
|
+
denominator = 1
|
|
145
|
+
return (x - r_l) * numerator / denominator + left
|
|
146
|
+
case "intercept":
|
|
147
|
+
if left is not None and right is None:
|
|
148
|
+
return x - r_l + left if r_l < left or self._strict else x
|
|
149
|
+
elif left is None and right is not None:
|
|
150
|
+
return x - r_r + right if r_r > right or self._strict else x
|
|
151
|
+
else:
|
|
152
|
+
raise ValueError("Cannot use intercept normalization when both ends are fixed")
|
|
153
|
+
case "cut":
|
|
154
|
+
if self._strict:
|
|
155
|
+
raise ValueError("Method \"cut\" cannot be strict")
|
|
156
|
+
if left is not None:
|
|
157
|
+
x[x < left] = left
|
|
158
|
+
if right is not None:
|
|
159
|
+
x[x > right] = right
|
|
160
|
+
return x
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class ColorizeLabel(nn.Module):
|
|
164
|
+
def __init__(self, *, colormap: Colormap | None = None) -> None:
|
|
165
|
+
super().__init__()
|
|
166
|
+
if not colormap:
|
|
167
|
+
colormap = []
|
|
168
|
+
for r in range(8):
|
|
169
|
+
for g in range(8):
|
|
170
|
+
for b in range(32):
|
|
171
|
+
colormap.append([r * 32, g * 32, 255 - b * 32])
|
|
172
|
+
self._colormap: torch.Tensor = torch.tensor(colormap)
|
|
173
|
+
|
|
174
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
175
|
+
cmap = self._colormap.to(x.device)
|
|
176
|
+
return (
|
|
177
|
+
torch.cat([cmap[(x > 0).int()].permute(2, 0, 1), x.unsqueeze(0)]) if 0 <= x.min() < x.max() <= 1
|
|
178
|
+
else cmap[x.int()].permute(2, 0, 1)
|
|
179
|
+
)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import nn
|
|
5
|
+
|
|
6
|
+
from mipcandy.metrics import do_reduction, soft_dice_coefficient
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FocalBCEWithLogits(nn.Module):
|
|
10
|
+
def __init__(self, alpha: float, gamma: float, *, reduction: Literal["mean", "sum", "none"] = "mean") -> None:
|
|
11
|
+
super().__init__()
|
|
12
|
+
self.alpha: float = alpha
|
|
13
|
+
self.gamma: float = gamma
|
|
14
|
+
self.reduction: Literal["mean", "sum", "none"] = reduction
|
|
15
|
+
|
|
16
|
+
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
|
|
17
|
+
bce = nn.functional.binary_cross_entropy_with_logits(logits, targets, reduction="none")
|
|
18
|
+
p = torch.sigmoid(logits)
|
|
19
|
+
p_t = torch.where(targets.bool(), p, 1 - p)
|
|
20
|
+
alpha_t = torch.where(targets.bool(), torch.as_tensor(self.alpha, device=logits.device), torch.as_tensor(
|
|
21
|
+
1 - self.alpha, device=logits.device))
|
|
22
|
+
loss = alpha_t * (1 - p_t).pow(self.gamma) * bce
|
|
23
|
+
return do_reduction(loss, self.reduction)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DiceBCELossWithLogits(nn.Module):
|
|
27
|
+
def __init__(self, num_classes: int, *, lambda_bce: float = .5, lambda_soft_dice: float = 1,
|
|
28
|
+
smooth: float = 1e-5) -> None:
|
|
29
|
+
super().__init__()
|
|
30
|
+
self.num_classes: int = num_classes
|
|
31
|
+
self.lambda_bce: float = lambda_bce
|
|
32
|
+
self.lambda_soft_dice: float = lambda_soft_dice
|
|
33
|
+
self.smooth: float = smooth
|
|
34
|
+
|
|
35
|
+
def forward(self, masks: torch.Tensor, labels: torch.Tensor) -> tuple[torch.Tensor, dict[str, float]]:
|
|
36
|
+
labels = labels.float()
|
|
37
|
+
bce = nn.functional.binary_cross_entropy_with_logits(masks, labels)
|
|
38
|
+
masks = masks.sigmoid()
|
|
39
|
+
soft_dice = soft_dice_coefficient(masks, labels, smooth=self.smooth)
|
|
40
|
+
c = self.lambda_bce * bce + self.lambda_soft_dice * (1 - soft_dice)
|
|
41
|
+
return c, {"soft dice": soft_dice.item(), "bce loss": bce.item()}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from typing import override
|
|
2
|
+
|
|
3
|
+
from torch import optim
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AbsoluteLinearLR(optim.lr_scheduler.LRScheduler):
|
|
7
|
+
"""
|
|
8
|
+
lr = kx + b
|
|
9
|
+
"""
|
|
10
|
+
def __init__(self, optimizer: optim.Optimizer, k: float, b: float, *, min_lr: float = 1e-6,
|
|
11
|
+
restart: bool = False, last_epoch: int = -1) -> None:
|
|
12
|
+
self._k: float = k
|
|
13
|
+
self._b: float = b
|
|
14
|
+
if min_lr < 0:
|
|
15
|
+
raise ValueError(f"`min_lr` must be positive, but got {min_lr}")
|
|
16
|
+
self._min_lr: float = min_lr
|
|
17
|
+
self._restart: bool = restart
|
|
18
|
+
self._restart_step: int = 0
|
|
19
|
+
super().__init__(optimizer, last_epoch)
|
|
20
|
+
|
|
21
|
+
def _interp(self, step: int) -> float:
|
|
22
|
+
step -= self._restart_step
|
|
23
|
+
r = self._k * step + self._b
|
|
24
|
+
if r < self._min_lr:
|
|
25
|
+
if self._restart:
|
|
26
|
+
self._restart_step = step
|
|
27
|
+
return self._interp(step)
|
|
28
|
+
return self._min_lr
|
|
29
|
+
return r
|
|
30
|
+
|
|
31
|
+
@override
|
|
32
|
+
def get_lr(self) -> list[float]:
|
|
33
|
+
target = self._interp(self.last_epoch)
|
|
34
|
+
return [target for _ in self.optimizer.param_groups]
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
from mipcandy.data.convertion import convert_ids_to_logits, convert_logits_to_ids
|
|
2
|
+
from mipcandy.data.dataset import Loader, UnsupervisedDataset, SupervisedDataset, DatasetFromMemory, MergedDataset, \
|
|
3
|
+
NNUNetDataset, BinarizedDataset
|
|
4
|
+
from mipcandy.data.geometric import ensure_num_dimensions, orthographic_views, aggregate_orthographic_views
|
|
5
|
+
from mipcandy.data.io import resample_to_isotropic, load_image, save_image
|
|
6
|
+
from mipcandy.data.visualization import visualize2d, visualize3d, overlay
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import nn
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def convert_ids_to_logits(ids: torch.Tensor, d: Literal[1, 2, 3], num_classes: int) -> torch.Tensor:
|
|
8
|
+
if ids.dtype != torch.int or ids.min() < 0:
|
|
9
|
+
raise TypeError("`ids` should be positive integers")
|
|
10
|
+
d += 1
|
|
11
|
+
if ids.ndim != d:
|
|
12
|
+
if ids.ndim == d + 1 and ids.shape[1] == 1:
|
|
13
|
+
ids = ids.squeeze(1)
|
|
14
|
+
else:
|
|
15
|
+
raise ValueError(f"`ids` should be {d} dimensional or {d + 1} dimensional with single channel")
|
|
16
|
+
return nn.functional.one_hot(ids.long(), num_classes).movedim(-1, 1).float()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def convert_logits_to_ids(logits: torch.Tensor, *, channel_dim: int = 1) -> torch.Tensor:
|
|
20
|
+
return logits.max(channel_dim).indices.int()
|