예제 #1
0
 def test_list_tuple(self):
     test_data = [[1, 2], [3, 4]]
     result = ToNumpy()(test_data)
     assert_allclose(result, np.asarray(test_data), type_test=False)
     test_data = ((1, 2), (3, 4))
     result = ToNumpy()(test_data)
     assert_allclose(result, np.asarray(test_data), type_test=False)
예제 #2
0
 def test_list_tuple(self):
     test_data = [[1, 2], [3, 4]]
     result = ToNumpy()(test_data)
     np.testing.assert_allclose(result, np.asarray(test_data))
     test_data = ((1, 2), (3, 4))
     result = ToNumpy()(test_data)
     np.testing.assert_allclose(result, np.asarray(test_data))
예제 #3
0
 def test_list_tuple(self):
     test_data = [[1, 2], [3, 4]]
     result = ToNumpy()(test_data)
     assert_allclose(result, np.asarray(test_data), type_test=False)
     test_data = ((1, 2), (3, 4))
     result = ToNumpy(wrap_sequence=False)(test_data)
     self.assertTrue(type(result), tuple)
     assert_allclose(result, ((np.asarray(1), np.asarray(2)),
                              (np.asarray(3), np.asarray(4))))
예제 #4
0
 def test_tensor_input(self):
     test_data = torch.tensor([[1, 2], [3, 4]])
     test_data = test_data.rot90()
     self.assertFalse(test_data.is_contiguous())
     result = ToNumpy()(test_data)
     self.assertTrue(isinstance(result, np.ndarray))
     self.assertTrue(result.flags["C_CONTIGUOUS"])
     np.testing.assert_allclose(result, test_data.numpy())
예제 #5
0
 def test_numpy_input(self):
     test_data = np.array([[1, 2], [3, 4]])
     test_data = np.rot90(test_data)
     self.assertFalse(test_data.flags["C_CONTIGUOUS"])
     result = ToNumpy()(test_data)
     self.assertTrue(isinstance(result, np.ndarray))
     self.assertTrue(result.flags["C_CONTIGUOUS"])
     np.testing.assert_allclose(result, test_data)
예제 #6
0
 def test_cupy_input(self):
     test_data = cp.array([[1, 2], [3, 4]])
     test_data = cp.rot90(test_data)
     self.assertFalse(test_data.flags["C_CONTIGUOUS"])
     result = ToNumpy()(test_data)
     self.assertTrue(isinstance(result, np.ndarray))
     self.assertTrue(result.flags["C_CONTIGUOUS"])
     assert_allclose(result, test_data.get(), type_test=False)
예제 #7
0
 def test_numpy_input(self):
     test_data = np.array([[1, 2], [3, 4]])
     test_data = np.rot90(test_data)
     self.assertFalse(test_data.flags["C_CONTIGUOUS"])
     result = ToNumpy(dtype="float32")(test_data)
     self.assertTrue(isinstance(result, np.ndarray))
     self.assertTrue(result.dtype == np.float32)
     self.assertTrue(result.flags["C_CONTIGUOUS"])
     assert_allclose(result, test_data, type_test=False)
예제 #8
0
    def initialize(self, args):
        """
        `initialize` is called only once when the model is being loaded.
        Implementing `initialize` function is optional. This function allows
        the model to intialize any state associated with this model.
        """

        # Pull model from google drive
        extract_dir = "/models/monai_covid/1"
        tar_save_path = os.path.join(extract_dir, model_filename)
        download_and_extract(gdrive_url,
                             tar_save_path,
                             output_dir=extract_dir,
                             hash_val=md5_check,
                             hash_type="md5")
        # load model configuration
        self.model_config = json.loads(args['model_config'])

        # create inferer engine and load PyTorch model
        inference_device_kind = args.get('model_instance_kind', None)
        logger.info(f"Inference device: {inference_device_kind}")

        self.inference_device = torch.device('cpu')
        if inference_device_kind is None or inference_device_kind == 'CPU':
            self.inference_device = torch.device('cpu')
        elif inference_device_kind == 'GPU':
            inference_device_id = args.get('model_instance_device_id', '0')
            logger.info(f"Inference device id: {inference_device_id}")

            if torch.cuda.is_available():
                self.inference_device = torch.device(
                    f'cuda:{inference_device_id}')
                cudnn.enabled = True
            else:
                logger.error(
                    f"No CUDA device detected. Using device: {inference_device_kind}"
                )

        # create pre-transforms
        self.pre_transforms = Compose([
            LoadImage(reader="NibabelReader",
                      image_only=True,
                      dtype=np.float32),
            AddChannel(),
            ScaleIntensityRange(a_min=-1000,
                                a_max=500,
                                b_min=0.0,
                                b_max=1.0,
                                clip=True),
            CropForeground(margin=5),
            Resize([192, 192, 64], mode="area"),
            AddChannel(),
            ToTensor(),
            Lambda(func=lambda x: x.to(device=self.inference_device)),
        ])

        # create post-transforms
        self.post_transforms = Compose([
            Lambda(func=lambda x: x.to(device="cpu")),
            Activations(sigmoid=True),
            ToNumpy(),
            AsDiscrete(threshold_values=True, logit_thresh=0.5),
        ])

        self.inferer = SimpleInferer()

        self.model = torch.jit.load(
            f'{pathlib.Path(os.path.realpath(__file__)).parent}{os.path.sep}covid19_model.ts',
            map_location=self.inference_device)
예제 #9
0
TEST_CASE_ARRAY_0 = [np.random.randn(3, 3)]
TEST_CASE_ARRAY_1 = [np.random.randn(3, 10, 10)]

TEST_CASE_DICT_0 = [{"image": np.random.randn(3, 3)}]
TEST_CASE_DICT_1 = [{"image": np.random.randn(3, 10, 10)}]

TEST_CASE_TORCH_0 = [torch.randn(3, 3)]
TEST_CASE_TORCH_1 = [torch.randn(3, 10, 10)]

TEST_CASE_WRAPPER = [np.random.randn(3, 10, 10)]

TEST_CASE_RECURSIVE_0 = [
    torch.randn(3, 3),
    Compose([
        ToNumpy(),
        Flip(),
        RandAdjustContrast(prob=0.0),
        RandFlip(prob=1.0),
        ToTensor()
    ]),
]
TEST_CASE_RECURSIVE_1 = [
    torch.randn(3, 3),
    Compose([
        ToNumpy(),
        Flip(),
        Compose([RandAdjustContrast(prob=0.0),
                 RandFlip(prob=1.0)]),
        ToTensor()
    ]),
예제 #10
0
 def test_single_value(self):
     for test_data in [5, np.array(5), torch.tensor(5)]:
         result = ToNumpy(dtype=np.uint8)(test_data)
         self.assertTrue(isinstance(result, np.ndarray))
         assert_allclose(result, np.asarray(test_data), type_test=False)
         self.assertEqual(result.ndim, 0)
예제 #11
0
    def _define_transforms(self):
        """Define and initialize all data transforms.

          * training set images transform
          * training set targets transform
          * validation set images transform
          * validation set targets transform
          * validation set images post-transform
          * test set images transform
          * test set targets transform
          * test set images post-transform
          * prediction set images transform
          * prediction set images post-transform

        @return True if data transforms could be instantiated, False otherwise.
        """
        # Define transforms for training
        self._train_image_transforms = Compose([
            LoadImage(image_only=True),
            ScaleIntensityRange(0, 65535, 0.0, 1.0, clip=False),
            AddChannel(),
            RandSpatialCrop(self._roi_size, random_size=False),
            RandRotate90(prob=0.5, spatial_axes=(0, 1)),
            ToTensor()
        ])
        self._train_target_transforms = Compose([
            LoadImage(image_only=True),
            ScaleIntensityRange(0, 65535, 0.0, 1.0, clip=False),
            AddChannel(),
            RandSpatialCrop(self._roi_size, random_size=False),
            RandRotate90(prob=0.5, spatial_axes=(0, 1)),
            ToTensor()
        ])

        # Define transforms for validation
        self._validation_image_transforms = Compose([
            LoadImage(image_only=True),
            ScaleIntensityRange(0, 65535, 0.0, 1.0, clip=False),
            AddChannel(),
            ToTensor()
        ])
        self._validation_target_transforms = Compose([
            LoadImage(image_only=True),
            ScaleIntensityRange(0, 65535, 0.0, 1.0, clip=False),
            AddChannel(),
            ToTensor()
        ])

        # Define transforms for testing
        self._test_image_transforms = Compose([
            LoadImage(image_only=True),
            ScaleIntensityRange(0, 65535, 0.0, 1.0, clip=False),
            AddChannel(),
            ToTensor()
        ])
        self._test_target_transforms = Compose([
            LoadImage(image_only=True),
            ScaleIntensityRange(0, 65535, 0.0, 1.0, clip=False),
            AddChannel(),
            ToTensor()
        ])

        # Define transforms for prediction
        self._prediction_image_transforms = Compose(
            [LoadImage(image_only=True),
             AddChannel(),
             ToTensor()])

        # Post transforms
        self._validation_post_transforms = Compose([Identity()])

        self._test_post_transforms = Compose(
            [ToNumpy(), ScaleIntensity(0, 65535)])

        self._prediction_post_transforms = Compose(
            [ToNumpy(), ScaleIntensity(0, 65535)])