class_docstr: 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 loading datasets in each GPU/CPU sub-process.
      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 NoneType or "None",
          the DataAnalyzer will skip looking for labels and all label-related operations.
      hist_bins: bins to compute histogram for each image channel.
      hist_range: ranges to compute histogram for each image channel.
      fmt: format used to save the analysis results. Currently support ``"json"`` and ``"yaml"``, defaults to "yaml".
      histogram_only: whether to only compute histograms. Defaults to False.
      extra_params: other optional arguments. Currently supported arguments are :
          'allowed_shape_difference' (default 5) can be used to change the default tolerance of
          the allowed shape differences between the image and label items. In case of shape mismatch below
          the tolerance, the label image will be resized to match the image using nearest interpolation.
  
  
  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"
class_docstr_tok: ["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","loading","datasets","in","each","GPU\/CPU","sub-process",".","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","NoneType","or","``","None","''",",","the","DataAnalyzer","will","skip","looking","for","labels","and","all","label-related","operations",".","hist_bins",":","bins","to","compute","histogram","for","each","image","channel",".","hist_range",":","ranges","to","compute","histogram","for","each","image","channel",".","fmt",":","format","used","to","save","the","analysis","results",".","Currently","support","``","``","json","''","``","and","``","``","yaml","''","``",",","defaults","to","``","yaml","''",".","histogram_only",":","whether","to","only","compute","histograms",".","Defaults","to","False",".","extra_params",":","other","optional","arguments",".","Currently","supported","arguments","are",":","'allowed_shape_difference","'","(","default","5",")","can","be","used","to","change","the","default","tolerance","of","the","allowed","shape","differences","between","the","image","and","label","items",".","In","case","of","shape","mismatch","below","the","tolerance",",","the","label","image","will","be","resized","to","match","the","image","using","nearest","interpolation",".","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","''"]
docstr: Get all case stats. Caller of the DataAnalyser class. The function initiates multiple GPU or CPU processes of the internal
  _get_all_case_stats functions, which iterates datalist and call SegSummarizer to generate stats for each case.
  After all case stats are generated, SegSummarizer is called to combine results.
  
  Args:
      key: dataset key
      transform_list: option list of transforms before SegSummarizer
  
  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.
docstr_tok: ["Get","all","case","stats",".","Caller","of","the","DataAnalyser","class",".","The","function","initiates","multiple","GPU","or","CPU","processes","of","the","internal","_get_all_case_stats","functions",",","which","iterates","datalist","and","call","SegSummarizer","to","generate","stats","for","each","case",".","After","all","case","stats","are","generated",",","SegSummarizer","is","called","to","combine","results",".","Args",":","key",":","dataset","key","transform_list",":","option","list","of","transforms","before","SegSummarizer","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","."]
code: def get_all_case_stats(self, key="training", transform_list=None):
      """
      Get all case stats. Caller of the DataAnalyser class. The function initiates multiple GPU or CPU processes of the internal
      _get_all_case_stats functions, which iterates datalist and call SegSummarizer to generate stats for each case.
      After all case stats are generated, SegSummarizer is called to combine results.
  
      Args:
          key: dataset key
          transform_list: option list of transforms before SegSummarizer
  
      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.
  
      """
      result: dict[DataStatsKeys, Any] = {
          DataStatsKeys.SUMMARY: {},
          DataStatsKeys.BY_CASE: [],
      }
      result_bycase: dict[DataStatsKeys, Any] = {
          DataStatsKeys.SUMMARY: {},
          DataStatsKeys.BY_CASE: [],
      }
      if self.device.type == "cpu":
          nprocs = 1
          logger.info("Using CPU for data analyzing!")
      else:
          nprocs = torch.cuda.device_count()
          logger.info(f"Found {nprocs} GPUs for data analyzing!")
      if nprocs > 1:
          tmp_ctx: Any = get_context("forkserver")
          with tmp_ctx.Manager() as manager:
              manager_list = manager.list()
              processes = []
              for rank in range(nprocs):
                  p = tmp_ctx.Process(
                      target=self._get_all_case_stats,
                      args=(
                          rank,
                          nprocs,
                          manager_list,
                          key,
                          transform_list,
                      ),
                  )
                  processes.append(p)
              for p in processes:
                  p.start()
              for p in processes:
                  p.join()
              # merge DataStatsKeys.BY_CASE
              for _ in manager_list:
                  result_bycase[DataStatsKeys.BY_CASE].extend(
                      _[DataStatsKeys.BY_CASE]
                  )
      else:
          result_bycase = self._get_all_case_stats(
              0, 1, None, key, transform_list
          )
  
      summarizer = SegSummarizer(
          self.image_key,
          self.label_key,
          average=self.average,
          do_ccp=self.do_ccp,
          hist_bins=self.hist_bins,
          hist_range=self.hist_range,
          histogram_only=self.histogram_only,
      )
      n_cases = len(result_bycase[DataStatsKeys.BY_CASE])
      result[DataStatsKeys.SUMMARY] = summarizer.summarize(
          cast(list, result_bycase[DataStatsKeys.BY_CASE])
      )
      result[DataStatsKeys.SUMMARY]["n_cases"] = n_cases
      result_bycase[DataStatsKeys.SUMMARY] = result[
          DataStatsKeys.SUMMARY
      ]
      if not self._check_data_uniformity(
          [ImageStatsKeys.SPACING], result
      ):
          logger.info(
              "Data spacing is not completely uniform. MONAI transforms may provide unexpected result"
          )
      if self.output_path:
          logger.info(f"Writing data stats to {self.output_path}.")
          ConfigParser.export_config_file(
              result,
              self.output_path,
              fmt=self.fmt,
              default_flow_style=None,
              sort_keys=False,
          )
          by_case_path = self.output_path.replace(
              f".{self.fmt}", f"_by_case.{self.fmt}"
          )
          if (
              by_case_path == self.output_path
          ):  # self.output_path not ended with self.fmt?
              by_case_path += f".by_case.{self.fmt}"
          logger.info(
              f"Writing by-case data stats to {by_case_path}, this may take a while."
          )
          ConfigParser.export_config_file(
              result_bycase,
              by_case_path,
              fmt=self.fmt,
              default_flow_style=None,
              sort_keys=False,
          )
      # release memory
      if self.device.type == "cuda":
          # release unreferenced tensors to mitigate OOM
          # limitation: https://github.com/pytorch/pytorch/issues/12873#issuecomment-482916237
          torch.cuda.empty_cache()
      result[DataStatsKeys.BY_CASE] = result_bycase[
          DataStatsKeys.BY_CASE
      ]
      return result
  
imports: from __future__ import annotations
  import warnings
  from os import path
  from typing import Any, cast
  import numpy
  import torch
  from torch.multiprocessing import get_context
  from monai.apps.auto3dseg.transforms import EnsureSameShaped
  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, partition_dataset
  from monai.data.utils import no_collation
  from monai.transforms import Compose, EnsureTyped, LoadImaged, Orientationd
  from monai.utils import ImageMetaKey, StrEnum, min_version, optional_import
  from monai.utils.enums import DataStatsKeys, ImageStatsKeys
label_desc: Use image node_id 3 for calling the DataAnalyzer obj's underlying member method code with example usage: obj.get_all_case_stats(key, transform_list) and returns: result