Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
177 commits
Select commit Hold shift + click to select a range
eeabbb4
Add a data analysis module to report the composition of a given datas…
mingxin-zheng Jul 26, 2022
e492de8
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Jul 26, 2022
3f186c8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 26, 2022
918bc86
Exclude auto3d test from min_tests
mingxin-zheng Jul 27, 2022
e2f4c5f
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Jul 27, 2022
2481198
fix: change device for cpu-only environment
mingxin-zheng Jul 27, 2022
b616943
fix: change num of workers in MacOS and Win32
mingxin-zheng Jul 27, 2022
5fbbdfe
format autofix
mingxin-zheng Jul 28, 2022
b883c6e
fix: format args doc-string and other required by flake8-py3
mingxin-zheng Jul 28, 2022
c88ca0f
fix format: type annotation, dict format
mingxin-zheng Jul 29, 2022
4270696
fix: package error
mingxin-zheng Aug 2, 2022
2ae3518
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 2, 2022
2a3cfb6
fix: autofix deletes empty lines
mingxin-zheng Aug 2, 2022
2494f3c
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 2, 2022
b604466
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 2, 2022
a1055d8
fix: style
mingxin-zheng Aug 3, 2022
61ec647
fix style, improve documentations, and move/remove functions
mingxin-zheng Aug 4, 2022
f2414c3
fix type assignment error
mingxin-zheng Aug 5, 2022
56bbc32
add example code blocks, fix typo, and change use of tempfile
mingxin-zheng Aug 5, 2022
58529d0
refractor: unit test setUp and tearDown methods
mingxin-zheng Aug 5, 2022
dcaca87
fix: dict copy issue and rename unit tests for future reuse
mingxin-zheng Aug 5, 2022
96175ff
fix min_test
mingxin-zheng Aug 10, 2022
18082ba
fix from 4854-quantile
mingxin-zheng Aug 10, 2022
0ae3ac2
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 10, 2022
3daae65
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 10, 2022
2dc9e2e
fix: unify operation, Doc-strings for input label, and replace lambda…
mingxin-zheng Aug 10, 2022
43335a5
add google fire to call the DataAnalyzer module in CLI
mingxin-zheng Aug 10, 2022
2c9275e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 10, 2022
aa0cefb
fix: fire usage
mingxin-zheng Aug 10, 2022
3495aa5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 10, 2022
8077f95
revert autofix that removes the fire dependency
mingxin-zheng Aug 10, 2022
ac8e7ec
manual merge with dev
mingxin-zheng Aug 10, 2022
4800952
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 10, 2022
2085afe
fix: avoid import from being deleted by pre-commit.ci hool
mingxin-zheng Aug 11, 2022
9d9b9e5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 10, 2022
9d3704b
fix fire test
mingxin-zheng Aug 11, 2022
f8b4ddc
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 11, 2022
8248ed6
fix import
mingxin-zheng Aug 11, 2022
53b5f58
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 11, 2022
094f35d
fix: merge dev docstring into the current branch
mingxin-zheng Aug 11, 2022
0aa05dc
fix: format
mingxin-zheng Aug 11, 2022
0618da5
fix docstrings
mingxin-zheng Aug 12, 2022
e51777a
fix docstrings
mingxin-zheng Aug 12, 2022
9cb81a4
Update monai/apps/auto3d/data_analyzer.py
mingxin-zheng Aug 12, 2022
f9ec857
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 12, 2022
e46fced
fix docstrings
mingxin-zheng Aug 12, 2022
2596edd
fix docstrings for nan/inf
mingxin-zheng Aug 12, 2022
a359282
add missing key handling
mingxin-zheng Aug 12, 2022
f998222
fix _ usage and docstring
mingxin-zheng Aug 12, 2022
d3ad118
fix var name update
mingxin-zheng Aug 12, 2022
8f97b3e
add warning for users when output_path file exists
mingxin-zheng Aug 12, 2022
c90a289
add optional argument definitions
mingxin-zheng Aug 12, 2022
e7ca379
fix format
mingxin-zheng Aug 12, 2022
b8d91e4
add optional argument image_only
mingxin-zheng Aug 12, 2022
52b9bfe
fix optional remove
mingxin-zheng Aug 12, 2022
cb1bbb2
fix docstring
mingxin-zheng Aug 12, 2022
0ef823b
fix error raising condition and set average to True by default
mingxin-zheng Aug 13, 2022
43f36b1
misc fix: output type definition
mingxin-zheng Aug 13, 2022
adea43b
fix docstring for fire usage
mingxin-zheng Aug 13, 2022
ec22f2b
add unit test to read datalist from .json file
mingxin-zheng Aug 13, 2022
62d67ec
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 15, 2022
b5c9076
fix docstrings
mingxin-zheng Aug 12, 2022
963493c
fix docstrings
mingxin-zheng Aug 12, 2022
51953c7
fix docstrings
mingxin-zheng Aug 12, 2022
e098454
fix docstrings for nan/inf
mingxin-zheng Aug 12, 2022
99a386e
add missing key handling
mingxin-zheng Aug 12, 2022
6b07836
fix _ usage and docstring
mingxin-zheng Aug 12, 2022
633f189
fix var name update
mingxin-zheng Aug 12, 2022
ea76967
add warning for users when output_path file exists
mingxin-zheng Aug 12, 2022
8de2085
add optional argument definitions
mingxin-zheng Aug 12, 2022
14dc3ca
fix format
mingxin-zheng Aug 12, 2022
acc2044
add optional argument image_only
mingxin-zheng Aug 12, 2022
36404c4
fix optional remove
mingxin-zheng Aug 12, 2022
1f6afc2
fix docstring
mingxin-zheng Aug 12, 2022
2d5d929
fix error raising condition and set average to True by default
mingxin-zheng Aug 13, 2022
97bad4c
misc fix: output type definition
mingxin-zheng Aug 13, 2022
645d825
fix docstring for fire usage
mingxin-zheng Aug 13, 2022
3696c0f
add unit test to read datalist from .json file
mingxin-zheng Aug 13, 2022
718c16b
233 - set up a backward compatibility policy (#4857)
wyli Aug 11, 2022
108c009
4862 Enhance docstring for the regular 2D image dims (#4892)
Nic-Ma Aug 11, 2022
1211bf2
4754 default ToTensor.track_meta to None (#4874)
wyli Aug 11, 2022
60489d5
fix(VnetInputTransition): added custom out channels (#4895)
a-parida12 Aug 11, 2022
be2d420
4846 send weight differences (#4876)
holgerroth Aug 11, 2022
b49d455
Add flexible unet for encoder-decoder structure (#4801)
binliunls Aug 12, 2022
d10f064
e2e-varnet (#4853)
mersad95zd Aug 12, 2022
9e2a18c
Add dummy filter and base class for FL (#4899)
holgerroth Aug 12, 2022
a3967f9
4907 invertd for resizing same spatial shapes (#4908)
wyli Aug 14, 2022
f429379
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 15, 2022
3eab8ad
fix: allow user to define their image/label keys
mingxin-zheng Aug 15, 2022
9a739ca
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 15, 2022
3c360ef
fix: allow user to define image/label keys
mingxin-zheng Aug 15, 2022
c49c3c0
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 15, 2022
3657228
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 15, 2022
db09f96
add gpu version of ccp
mingxin-zheng Aug 15, 2022
c91eaf3
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 15, 2022
ed0d855
add warning if the spacing of the images is not constant
mingxin-zheng Aug 15, 2022
9e7024e
fix docstring and argument list input
mingxin-zheng Aug 15, 2022
10d5dc5
fix: type check
mingxin-zheng Aug 15, 2022
db2a971
fix type hint
mingxin-zheng Aug 15, 2022
b7bde01
fix flake8
mingxin-zheng Aug 15, 2022
d213e97
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 15, 2022
c302678
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 15, 2022
4ce73bc
fix flake8
mingxin-zheng Aug 15, 2022
e8c95db
fix prev breaking change
mingxin-zheng Aug 15, 2022
e38585d
move from apps/auto3d to auto3dseg
mingxin-zheng Aug 16, 2022
94c1c87
fix test_module_list
mingxin-zheng Aug 16, 2022
b584908
Merge branch 'dev' into auto3d-1.0
Nic-Ma Aug 16, 2022
937fdad
fix docstring
mingxin-zheng Aug 16, 2022
ac2d689
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 16, 2022
699fdcb
misc fix whitespace
mingxin-zheng Aug 16, 2022
0634ab3
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 16, 2022
5359741
update monai/README.md
mingxin-zheng Aug 16, 2022
45fba8d
fix build-doc
mingxin-zheng Aug 16, 2022
ff09fcd
move auto3dseg from monai to monai.apps
mingxin-zheng Aug 16, 2022
78492e2
Merge branch 'dev' into auto3d-1.0
wyli Aug 16, 2022
22080cb
fix bugs that cause wrong datastats numbers
mingxin-zheng Aug 17, 2022
c296dbe
refactor data analyzer
mingxin-zheng Aug 22, 2022
decf6dd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 22, 2022
6b2f99d
refractor: break into smaller scripts
mingxin-zheng Aug 22, 2022
317a661
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 22, 2022
5e352e6
refractor remove duplicated function defs
mingxin-zheng Aug 22, 2022
f9c26b4
refactor remove duplicate function defs concat_np/concat_dict
mingxin-zheng Aug 22, 2022
ae60295
refractor unify numerics retrieval methods in utils
mingxin-zheng Aug 22, 2022
e2921de
fix to allow no label key / image_only
mingxin-zheng Aug 22, 2022
6b62640
autofix
mingxin-zheng Aug 22, 2022
6a49a0e
refractor make AnalyzeEngine callable and remove data from init
mingxin-zheng Aug 22, 2022
ed8b6c9
add docstring and unit tests for analyzer
mingxin-zheng Aug 23, 2022
6172a0e
fix MapTranform init for Analyzer
mingxin-zheng Aug 23, 2022
b10f153
add unit tests for Analyzer and move datafold_read to util.py
mingxin-zheng Aug 23, 2022
b332a49
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 23, 2022
a08a6e7
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 23, 2022
e5266c3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 23, 2022
2d80747
fix missing MetaTensor support in unified operations
mingxin-zheng Aug 23, 2022
7dabc0c
add docstrings and unit tests for case analyzers
mingxin-zheng Aug 23, 2022
c0ef5f7
add docstring, unit tests, minor refractoring
mingxin-zheng Aug 23, 2022
9147b45
extend numpy operations for list object (in addition to nd.ndarray)
mingxin-zheng Aug 23, 2022
c0941cf
force numerical values in basic types and list
mingxin-zheng Aug 23, 2022
5d0afde
fix StrEnum key can not be written to yaml
mingxin-zheng Aug 23, 2022
128d89a
misc fix StrEnum key can not be written to yaml
mingxin-zheng Aug 23, 2022
b49151c
misc fix for pixel_percentage
mingxin-zheng Aug 23, 2022
19df805
fix report results and StrEnums for data_analyzer
mingxin-zheng Aug 23, 2022
8150bd0
autofix
mingxin-zheng Aug 24, 2022
eb7fb87
add docstring and unit tests for operations
mingxin-zheng Aug 24, 2022
3e5c655
make AnalyzerEngine a subclass of Compose
mingxin-zheng Aug 24, 2022
665d457
Merge branch 'dev' into auto3d-1.0
mingxin-zheng Aug 24, 2022
2fe02f5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 24, 2022
69dee73
add docstring
mingxin-zheng Aug 24, 2022
383829d
autofix, rename case engine to SegSummarizer
mingxin-zheng Aug 24, 2022
79e5d9d
rename
mingxin-zheng Aug 24, 2022
7720628
fix flake
mingxin-zheng Aug 24, 2022
5be9720
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 24, 2022
06aba86
fix format
mingxin-zheng Aug 24, 2022
9c2bfc0
fix hint
mingxin-zheng Aug 24, 2022
d80e660
fix flake
mingxin-zheng Aug 25, 2022
13a9af1
fix type hints
mingxin-zheng Aug 25, 2022
db3536d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 25, 2022
e689ce4
autofix
mingxin-zheng Aug 25, 2022
a4f3337
fix mypy
mingxin-zheng Aug 25, 2022
fea21b9
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 25, 2022
a98fa39
adds doc pages
wyli Aug 25, 2022
2362889
misc fixes
mingxin-zheng Aug 25, 2022
725b43c
Merge branch 'auto3d-1.0' of https://github.com/mingxin-zheng/MONAI i…
mingxin-zheng Aug 25, 2022
754b0b9
pass average to seg_summarizer and fix do_ccp
mingxin-zheng Aug 25, 2022
1aa005c
misc fix and docstring update
mingxin-zheng Aug 26, 2022
bb02d7d
misc fix: seperate test script, folder, and add error checking for de…
mingxin-zheng Aug 26, 2022
f138cdb
misc fix, add yaml strEnum representer
mingxin-zheng Aug 26, 2022
302c5bc
misc fix on mintests
mingxin-zheng Aug 26, 2022
99e2168
misc duplicate module names
mingxin-zheng Aug 26, 2022
01bb412
misc mintests
mingxin-zheng Aug 26, 2022
5be7ad3
Merge pull request #1 from wyli/auto3d-1.0
mingxin-zheng Aug 26, 2022
7802e02
fix min_test err
mingxin-zheng Aug 26, 2022
6f4f324
Merge branch 'dev' into auto3d-1.0
wyli Aug 26, 2022
faed367
update docs
wyli Aug 26, 2022
40957f7
Merge branch 'dev' into auto3d-1.0
wyli Aug 26, 2022
8e98c4c
fixes pickle
wyli Aug 26, 2022
3c53a99
Merge remote-tracking branch 'upstream/dev' into auto3d-1.0
wyli Aug 26, 2022
a520b05
fixes mypy error
wyli Aug 26, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ API Reference
:maxdepth: 1

apps
auto3dseg
fl
bundle
transforms
Expand Down
7 changes: 7 additions & 0 deletions docs/source/apps.rst
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,10 @@ Applications
`ComplexConj`
~~~~~~~~~~~~~
.. autofunction:: monai.apps.reconstruction.complex_utils.complex_conj

`auto3dseg`
-----------

.. automodule:: monai.apps.auto3dseg.data_analyzer
:members:
:imported-members:
10 changes: 10 additions & 0 deletions docs/source/auto3dseg.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
:github_url: https://github.com/Project-MONAI/MONAI

.. _auto3dseg:

auto3dseg
=========

.. automodule:: monai.auto3dseg
:members:
:imported-members:
1 change: 1 addition & 0 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"utils",
"inferers",
"optimizers",
"auto3dseg",
]


Expand Down
2 changes: 2 additions & 0 deletions monai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

* **apps**: high level medical domain specific deep learning applications.

* **auto3dseg**: automated machine learning (AutoML) components for volumetric image analysis.

* **bundle**: components to build the portable self-descriptive model bundle.

* **config**: for system configuration and diagnostic output.
Expand Down
1 change: 1 addition & 0 deletions monai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@

__all__ = [
"apps",
"auto3dseg",
"bundle",
"config",
"data",
Expand Down
10 changes: 10 additions & 0 deletions monai/apps/auto3dseg/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
19 changes: 19 additions & 0 deletions monai/apps/auto3dseg/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from monai.apps.auto3dseg.data_analyzer import DataAnalyzer

if __name__ == "__main__":
from monai.utils import optional_import

fire, _ = optional_import("fire")
fire.Fire({"DataAnalyzer": DataAnalyzer})
239 changes: 239 additions & 0 deletions monai/apps/auto3dseg/data_analyzer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import warnings
from os import path
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from monai.apps.utils import get_logger
from monai.auto3dseg import SegSummarizer
from monai.auto3dseg.utils import datafold_read
from monai.bundle import config_parser
from monai.bundle.config_parser import ConfigParser
from monai.data import DataLoader, Dataset
from monai.data.utils import no_collation
from monai.transforms import (
Compose,
EnsureChannelFirstd,
EnsureTyped,
Lambdad,
LoadImaged,
Orientationd,
SqueezeDimd,
ToDeviced,
)
from monai.utils import StrEnum, min_version, optional_import
from monai.utils.enums import DataStatsKeys, ImageStatsKeys


def strenum_representer(dumper, data):
return dumper.represent_scalar("tag:yaml.org,2002:str", data.value)


config_parser.yaml.SafeDumper.add_multi_representer(StrEnum, strenum_representer)

tqdm, has_tqdm = optional_import("tqdm", "4.47.0", min_version, "tqdm")
logger = get_logger(module_name=__name__)

__all__ = ["DataAnalyzer"]


def _argmax_if_multichannel(x):
return torch.argmax(x, dim=0, keepdim=True) if x.shape[0] > 1 else x


class DataAnalyzer:
"""
The DataAnalyzer automatically analyzes given medical image dataset and reports the statistics.
The module expects file paths to the image data and utilizes the LoadImaged transform to read the
files, which supports nii, nii.gz, png, jpg, bmp, npz, npy, and dcm formats. Currently, only
segmentation task is supported, so the user needs to provide paths to the image and label files
(if have). Also, label data format is preferred to be (1,H,W,D), with the label index in the
first dimension. If it is in onehot format, it will be converted to the preferred format.

Args:
datalist: a Python dictionary storing group, fold, and other information of the medical
image dataset, or a string to the JSON file storing the dictionary.
dataroot: user's local directory containing the datasets.
output_path: path to save the analysis result.
average: whether to average the statistical value across different image modalities.
do_ccp: apply the connected component algorithm to process the labels/images
device: a string specifying hardware (CUDA/CPU) utilized for the operations.
worker: number of workers to use for parallel processing. If device is cuda/GPU, worker has
to be 0.
image_key: a string that user specify for the image. The DataAnalyzer will look it up in the
datalist to locate the image files of the dataset.
label_key: a string that user specify for the label. The DataAnalyzer will look it up in the
datalist to locate the label files of the dataset. If label_key is None, the DataAnalyzer
will skip looking for labels and all label-related operations.

Raises:
ValueError if device is GPU and worker > 0.

Examples:
.. code-block:: python

from monai.apps.auto3dseg.data_analyzer import DataAnalyzer

datalist = {
"testing": [{"image": "image_003.nii.gz"}],
"training": [
{"fold": 0, "image": "image_001.nii.gz", "label": "label_001.nii.gz"},
{"fold": 0, "image": "image_002.nii.gz", "label": "label_002.nii.gz"},
{"fold": 1, "image": "image_001.nii.gz", "label": "label_001.nii.gz"},
{"fold": 1, "image": "image_004.nii.gz", "label": "label_004.nii.gz"},
],
}

dataroot = '/datasets' # the directory where you have the image files (nii.gz)
DataAnalyzer(datalist, dataroot)

Notes:
The module can also be called from the command line interface (CLI).

For example:

.. code-block:: bash

python -m monai.apps.auto3dseg \\
DataAnalyzer \\
get_all_case_stats \\
--datalist="my_datalist.json" \\
--dataroot="my_dataroot_dir"

"""

def __init__(
self,
datalist: Union[str, Dict],
dataroot: str = "",
output_path: str = "./data_stats.yaml",
average: bool = True,
do_ccp: bool = True,
device: Union[str, torch.device] = "cuda",
worker: int = 0,
image_key: str = "image",
label_key: Optional[str] = "label",
):
if path.isfile(output_path):
warnings.warn(f"File {output_path} already exists and will be overwritten.")
logger.debug(f"{output_path} will be overwritten by a new datastat.")

self.datalist = datalist
self.dataroot = dataroot
self.output_path = output_path
self.average = average
self.do_ccp = do_ccp
self.device = torch.device(device)
self.worker = worker
self.image_key = image_key
self.label_key = label_key

if (self.device.type == "cuda") and (worker > 0):
raise ValueError("CUDA does not support multiple subprocess. If device is GPU, please set worker to 0")

@staticmethod
def _check_data_uniformity(keys: List[str], result: Dict):
"""
Check data uniformity since DataAnalyzer provides no support to multi-modal images with different
affine matrices/spacings due to monai transforms.

Args:
keys: a list of string-type keys under image_stats dictionary.

Returns:
False if one of the selected key values is not constant across the dataset images.

"""

constant_props = [result[DataStatsKeys.SUMMARY][DataStatsKeys.IMAGE_STATS][key] for key in keys]
for prop in constant_props:
if "stdev" in prop and np.any(prop["stdev"]):
return False

return True

def get_all_case_stats(self):
"""
Get all case stats. Caller of the DataAnalyser class. The function iterates datalist and
call get_case_stats to generate stats. Then get_case_summary is called to combine results.

Returns:
A data statistics dictionary containing
"stats_summary" (summary statistics of the entire datasets). Within stats_summary
there are "image_stats" (summarizing info of shape, channel, spacing, and etc
using operations_summary), "image_foreground_stats" (info of the intensity for the
non-zero labeled voxels), and "label_stats" (info of the labels, pixel percentage,
image_intensity, and each individual label in a list)
"stats_by_cases" (List type value. Each element of the list is statistics of
an image-label info. Within each element, there are: "image" (value is the
path to an image), "label" (value is the path to the corresponding label), "image_stats"
(summarizing info of shape, channel, spacing, and etc using operations),
"image_foreground_stats" (similar to the previous one but one foreground image), and
"label_stats" (stats of the individual labels )

Notes:
Since the backend of the statistics computation are torch/numpy, nan/inf value
may be generated and carried over in the computation. In such cases, the output
dictionary will include .nan/.inf in the statistics.

"""
summarizer = SegSummarizer(self.image_key, self.label_key, average=self.average, do_ccp=self.do_ccp)
keys = list(filter(None, [self.image_key, self.label_key]))
transform_list = [
LoadImaged(keys=keys),
EnsureChannelFirstd(keys=keys), # this creates label to be (1,H,W,D)
Orientationd(keys=keys, axcodes="RAS"),
EnsureTyped(keys=keys, data_type="tensor"),
Lambdad(keys=self.label_key, func=_argmax_if_multichannel) if self.label_key else None,
SqueezeDimd(keys=["label"], dim=0) if self.label_key else None,
ToDeviced(keys=keys, device=self.device),
summarizer,
]

transform = Compose(transforms=list(filter(None, transform_list)))

files, _ = datafold_read(datalist=self.datalist, basedir=self.dataroot, fold=-1)
dataset = Dataset(data=files, transform=transform)
dataloader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=self.worker, collate_fn=no_collation)
result = {DataStatsKeys.SUMMARY: {}, DataStatsKeys.BY_CASE: []}
if not has_tqdm:
warnings.warn("tqdm is not installed. not displaying the caching progress.")

for batch_data in tqdm(dataloader) if has_tqdm else dataloader:
# d = transform(batch_data[0])
d = batch_data[0]
stats_by_cases = {
DataStatsKeys.BY_CASE_IMAGE_PATH: d[DataStatsKeys.BY_CASE_IMAGE_PATH],
DataStatsKeys.BY_CASE_LABEL_PATH: d[DataStatsKeys.BY_CASE_LABEL_PATH],
DataStatsKeys.IMAGE_STATS: d[DataStatsKeys.IMAGE_STATS],
}

if self.label_key is not None:
stats_by_cases.update(
{
DataStatsKeys.FG_IMAGE_STATS: d[DataStatsKeys.FG_IMAGE_STATS],
DataStatsKeys.LABEL_STATS: d[DataStatsKeys.LABEL_STATS],
}
)
result[DataStatsKeys.BY_CASE].append(stats_by_cases)

result[DataStatsKeys.SUMMARY] = summarizer.summarize(result[DataStatsKeys.BY_CASE])

if not self._check_data_uniformity([ImageStatsKeys.SPACING], result):
logger.warning("Data is not completely uniform. MONAI transforms may provide unexpected result")

ConfigParser.export_config_file(result, self.output_path, fmt="yaml", default_flow_style=None)

return result
31 changes: 31 additions & 0 deletions monai/auto3dseg/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from .analyzer import (
FgImageStats,
FgImageStatsSumm,
FilenameStats,
ImageStats,
ImageStatsSumm,
LabelStats,
LabelStatsSumm,
)
from .operations import Operations, SampleOperations, SummaryOperations
from .seg_summarizer import SegSummarizer
from .utils import (
concat_multikeys_to_dict,
concat_val_to_np,
datafold_read,
get_foreground_image,
get_foreground_label,
get_label_ccp,
verify_report_format,
)
Loading