monai-weekly 1.5.dev2506__py3-none-any.whl → 1.5.dev2507__py3-none-any.whl
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.
- monai/__init__.py +1 -1
- monai/_version.py +3 -3
- monai/apps/auto3dseg/transforms.py +1 -4
- monai/data/utils.py +6 -13
- monai/inferers/utils.py +1 -2
- monai/losses/dice.py +2 -14
- monai/losses/ds_loss.py +1 -3
- monai/networks/layers/simplelayers.py +2 -14
- monai/networks/utils.py +4 -16
- monai/transforms/compose.py +28 -11
- monai/transforms/croppad/array.py +1 -6
- monai/transforms/io/array.py +0 -1
- monai/transforms/transform.py +15 -6
- monai/transforms/utils.py +1 -2
- monai/utils/tf32.py +0 -10
- monai/visualize/class_activation_maps.py +5 -8
- {monai_weekly-1.5.dev2506.dist-info → monai_weekly-1.5.dev2507.dist-info}/METADATA +2 -2
- monai_weekly-1.5.dev2507.dist-info/RECORD +1181 -0
- {monai_weekly-1.5.dev2506.dist-info → monai_weekly-1.5.dev2507.dist-info}/top_level.txt +1 -0
- tests/apps/__init__.py +10 -0
- tests/apps/deepedit/__init__.py +10 -0
- tests/apps/deepedit/test_deepedit_transforms.py +314 -0
- tests/apps/deepgrow/__init__.py +10 -0
- tests/apps/deepgrow/test_deepgrow_dataset.py +109 -0
- tests/apps/deepgrow/transforms/__init__.py +10 -0
- tests/apps/deepgrow/transforms/test_deepgrow_interaction.py +97 -0
- tests/apps/deepgrow/transforms/test_deepgrow_transforms.py +556 -0
- tests/apps/detection/__init__.py +10 -0
- tests/apps/detection/metrics/__init__.py +10 -0
- tests/apps/detection/metrics/test_detection_coco_metrics.py +69 -0
- tests/apps/detection/networks/__init__.py +10 -0
- tests/apps/detection/networks/test_retinanet.py +210 -0
- tests/apps/detection/networks/test_retinanet_detector.py +203 -0
- tests/apps/detection/test_box_transform.py +370 -0
- tests/apps/detection/utils/__init__.py +10 -0
- tests/apps/detection/utils/test_anchor_box.py +88 -0
- tests/apps/detection/utils/test_atss_box_matcher.py +46 -0
- tests/apps/detection/utils/test_box_coder.py +43 -0
- tests/apps/detection/utils/test_detector_boxselector.py +67 -0
- tests/apps/detection/utils/test_detector_utils.py +96 -0
- tests/apps/detection/utils/test_hardnegsampler.py +54 -0
- tests/apps/nuclick/__init__.py +10 -0
- tests/apps/nuclick/test_nuclick_transforms.py +259 -0
- tests/apps/pathology/__init__.py +10 -0
- tests/apps/pathology/handlers/__init__.py +10 -0
- tests/apps/pathology/handlers/test_from_engine_hovernet.py +38 -0
- tests/apps/pathology/test_lesion_froc.py +333 -0
- tests/apps/pathology/test_pathology_prob_nms.py +55 -0
- tests/apps/pathology/test_prepare_batch_hovernet.py +70 -0
- tests/apps/pathology/test_sliding_window_hovernet_inference.py +303 -0
- tests/apps/pathology/transforms/__init__.py +10 -0
- tests/apps/pathology/transforms/post/__init__.py +10 -0
- tests/apps/pathology/transforms/post/test_generate_distance_map.py +51 -0
- tests/apps/pathology/transforms/post/test_generate_distance_mapd.py +70 -0
- tests/apps/pathology/transforms/post/test_generate_instance_border.py +49 -0
- tests/apps/pathology/transforms/post/test_generate_instance_borderd.py +59 -0
- tests/apps/pathology/transforms/post/test_generate_instance_centroid.py +53 -0
- tests/apps/pathology/transforms/post/test_generate_instance_centroidd.py +56 -0
- tests/apps/pathology/transforms/post/test_generate_instance_contour.py +58 -0
- tests/apps/pathology/transforms/post/test_generate_instance_contourd.py +61 -0
- tests/apps/pathology/transforms/post/test_generate_instance_type.py +51 -0
- tests/apps/pathology/transforms/post/test_generate_instance_typed.py +53 -0
- tests/apps/pathology/transforms/post/test_generate_succinct_contour.py +55 -0
- tests/apps/pathology/transforms/post/test_generate_succinct_contourd.py +57 -0
- tests/apps/pathology/transforms/post/test_generate_watershed_markers.py +53 -0
- tests/apps/pathology/transforms/post/test_generate_watershed_markersd.py +83 -0
- tests/apps/pathology/transforms/post/test_generate_watershed_mask.py +77 -0
- tests/apps/pathology/transforms/post/test_generate_watershed_maskd.py +77 -0
- tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processing.py +61 -0
- tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processingd.py +66 -0
- tests/apps/pathology/transforms/post/test_hovernet_nuclear_type_post_processing.py +66 -0
- tests/apps/pathology/transforms/post/test_watershed.py +60 -0
- tests/apps/pathology/transforms/post/test_watershedd.py +70 -0
- tests/apps/pathology/transforms/test_pathology_he_stain.py +230 -0
- tests/apps/pathology/transforms/test_pathology_he_stain_dict.py +225 -0
- tests/apps/reconstruction/__init__.py +10 -0
- tests/apps/reconstruction/nets/__init__.py +10 -0
- tests/apps/reconstruction/nets/test_recon_net_utils.py +82 -0
- tests/apps/reconstruction/test_complex_utils.py +77 -0
- tests/apps/reconstruction/test_fastmri_reader.py +82 -0
- tests/apps/reconstruction/test_mri_utils.py +37 -0
- tests/apps/reconstruction/transforms/__init__.py +10 -0
- tests/apps/reconstruction/transforms/test_kspace_mask.py +50 -0
- tests/apps/reconstruction/transforms/test_reference_based_normalize_intensity.py +77 -0
- tests/apps/reconstruction/transforms/test_reference_based_spatial_cropd.py +57 -0
- tests/apps/test_auto3dseg_bundlegen.py +156 -0
- tests/apps/test_check_hash.py +53 -0
- tests/apps/test_cross_validation.py +74 -0
- tests/apps/test_decathlondataset.py +93 -0
- tests/apps/test_download_and_extract.py +70 -0
- tests/apps/test_download_url_yandex.py +45 -0
- tests/apps/test_mednistdataset.py +72 -0
- tests/apps/test_mmar_download.py +154 -0
- tests/apps/test_tciadataset.py +123 -0
- tests/apps/vista3d/__init__.py +10 -0
- tests/apps/vista3d/test_point_based_window_inferer.py +77 -0
- tests/apps/vista3d/test_vista3d_sampler.py +100 -0
- tests/apps/vista3d/test_vista3d_transforms.py +94 -0
- tests/bundle/__init__.py +10 -0
- tests/bundle/test_bundle_ckpt_export.py +107 -0
- tests/bundle/test_bundle_download.py +435 -0
- tests/bundle/test_bundle_get_data.py +94 -0
- tests/bundle/test_bundle_push_to_hf_hub.py +41 -0
- tests/bundle/test_bundle_trt_export.py +147 -0
- tests/bundle/test_bundle_utils.py +149 -0
- tests/bundle/test_bundle_verify_metadata.py +66 -0
- tests/bundle/test_bundle_verify_net.py +76 -0
- tests/bundle/test_bundle_workflow.py +272 -0
- tests/bundle/test_component_locator.py +38 -0
- tests/bundle/test_config_item.py +138 -0
- tests/bundle/test_config_parser.py +392 -0
- tests/bundle/test_reference_resolver.py +114 -0
- tests/config/__init__.py +10 -0
- tests/config/test_cv2_dist.py +53 -0
- tests/engines/__init__.py +10 -0
- tests/engines/test_ensemble_evaluator.py +94 -0
- tests/engines/test_prepare_batch_default.py +76 -0
- tests/engines/test_prepare_batch_default_dist.py +76 -0
- tests/engines/test_prepare_batch_diffusion.py +104 -0
- tests/engines/test_prepare_batch_extra_input.py +80 -0
- tests/fl/__init__.py +10 -0
- tests/fl/monai_algo/__init__.py +10 -0
- tests/fl/monai_algo/test_fl_monai_algo.py +251 -0
- tests/fl/monai_algo/test_fl_monai_algo_dist.py +117 -0
- tests/fl/test_fl_monai_algo_stats.py +81 -0
- tests/fl/utils/__init__.py +10 -0
- tests/fl/utils/test_fl_exchange_object.py +63 -0
- tests/handlers/__init__.py +10 -0
- tests/handlers/test_handler_checkpoint_loader.py +182 -0
- tests/handlers/test_handler_checkpoint_saver.py +233 -0
- tests/handlers/test_handler_classification_saver.py +64 -0
- tests/handlers/test_handler_classification_saver_dist.py +77 -0
- tests/handlers/test_handler_clearml_image.py +65 -0
- tests/handlers/test_handler_clearml_stats.py +65 -0
- tests/handlers/test_handler_confusion_matrix.py +104 -0
- tests/handlers/test_handler_confusion_matrix_dist.py +70 -0
- tests/handlers/test_handler_decollate_batch.py +66 -0
- tests/handlers/test_handler_early_stop.py +68 -0
- tests/handlers/test_handler_garbage_collector.py +73 -0
- tests/handlers/test_handler_hausdorff_distance.py +111 -0
- tests/handlers/test_handler_ignite_metric.py +191 -0
- tests/handlers/test_handler_lr_scheduler.py +94 -0
- tests/handlers/test_handler_mean_dice.py +98 -0
- tests/handlers/test_handler_mean_iou.py +76 -0
- tests/handlers/test_handler_metrics_reloaded.py +149 -0
- tests/handlers/test_handler_metrics_saver.py +89 -0
- tests/handlers/test_handler_metrics_saver_dist.py +120 -0
- tests/handlers/test_handler_mlflow.py +296 -0
- tests/handlers/test_handler_nvtx.py +93 -0
- tests/handlers/test_handler_panoptic_quality.py +89 -0
- tests/handlers/test_handler_parameter_scheduler.py +136 -0
- tests/handlers/test_handler_post_processing.py +74 -0
- tests/handlers/test_handler_prob_map_producer.py +111 -0
- tests/handlers/test_handler_regression_metrics.py +160 -0
- tests/handlers/test_handler_regression_metrics_dist.py +245 -0
- tests/handlers/test_handler_rocauc.py +48 -0
- tests/handlers/test_handler_rocauc_dist.py +54 -0
- tests/handlers/test_handler_stats.py +281 -0
- tests/handlers/test_handler_surface_distance.py +113 -0
- tests/handlers/test_handler_tb_image.py +61 -0
- tests/handlers/test_handler_tb_stats.py +166 -0
- tests/handlers/test_handler_validation.py +59 -0
- tests/handlers/test_trt_compile.py +145 -0
- tests/handlers/test_write_metrics_reports.py +68 -0
- tests/inferers/__init__.py +10 -0
- tests/inferers/test_avg_merger.py +179 -0
- tests/inferers/test_controlnet_inferers.py +1310 -0
- tests/inferers/test_diffusion_inferer.py +236 -0
- tests/inferers/test_latent_diffusion_inferer.py +824 -0
- tests/inferers/test_patch_inferer.py +309 -0
- tests/inferers/test_saliency_inferer.py +55 -0
- tests/inferers/test_slice_inferer.py +57 -0
- tests/inferers/test_sliding_window_inference.py +377 -0
- tests/inferers/test_sliding_window_splitter.py +284 -0
- tests/inferers/test_wsi_sliding_window_splitter.py +249 -0
- tests/inferers/test_zarr_avg_merger.py +326 -0
- tests/integration/__init__.py +10 -0
- tests/integration/test_auto3dseg_ensemble.py +211 -0
- tests/integration/test_auto3dseg_hpo.py +189 -0
- tests/integration/test_deepedit_interaction.py +122 -0
- tests/integration/test_downsample_block.py +50 -0
- tests/integration/test_hovernet_nuclear_type_post_processingd.py +71 -0
- tests/integration/test_integration_autorunner.py +201 -0
- tests/integration/test_integration_bundle_run.py +240 -0
- tests/integration/test_integration_classification_2d.py +282 -0
- tests/integration/test_integration_determinism.py +95 -0
- tests/integration/test_integration_fast_train.py +231 -0
- tests/integration/test_integration_gpu_customization.py +159 -0
- tests/integration/test_integration_lazy_samples.py +219 -0
- tests/integration/test_integration_nnunetv2_runner.py +96 -0
- tests/integration/test_integration_segmentation_3d.py +304 -0
- tests/integration/test_integration_sliding_window.py +100 -0
- tests/integration/test_integration_stn.py +133 -0
- tests/integration/test_integration_unet_2d.py +67 -0
- tests/integration/test_integration_workers.py +61 -0
- tests/integration/test_integration_workflows.py +365 -0
- tests/integration/test_integration_workflows_adversarial.py +173 -0
- tests/integration/test_integration_workflows_gan.py +158 -0
- tests/integration/test_loader_semaphore.py +48 -0
- tests/integration/test_mapping_filed.py +122 -0
- tests/integration/test_meta_affine.py +183 -0
- tests/integration/test_metatensor_integration.py +114 -0
- tests/integration/test_module_list.py +76 -0
- tests/integration/test_one_of.py +283 -0
- tests/integration/test_pad_collation.py +124 -0
- tests/integration/test_reg_loss_integration.py +107 -0
- tests/integration/test_retinanet_predict_utils.py +154 -0
- tests/integration/test_seg_loss_integration.py +159 -0
- tests/integration/test_spatial_combine_transforms.py +185 -0
- tests/integration/test_testtimeaugmentation.py +186 -0
- tests/integration/test_vis_gradbased.py +69 -0
- tests/integration/test_vista3d_utils.py +159 -0
- tests/losses/__init__.py +10 -0
- tests/losses/deform/__init__.py +10 -0
- tests/losses/deform/test_bending_energy.py +88 -0
- tests/losses/deform/test_diffusion_loss.py +117 -0
- tests/losses/image_dissimilarity/__init__.py +10 -0
- tests/losses/image_dissimilarity/test_global_mutual_information_loss.py +150 -0
- tests/losses/image_dissimilarity/test_local_normalized_cross_correlation_loss.py +162 -0
- tests/losses/test_adversarial_loss.py +94 -0
- tests/losses/test_barlow_twins_loss.py +109 -0
- tests/losses/test_cldice_loss.py +51 -0
- tests/losses/test_contrastive_loss.py +86 -0
- tests/losses/test_dice_ce_loss.py +123 -0
- tests/losses/test_dice_focal_loss.py +124 -0
- tests/losses/test_dice_loss.py +227 -0
- tests/losses/test_ds_loss.py +189 -0
- tests/losses/test_focal_loss.py +379 -0
- tests/losses/test_generalized_dice_focal_loss.py +85 -0
- tests/losses/test_generalized_dice_loss.py +221 -0
- tests/losses/test_generalized_wasserstein_dice_loss.py +234 -0
- tests/losses/test_giou_loss.py +62 -0
- tests/losses/test_hausdorff_loss.py +264 -0
- tests/losses/test_masked_dice_loss.py +152 -0
- tests/losses/test_masked_loss.py +87 -0
- tests/losses/test_multi_scale.py +86 -0
- tests/losses/test_nacl_loss.py +167 -0
- tests/losses/test_perceptual_loss.py +122 -0
- tests/losses/test_spectral_loss.py +86 -0
- tests/losses/test_ssim_loss.py +59 -0
- tests/losses/test_sure_loss.py +72 -0
- tests/losses/test_tversky_loss.py +198 -0
- tests/losses/test_unified_focal_loss.py +66 -0
- tests/metrics/__init__.py +10 -0
- tests/metrics/test_compute_confusion_matrix.py +294 -0
- tests/metrics/test_compute_f_beta.py +80 -0
- tests/metrics/test_compute_fid_metric.py +40 -0
- tests/metrics/test_compute_froc.py +143 -0
- tests/metrics/test_compute_generalized_dice.py +240 -0
- tests/metrics/test_compute_meandice.py +306 -0
- tests/metrics/test_compute_meaniou.py +223 -0
- tests/metrics/test_compute_mmd_metric.py +56 -0
- tests/metrics/test_compute_multiscalessim_metric.py +83 -0
- tests/metrics/test_compute_panoptic_quality.py +113 -0
- tests/metrics/test_compute_regression_metrics.py +196 -0
- tests/metrics/test_compute_roc_auc.py +155 -0
- tests/metrics/test_compute_variance.py +147 -0
- tests/metrics/test_cumulative.py +63 -0
- tests/metrics/test_cumulative_average.py +74 -0
- tests/metrics/test_cumulative_average_dist.py +48 -0
- tests/metrics/test_hausdorff_distance.py +209 -0
- tests/metrics/test_label_quality_score.py +134 -0
- tests/metrics/test_loss_metric.py +57 -0
- tests/metrics/test_metrics_reloaded.py +96 -0
- tests/metrics/test_ssim_metric.py +78 -0
- tests/metrics/test_surface_dice.py +416 -0
- tests/metrics/test_surface_distance.py +186 -0
- tests/networks/__init__.py +10 -0
- tests/networks/blocks/__init__.py +10 -0
- tests/networks/blocks/dints_block/__init__.py +10 -0
- tests/networks/blocks/dints_block/test_acn_block.py +41 -0
- tests/networks/blocks/dints_block/test_factorized_increase.py +37 -0
- tests/networks/blocks/dints_block/test_factorized_reduce.py +37 -0
- tests/networks/blocks/dints_block/test_p3d_block.py +78 -0
- tests/networks/blocks/test_adn.py +86 -0
- tests/networks/blocks/test_convolutions.py +156 -0
- tests/networks/blocks/test_crf_cpu.py +513 -0
- tests/networks/blocks/test_crf_cuda.py +528 -0
- tests/networks/blocks/test_crossattention.py +185 -0
- tests/networks/blocks/test_denseblock.py +105 -0
- tests/networks/blocks/test_dynunet_block.py +116 -0
- tests/networks/blocks/test_fpn_block.py +88 -0
- tests/networks/blocks/test_localnet_block.py +121 -0
- tests/networks/blocks/test_mlp.py +78 -0
- tests/networks/blocks/test_patchembedding.py +212 -0
- tests/networks/blocks/test_regunet_block.py +103 -0
- tests/networks/blocks/test_se_block.py +85 -0
- tests/networks/blocks/test_se_blocks.py +78 -0
- tests/networks/blocks/test_segresnet_block.py +57 -0
- tests/networks/blocks/test_selfattention.py +232 -0
- tests/networks/blocks/test_simple_aspp.py +87 -0
- tests/networks/blocks/test_spatialattention.py +55 -0
- tests/networks/blocks/test_subpixel_upsample.py +87 -0
- tests/networks/blocks/test_text_encoding.py +49 -0
- tests/networks/blocks/test_transformerblock.py +90 -0
- tests/networks/blocks/test_unetr_block.py +158 -0
- tests/networks/blocks/test_upsample_block.py +134 -0
- tests/networks/blocks/warp/__init__.py +10 -0
- tests/networks/blocks/warp/test_dvf2ddf.py +72 -0
- tests/networks/blocks/warp/test_warp.py +250 -0
- tests/networks/layers/__init__.py +10 -0
- tests/networks/layers/filtering/__init__.py +10 -0
- tests/networks/layers/filtering/test_bilateral_approx_cpu.py +399 -0
- tests/networks/layers/filtering/test_bilateral_approx_cuda.py +404 -0
- tests/networks/layers/filtering/test_bilateral_precise.py +437 -0
- tests/networks/layers/filtering/test_phl_cpu.py +259 -0
- tests/networks/layers/filtering/test_phl_cuda.py +167 -0
- tests/networks/layers/filtering/test_trainable_bilateral.py +474 -0
- tests/networks/layers/filtering/test_trainable_joint_bilateral.py +609 -0
- tests/networks/layers/test_affine_transform.py +385 -0
- tests/networks/layers/test_apply_filter.py +89 -0
- tests/networks/layers/test_channel_pad.py +51 -0
- tests/networks/layers/test_conjugate_gradient.py +56 -0
- tests/networks/layers/test_drop_path.py +46 -0
- tests/networks/layers/test_gaussian.py +317 -0
- tests/networks/layers/test_gaussian_filter.py +206 -0
- tests/networks/layers/test_get_layers.py +65 -0
- tests/networks/layers/test_gmm.py +314 -0
- tests/networks/layers/test_grid_pull.py +93 -0
- tests/networks/layers/test_hilbert_transform.py +131 -0
- tests/networks/layers/test_lltm.py +62 -0
- tests/networks/layers/test_median_filter.py +52 -0
- tests/networks/layers/test_polyval.py +55 -0
- tests/networks/layers/test_preset_filters.py +136 -0
- tests/networks/layers/test_savitzky_golay_filter.py +141 -0
- tests/networks/layers/test_separable_filter.py +87 -0
- tests/networks/layers/test_skip_connection.py +48 -0
- tests/networks/layers/test_vector_quantizer.py +89 -0
- tests/networks/layers/test_weight_init.py +50 -0
- tests/networks/nets/__init__.py +10 -0
- tests/networks/nets/dints/__init__.py +10 -0
- tests/networks/nets/dints/test_dints_cell.py +110 -0
- tests/networks/nets/dints/test_dints_mixop.py +84 -0
- tests/networks/nets/regunet/__init__.py +10 -0
- tests/networks/nets/regunet/test_localnet.py +86 -0
- tests/networks/nets/regunet/test_regunet.py +88 -0
- tests/networks/nets/test_ahnet.py +224 -0
- tests/networks/nets/test_attentionunet.py +88 -0
- tests/networks/nets/test_autoencoder.py +95 -0
- tests/networks/nets/test_autoencoderkl.py +337 -0
- tests/networks/nets/test_basic_unet.py +102 -0
- tests/networks/nets/test_basic_unetplusplus.py +109 -0
- tests/networks/nets/test_bundle_init_bundle.py +55 -0
- tests/networks/nets/test_cell_sam_wrapper.py +58 -0
- tests/networks/nets/test_controlnet.py +215 -0
- tests/networks/nets/test_daf3d.py +62 -0
- tests/networks/nets/test_densenet.py +121 -0
- tests/networks/nets/test_diffusion_model_unet.py +585 -0
- tests/networks/nets/test_dints_network.py +168 -0
- tests/networks/nets/test_discriminator.py +59 -0
- tests/networks/nets/test_dynunet.py +181 -0
- tests/networks/nets/test_efficientnet.py +400 -0
- tests/networks/nets/test_flexible_unet.py +341 -0
- tests/networks/nets/test_fullyconnectednet.py +69 -0
- tests/networks/nets/test_generator.py +59 -0
- tests/networks/nets/test_globalnet.py +103 -0
- tests/networks/nets/test_highresnet.py +67 -0
- tests/networks/nets/test_hovernet.py +218 -0
- tests/networks/nets/test_mednext.py +122 -0
- tests/networks/nets/test_milmodel.py +92 -0
- tests/networks/nets/test_net_adapter.py +68 -0
- tests/networks/nets/test_network_consistency.py +86 -0
- tests/networks/nets/test_patch_gan_dicriminator.py +179 -0
- tests/networks/nets/test_quicknat.py +57 -0
- tests/networks/nets/test_resnet.py +340 -0
- tests/networks/nets/test_segresnet.py +120 -0
- tests/networks/nets/test_segresnet_ds.py +156 -0
- tests/networks/nets/test_senet.py +151 -0
- tests/networks/nets/test_spade_autoencoderkl.py +295 -0
- tests/networks/nets/test_spade_diffusion_model_unet.py +574 -0
- tests/networks/nets/test_spade_vaegan.py +140 -0
- tests/networks/nets/test_swin_unetr.py +139 -0
- tests/networks/nets/test_torchvision_fc_model.py +201 -0
- tests/networks/nets/test_transchex.py +84 -0
- tests/networks/nets/test_transformer.py +108 -0
- tests/networks/nets/test_unet.py +208 -0
- tests/networks/nets/test_unetr.py +137 -0
- tests/networks/nets/test_varautoencoder.py +127 -0
- tests/networks/nets/test_vista3d.py +84 -0
- tests/networks/nets/test_vit.py +139 -0
- tests/networks/nets/test_vitautoenc.py +112 -0
- tests/networks/nets/test_vnet.py +81 -0
- tests/networks/nets/test_voxelmorph.py +280 -0
- tests/networks/nets/test_vqvae.py +274 -0
- tests/networks/nets/test_vqvaetransformer_inferer.py +295 -0
- tests/networks/schedulers/__init__.py +10 -0
- tests/networks/schedulers/test_scheduler_ddim.py +83 -0
- tests/networks/schedulers/test_scheduler_ddpm.py +104 -0
- tests/networks/schedulers/test_scheduler_pndm.py +108 -0
- tests/networks/test_bundle_onnx_export.py +71 -0
- tests/networks/test_convert_to_onnx.py +106 -0
- tests/networks/test_convert_to_torchscript.py +46 -0
- tests/networks/test_convert_to_trt.py +79 -0
- tests/networks/test_save_state.py +73 -0
- tests/networks/test_to_onehot.py +63 -0
- tests/networks/test_varnet.py +63 -0
- tests/networks/utils/__init__.py +10 -0
- tests/networks/utils/test_copy_model_state.py +187 -0
- tests/networks/utils/test_eval_mode.py +34 -0
- tests/networks/utils/test_freeze_layers.py +61 -0
- tests/networks/utils/test_replace_module.py +98 -0
- tests/networks/utils/test_train_mode.py +34 -0
- tests/optimizers/__init__.py +10 -0
- tests/optimizers/test_generate_param_groups.py +105 -0
- tests/optimizers/test_lr_finder.py +108 -0
- tests/optimizers/test_lr_scheduler.py +71 -0
- tests/optimizers/test_optim_novograd.py +100 -0
- tests/profile_subclass/__init__.py +10 -0
- tests/profile_subclass/cprofile_profiling.py +29 -0
- tests/profile_subclass/min_classes.py +30 -0
- tests/profile_subclass/profiling.py +73 -0
- tests/profile_subclass/pyspy_profiling.py +41 -0
- tests/transforms/__init__.py +10 -0
- tests/transforms/compose/__init__.py +10 -0
- tests/transforms/compose/test_compose.py +758 -0
- tests/transforms/compose/test_some_of.py +258 -0
- tests/transforms/croppad/__init__.py +10 -0
- tests/transforms/croppad/test_rand_weighted_crop.py +224 -0
- tests/transforms/croppad/test_rand_weighted_cropd.py +182 -0
- tests/transforms/functional/__init__.py +10 -0
- tests/transforms/functional/test_apply.py +75 -0
- tests/transforms/functional/test_resample.py +50 -0
- tests/transforms/intensity/__init__.py +10 -0
- tests/transforms/intensity/test_compute_ho_ver_maps.py +75 -0
- tests/transforms/intensity/test_compute_ho_ver_maps_d.py +79 -0
- tests/transforms/intensity/test_foreground_mask.py +98 -0
- tests/transforms/intensity/test_foreground_maskd.py +106 -0
- tests/transforms/intensity/test_rand_histogram_shiftd.py +76 -0
- tests/transforms/intensity/test_scale_intensity_range_percentiles.py +96 -0
- tests/transforms/intensity/test_scale_intensity_range_percentilesd.py +100 -0
- tests/transforms/inverse/__init__.py +10 -0
- tests/transforms/inverse/test_inverse_array.py +76 -0
- tests/transforms/inverse/test_traceable_transform.py +59 -0
- tests/transforms/post/__init__.py +10 -0
- tests/transforms/post/test_label_filterd.py +78 -0
- tests/transforms/post/test_probnms.py +72 -0
- tests/transforms/post/test_probnmsd.py +79 -0
- tests/transforms/post/test_remove_small_objects.py +102 -0
- tests/transforms/spatial/__init__.py +10 -0
- tests/transforms/spatial/test_convert_box_points.py +119 -0
- tests/transforms/spatial/test_grid_patch.py +134 -0
- tests/transforms/spatial/test_grid_patchd.py +102 -0
- tests/transforms/spatial/test_rand_grid_patch.py +150 -0
- tests/transforms/spatial/test_rand_grid_patchd.py +117 -0
- tests/transforms/spatial/test_spatial_resampled.py +124 -0
- tests/transforms/test_activations.py +120 -0
- tests/transforms/test_activationsd.py +64 -0
- tests/transforms/test_adaptors.py +160 -0
- tests/transforms/test_add_coordinate_channels.py +53 -0
- tests/transforms/test_add_coordinate_channelsd.py +67 -0
- tests/transforms/test_add_extreme_points_channel.py +80 -0
- tests/transforms/test_add_extreme_points_channeld.py +77 -0
- tests/transforms/test_adjust_contrast.py +70 -0
- tests/transforms/test_adjust_contrastd.py +64 -0
- tests/transforms/test_affine.py +245 -0
- tests/transforms/test_affine_grid.py +152 -0
- tests/transforms/test_affined.py +190 -0
- tests/transforms/test_as_channel_last.py +38 -0
- tests/transforms/test_as_channel_lastd.py +44 -0
- tests/transforms/test_as_discrete.py +81 -0
- tests/transforms/test_as_discreted.py +82 -0
- tests/transforms/test_border_pad.py +49 -0
- tests/transforms/test_border_padd.py +45 -0
- tests/transforms/test_bounding_rect.py +54 -0
- tests/transforms/test_bounding_rectd.py +53 -0
- tests/transforms/test_cast_to_type.py +63 -0
- tests/transforms/test_cast_to_typed.py +74 -0
- tests/transforms/test_center_scale_crop.py +55 -0
- tests/transforms/test_center_scale_cropd.py +56 -0
- tests/transforms/test_center_spatial_crop.py +56 -0
- tests/transforms/test_center_spatial_cropd.py +63 -0
- tests/transforms/test_classes_to_indices.py +93 -0
- tests/transforms/test_classes_to_indicesd.py +110 -0
- tests/transforms/test_clip_intensity_percentiles.py +196 -0
- tests/transforms/test_clip_intensity_percentilesd.py +193 -0
- tests/transforms/test_compose_get_number_conversions.py +127 -0
- tests/transforms/test_concat_itemsd.py +82 -0
- tests/transforms/test_convert_to_multi_channel.py +59 -0
- tests/transforms/test_convert_to_multi_channeld.py +37 -0
- tests/transforms/test_copy_itemsd.py +86 -0
- tests/transforms/test_create_grid_and_affine.py +274 -0
- tests/transforms/test_crop_foreground.py +164 -0
- tests/transforms/test_crop_foregroundd.py +205 -0
- tests/transforms/test_cucim_dict_transform.py +142 -0
- tests/transforms/test_cucim_transform.py +141 -0
- tests/transforms/test_data_stats.py +221 -0
- tests/transforms/test_data_statsd.py +249 -0
- tests/transforms/test_delete_itemsd.py +58 -0
- tests/transforms/test_detect_envelope.py +159 -0
- tests/transforms/test_distance_transform_edt.py +202 -0
- tests/transforms/test_divisible_pad.py +49 -0
- tests/transforms/test_divisible_padd.py +42 -0
- tests/transforms/test_ensure_channel_first.py +113 -0
- tests/transforms/test_ensure_channel_firstd.py +85 -0
- tests/transforms/test_ensure_type.py +94 -0
- tests/transforms/test_ensure_typed.py +110 -0
- tests/transforms/test_fg_bg_to_indices.py +83 -0
- tests/transforms/test_fg_bg_to_indicesd.py +78 -0
- tests/transforms/test_fill_holes.py +207 -0
- tests/transforms/test_fill_holesd.py +209 -0
- tests/transforms/test_flatten_sub_keysd.py +64 -0
- tests/transforms/test_flip.py +83 -0
- tests/transforms/test_flipd.py +90 -0
- tests/transforms/test_fourier.py +70 -0
- tests/transforms/test_gaussian_sharpen.py +92 -0
- tests/transforms/test_gaussian_sharpend.py +92 -0
- tests/transforms/test_gaussian_smooth.py +96 -0
- tests/transforms/test_gaussian_smoothd.py +96 -0
- tests/transforms/test_generate_label_classes_crop_centers.py +71 -0
- tests/transforms/test_generate_pos_neg_label_crop_centers.py +76 -0
- tests/transforms/test_generate_spatial_bounding_box.py +114 -0
- tests/transforms/test_get_extreme_points.py +57 -0
- tests/transforms/test_gibbs_noise.py +75 -0
- tests/transforms/test_gibbs_noised.py +88 -0
- tests/transforms/test_grid_distortion.py +113 -0
- tests/transforms/test_grid_distortiond.py +87 -0
- tests/transforms/test_grid_split.py +88 -0
- tests/transforms/test_grid_splitd.py +96 -0
- tests/transforms/test_histogram_normalize.py +59 -0
- tests/transforms/test_histogram_normalized.py +59 -0
- tests/transforms/test_image_filter.py +259 -0
- tests/transforms/test_intensity_stats.py +73 -0
- tests/transforms/test_intensity_statsd.py +90 -0
- tests/transforms/test_inverse.py +521 -0
- tests/transforms/test_inverse_collation.py +147 -0
- tests/transforms/test_invert.py +105 -0
- tests/transforms/test_invertd.py +142 -0
- tests/transforms/test_k_space_spike_noise.py +81 -0
- tests/transforms/test_k_space_spike_noised.py +98 -0
- tests/transforms/test_keep_largest_connected_component.py +419 -0
- tests/transforms/test_keep_largest_connected_componentd.py +348 -0
- tests/transforms/test_label_filter.py +78 -0
- tests/transforms/test_label_to_contour.py +179 -0
- tests/transforms/test_label_to_contourd.py +182 -0
- tests/transforms/test_label_to_mask.py +69 -0
- tests/transforms/test_label_to_maskd.py +70 -0
- tests/transforms/test_load_image.py +502 -0
- tests/transforms/test_load_imaged.py +198 -0
- tests/transforms/test_load_spacing_orientation.py +149 -0
- tests/transforms/test_map_and_generate_sampling_centers.py +86 -0
- tests/transforms/test_map_binary_to_indices.py +75 -0
- tests/transforms/test_map_classes_to_indices.py +135 -0
- tests/transforms/test_map_label_value.py +89 -0
- tests/transforms/test_map_label_valued.py +85 -0
- tests/transforms/test_map_transform.py +45 -0
- tests/transforms/test_mask_intensity.py +74 -0
- tests/transforms/test_mask_intensityd.py +68 -0
- tests/transforms/test_mean_ensemble.py +77 -0
- tests/transforms/test_mean_ensembled.py +91 -0
- tests/transforms/test_median_smooth.py +41 -0
- tests/transforms/test_median_smoothd.py +65 -0
- tests/transforms/test_morphological_ops.py +101 -0
- tests/transforms/test_nifti_endianness.py +107 -0
- tests/transforms/test_normalize_intensity.py +143 -0
- tests/transforms/test_normalize_intensityd.py +81 -0
- tests/transforms/test_nvtx_decorator.py +289 -0
- tests/transforms/test_nvtx_transform.py +143 -0
- tests/transforms/test_orientation.py +247 -0
- tests/transforms/test_orientationd.py +112 -0
- tests/transforms/test_rand_adjust_contrast.py +45 -0
- tests/transforms/test_rand_adjust_contrastd.py +44 -0
- tests/transforms/test_rand_affine.py +201 -0
- tests/transforms/test_rand_affine_grid.py +212 -0
- tests/transforms/test_rand_affined.py +281 -0
- tests/transforms/test_rand_axis_flip.py +50 -0
- tests/transforms/test_rand_axis_flipd.py +50 -0
- tests/transforms/test_rand_bias_field.py +69 -0
- tests/transforms/test_rand_bias_fieldd.py +65 -0
- tests/transforms/test_rand_coarse_dropout.py +110 -0
- tests/transforms/test_rand_coarse_dropoutd.py +107 -0
- tests/transforms/test_rand_coarse_shuffle.py +65 -0
- tests/transforms/test_rand_coarse_shuffled.py +59 -0
- tests/transforms/test_rand_crop_by_label_classes.py +170 -0
- tests/transforms/test_rand_crop_by_label_classesd.py +159 -0
- tests/transforms/test_rand_crop_by_pos_neg_label.py +152 -0
- tests/transforms/test_rand_crop_by_pos_neg_labeld.py +172 -0
- tests/transforms/test_rand_cucim_dict_transform.py +162 -0
- tests/transforms/test_rand_cucim_transform.py +162 -0
- tests/transforms/test_rand_deform_grid.py +138 -0
- tests/transforms/test_rand_elastic_2d.py +127 -0
- tests/transforms/test_rand_elastic_3d.py +104 -0
- tests/transforms/test_rand_elasticd_2d.py +177 -0
- tests/transforms/test_rand_elasticd_3d.py +156 -0
- tests/transforms/test_rand_flip.py +60 -0
- tests/transforms/test_rand_flipd.py +55 -0
- tests/transforms/test_rand_gaussian_noise.py +48 -0
- tests/transforms/test_rand_gaussian_noised.py +54 -0
- tests/transforms/test_rand_gaussian_sharpen.py +140 -0
- tests/transforms/test_rand_gaussian_sharpend.py +143 -0
- tests/transforms/test_rand_gaussian_smooth.py +98 -0
- tests/transforms/test_rand_gaussian_smoothd.py +98 -0
- tests/transforms/test_rand_gibbs_noise.py +103 -0
- tests/transforms/test_rand_gibbs_noised.py +117 -0
- tests/transforms/test_rand_grid_distortion.py +99 -0
- tests/transforms/test_rand_grid_distortiond.py +90 -0
- tests/transforms/test_rand_histogram_shift.py +92 -0
- tests/transforms/test_rand_k_space_spike_noise.py +92 -0
- tests/transforms/test_rand_k_space_spike_noised.py +76 -0
- tests/transforms/test_rand_rician_noise.py +52 -0
- tests/transforms/test_rand_rician_noised.py +52 -0
- tests/transforms/test_rand_rotate.py +166 -0
- tests/transforms/test_rand_rotate90.py +100 -0
- tests/transforms/test_rand_rotate90d.py +112 -0
- tests/transforms/test_rand_rotated.py +187 -0
- tests/transforms/test_rand_scale_crop.py +78 -0
- tests/transforms/test_rand_scale_cropd.py +98 -0
- tests/transforms/test_rand_scale_intensity.py +54 -0
- tests/transforms/test_rand_scale_intensity_fixed_mean.py +41 -0
- tests/transforms/test_rand_scale_intensity_fixed_meand.py +41 -0
- tests/transforms/test_rand_scale_intensityd.py +53 -0
- tests/transforms/test_rand_shift_intensity.py +52 -0
- tests/transforms/test_rand_shift_intensityd.py +67 -0
- tests/transforms/test_rand_simulate_low_resolution.py +83 -0
- tests/transforms/test_rand_simulate_low_resolutiond.py +73 -0
- tests/transforms/test_rand_spatial_crop.py +107 -0
- tests/transforms/test_rand_spatial_crop_samples.py +128 -0
- tests/transforms/test_rand_spatial_crop_samplesd.py +147 -0
- tests/transforms/test_rand_spatial_cropd.py +112 -0
- tests/transforms/test_rand_std_shift_intensity.py +43 -0
- tests/transforms/test_rand_std_shift_intensityd.py +38 -0
- tests/transforms/test_rand_zoom.py +105 -0
- tests/transforms/test_rand_zoomd.py +108 -0
- tests/transforms/test_randidentity.py +49 -0
- tests/transforms/test_random_order.py +144 -0
- tests/transforms/test_randtorchvisiond.py +65 -0
- tests/transforms/test_regularization.py +139 -0
- tests/transforms/test_remove_repeated_channel.py +34 -0
- tests/transforms/test_remove_repeated_channeld.py +44 -0
- tests/transforms/test_repeat_channel.py +34 -0
- tests/transforms/test_repeat_channeld.py +41 -0
- tests/transforms/test_resample_backends.py +65 -0
- tests/transforms/test_resample_to_match.py +110 -0
- tests/transforms/test_resample_to_matchd.py +93 -0
- tests/transforms/test_resampler.py +165 -0
- tests/transforms/test_resize.py +140 -0
- tests/transforms/test_resize_with_pad_or_crop.py +91 -0
- tests/transforms/test_resize_with_pad_or_cropd.py +86 -0
- tests/transforms/test_resized.py +163 -0
- tests/transforms/test_rotate.py +160 -0
- tests/transforms/test_rotate90.py +212 -0
- tests/transforms/test_rotate90d.py +106 -0
- tests/transforms/test_rotated.py +179 -0
- tests/transforms/test_save_classificationd.py +109 -0
- tests/transforms/test_save_image.py +80 -0
- tests/transforms/test_save_imaged.py +130 -0
- tests/transforms/test_savitzky_golay_smooth.py +73 -0
- tests/transforms/test_savitzky_golay_smoothd.py +73 -0
- tests/transforms/test_scale_intensity.py +76 -0
- tests/transforms/test_scale_intensity_fixed_mean.py +94 -0
- tests/transforms/test_scale_intensity_range.py +41 -0
- tests/transforms/test_scale_intensity_ranged.py +40 -0
- tests/transforms/test_scale_intensityd.py +57 -0
- tests/transforms/test_select_itemsd.py +41 -0
- tests/transforms/test_shift_intensity.py +31 -0
- tests/transforms/test_shift_intensityd.py +44 -0
- tests/transforms/test_signal_continuouswavelet.py +44 -0
- tests/transforms/test_signal_fillempty.py +52 -0
- tests/transforms/test_signal_fillemptyd.py +60 -0
- tests/transforms/test_signal_rand_add_gaussiannoise.py +50 -0
- tests/transforms/test_signal_rand_add_sine.py +52 -0
- tests/transforms/test_signal_rand_add_sine_partial.py +50 -0
- tests/transforms/test_signal_rand_add_squarepulse.py +58 -0
- tests/transforms/test_signal_rand_add_squarepulse_partial.py +62 -0
- tests/transforms/test_signal_rand_drop.py +50 -0
- tests/transforms/test_signal_rand_scale.py +52 -0
- tests/transforms/test_signal_rand_shift.py +55 -0
- tests/transforms/test_signal_remove_frequency.py +71 -0
- tests/transforms/test_smooth_field.py +177 -0
- tests/transforms/test_sobel_gradient.py +189 -0
- tests/transforms/test_sobel_gradientd.py +212 -0
- tests/transforms/test_spacing.py +381 -0
- tests/transforms/test_spacingd.py +178 -0
- tests/transforms/test_spatial_crop.py +82 -0
- tests/transforms/test_spatial_cropd.py +74 -0
- tests/transforms/test_spatial_pad.py +57 -0
- tests/transforms/test_spatial_padd.py +43 -0
- tests/transforms/test_spatial_resample.py +235 -0
- tests/transforms/test_squeezedim.py +62 -0
- tests/transforms/test_squeezedimd.py +98 -0
- tests/transforms/test_std_shift_intensity.py +76 -0
- tests/transforms/test_std_shift_intensityd.py +74 -0
- tests/transforms/test_threshold_intensity.py +38 -0
- tests/transforms/test_threshold_intensityd.py +58 -0
- tests/transforms/test_to_contiguous.py +47 -0
- tests/transforms/test_to_cupy.py +112 -0
- tests/transforms/test_to_cupyd.py +76 -0
- tests/transforms/test_to_device.py +42 -0
- tests/transforms/test_to_deviced.py +37 -0
- tests/transforms/test_to_numpy.py +85 -0
- tests/transforms/test_to_numpyd.py +68 -0
- tests/transforms/test_to_pil.py +52 -0
- tests/transforms/test_to_pild.py +50 -0
- tests/transforms/test_to_tensor.py +60 -0
- tests/transforms/test_to_tensord.py +71 -0
- tests/transforms/test_torchvision.py +66 -0
- tests/transforms/test_torchvisiond.py +63 -0
- tests/transforms/test_transform.py +62 -0
- tests/transforms/test_transpose.py +41 -0
- tests/transforms/test_transposed.py +52 -0
- tests/transforms/test_ultrasound_confidence_map_transform.py +711 -0
- tests/transforms/test_utils_pytorch_numpy_unification.py +90 -0
- tests/transforms/test_vote_ensemble.py +84 -0
- tests/transforms/test_vote_ensembled.py +107 -0
- tests/transforms/test_with_allow_missing_keys.py +76 -0
- tests/transforms/test_zoom.py +120 -0
- tests/transforms/test_zoomd.py +94 -0
- tests/transforms/transform/__init__.py +10 -0
- tests/transforms/transform/test_randomizable.py +52 -0
- tests/transforms/transform/test_randomizable_transform_type.py +37 -0
- tests/transforms/utility/__init__.py +10 -0
- tests/transforms/utility/test_apply_transform_to_points.py +81 -0
- tests/transforms/utility/test_apply_transform_to_pointsd.py +185 -0
- tests/transforms/utility/test_identity.py +29 -0
- tests/transforms/utility/test_identityd.py +30 -0
- tests/transforms/utility/test_lambda.py +71 -0
- tests/transforms/utility/test_lambdad.py +83 -0
- tests/transforms/utility/test_rand_lambda.py +87 -0
- tests/transforms/utility/test_rand_lambdad.py +77 -0
- tests/transforms/utility/test_simulatedelay.py +36 -0
- tests/transforms/utility/test_simulatedelayd.py +36 -0
- tests/transforms/utility/test_splitdim.py +52 -0
- tests/transforms/utility/test_splitdimd.py +96 -0
- tests/transforms/utils/__init__.py +10 -0
- tests/transforms/utils/test_correct_crop_centers.py +36 -0
- tests/transforms/utils/test_get_unique_labels.py +45 -0
- tests/transforms/utils/test_print_transform_backends.py +29 -0
- tests/transforms/utils/test_soft_clip.py +125 -0
- tests/utils/__init__.py +10 -0
- tests/utils/enums/__init__.py +10 -0
- tests/utils/enums/test_hovernet_loss.py +190 -0
- tests/utils/enums/test_ordering.py +289 -0
- tests/utils/enums/test_wsireader.py +663 -0
- tests/utils/misc/__init__.py +10 -0
- tests/utils/misc/test_ensure_tuple.py +53 -0
- tests/utils/misc/test_monai_env_vars.py +44 -0
- tests/utils/misc/test_monai_utils_misc.py +103 -0
- tests/utils/misc/test_str2bool.py +34 -0
- tests/utils/misc/test_str2list.py +33 -0
- tests/utils/test_alias.py +44 -0
- tests/utils/test_component_store.py +73 -0
- tests/utils/test_deprecated.py +455 -0
- tests/utils/test_enum_bound_interp.py +75 -0
- tests/utils/test_evenly_divisible_all_gather_dist.py +50 -0
- tests/utils/test_get_package_version.py +34 -0
- tests/utils/test_handler_logfile.py +84 -0
- tests/utils/test_handler_metric_logger.py +62 -0
- tests/utils/test_list_to_dict.py +43 -0
- tests/utils/test_look_up_option.py +87 -0
- tests/utils/test_optional_import.py +80 -0
- tests/utils/test_pad_mode.py +39 -0
- tests/utils/test_profiling.py +208 -0
- tests/utils/test_rankfilter_dist.py +77 -0
- tests/utils/test_require_pkg.py +83 -0
- tests/utils/test_sample_slices.py +43 -0
- tests/utils/test_set_determinism.py +74 -0
- tests/utils/test_squeeze_unsqueeze.py +71 -0
- tests/utils/test_state_cacher.py +67 -0
- tests/utils/test_torchscript_utils.py +113 -0
- tests/utils/test_version.py +91 -0
- tests/utils/test_version_after.py +65 -0
- tests/utils/type_conversion/__init__.py +10 -0
- tests/utils/type_conversion/test_convert_data_type.py +152 -0
- tests/utils/type_conversion/test_get_equivalent_dtype.py +65 -0
- tests/utils/type_conversion/test_safe_dtype_range.py +99 -0
- tests/visualize/__init__.py +10 -0
- tests/visualize/test_img2tensorboard.py +46 -0
- tests/visualize/test_occlusion_sensitivity.py +128 -0
- tests/visualize/test_plot_2d_or_3d_image.py +74 -0
- tests/visualize/test_vis_cam.py +98 -0
- tests/visualize/test_vis_gradcam.py +211 -0
- tests/visualize/utils/__init__.py +10 -0
- tests/visualize/utils/test_blend_images.py +63 -0
- tests/visualize/utils/test_matshow3d.py +133 -0
- monai_weekly-1.5.dev2506.dist-info/RECORD +0 -427
- {monai_weekly-1.5.dev2506.dist-info → monai_weekly-1.5.dev2507.dist-info}/LICENSE +0 -0
- {monai_weekly-1.5.dev2506.dist-info → monai_weekly-1.5.dev2507.dist-info}/WHEEL +0 -0
@@ -0,0 +1,365 @@
|
|
1
|
+
# Copyright (c) MONAI Consortium
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
3
|
+
# you may not use this file except in compliance with the License.
|
4
|
+
# You may obtain a copy of the License at
|
5
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
6
|
+
# Unless required by applicable law or agreed to in writing, software
|
7
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
8
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
9
|
+
# See the License for the specific language governing permissions and
|
10
|
+
# limitations under the License.
|
11
|
+
|
12
|
+
from __future__ import annotations
|
13
|
+
|
14
|
+
import os
|
15
|
+
import shutil
|
16
|
+
import tempfile
|
17
|
+
import unittest
|
18
|
+
import warnings
|
19
|
+
from glob import glob
|
20
|
+
|
21
|
+
import nibabel as nib
|
22
|
+
import numpy as np
|
23
|
+
import torch
|
24
|
+
from ignite.engine import Events
|
25
|
+
from ignite.metrics import Accuracy
|
26
|
+
|
27
|
+
import monai
|
28
|
+
from monai.data import create_test_image_3d
|
29
|
+
from monai.engines import IterationEvents, SupervisedEvaluator, SupervisedTrainer
|
30
|
+
from monai.handlers import (
|
31
|
+
CheckpointLoader,
|
32
|
+
CheckpointSaver,
|
33
|
+
LrScheduleHandler,
|
34
|
+
MeanDice,
|
35
|
+
StatsHandler,
|
36
|
+
TensorBoardImageHandler,
|
37
|
+
TensorBoardStatsHandler,
|
38
|
+
ValidationHandler,
|
39
|
+
from_engine,
|
40
|
+
)
|
41
|
+
from monai.inferers import SimpleInferer, SlidingWindowInferer
|
42
|
+
from monai.transforms import (
|
43
|
+
Activationsd,
|
44
|
+
AsDiscreted,
|
45
|
+
Compose,
|
46
|
+
EnsureChannelFirstd,
|
47
|
+
KeepLargestConnectedComponentd,
|
48
|
+
LoadImaged,
|
49
|
+
RandCropByPosNegLabeld,
|
50
|
+
RandRotate90d,
|
51
|
+
SaveImage,
|
52
|
+
SaveImaged,
|
53
|
+
ScaleIntensityd,
|
54
|
+
)
|
55
|
+
from monai.utils import optional_import, set_determinism
|
56
|
+
from tests.test_utils import DistTestCase, TimedCall, assert_allclose, skip_if_quick
|
57
|
+
from tests.testing_data.integration_answers import test_integration_value
|
58
|
+
|
59
|
+
SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter")
|
60
|
+
|
61
|
+
TASK = "integration_workflows"
|
62
|
+
|
63
|
+
|
64
|
+
def run_training_test(root_dir, device="cuda:0", amp=False, num_workers=4):
|
65
|
+
images = sorted(glob(os.path.join(root_dir, "img*.nii.gz")))
|
66
|
+
segs = sorted(glob(os.path.join(root_dir, "seg*.nii.gz")))
|
67
|
+
train_files = [{"image": img, "label": seg} for img, seg in zip(images[:20], segs[:20])]
|
68
|
+
val_files = [{"image": img, "label": seg} for img, seg in zip(images[-20:], segs[-20:])]
|
69
|
+
|
70
|
+
# define transforms for image and segmentation
|
71
|
+
train_transforms = Compose(
|
72
|
+
[
|
73
|
+
LoadImaged(keys=["image", "label"]),
|
74
|
+
EnsureChannelFirstd(keys=["image", "label"], channel_dim=-1),
|
75
|
+
ScaleIntensityd(keys=["image", "label"]),
|
76
|
+
RandCropByPosNegLabeld(
|
77
|
+
keys=["image", "label"], label_key="label", spatial_size=[96, 96, 96], pos=1, neg=1, num_samples=4
|
78
|
+
),
|
79
|
+
RandRotate90d(keys=["image", "label"], prob=0.5, spatial_axes=[0, 2]),
|
80
|
+
]
|
81
|
+
)
|
82
|
+
val_transforms = Compose(
|
83
|
+
[
|
84
|
+
LoadImaged(keys=["image", "label"]),
|
85
|
+
EnsureChannelFirstd(keys=["image", "label"], channel_dim=-1),
|
86
|
+
ScaleIntensityd(keys=["image", "label"]),
|
87
|
+
]
|
88
|
+
)
|
89
|
+
|
90
|
+
# create a training data loader
|
91
|
+
train_ds = monai.data.CacheDataset(data=train_files, transform=train_transforms, cache_rate=0.5)
|
92
|
+
# use batch_size=2 to load images and use RandCropByPosNegLabeld to generate 2 x 4 images for network training
|
93
|
+
train_loader = monai.data.DataLoader(train_ds, batch_size=2, shuffle=True, num_workers=num_workers)
|
94
|
+
# create a validation data loader
|
95
|
+
val_ds = monai.data.CacheDataset(data=val_files, transform=val_transforms, cache_rate=1.0)
|
96
|
+
val_loader = monai.data.DataLoader(val_ds, batch_size=1, num_workers=num_workers)
|
97
|
+
|
98
|
+
# create UNet, DiceLoss and Adam optimizer
|
99
|
+
net = monai.networks.nets.UNet(
|
100
|
+
spatial_dims=3,
|
101
|
+
in_channels=1,
|
102
|
+
out_channels=1,
|
103
|
+
channels=(16, 32, 64, 128, 256),
|
104
|
+
strides=(2, 2, 2, 2),
|
105
|
+
num_res_units=2,
|
106
|
+
).to(device)
|
107
|
+
loss = monai.losses.DiceLoss(sigmoid=True)
|
108
|
+
opt = torch.optim.Adam(net.parameters(), 1e-3)
|
109
|
+
lr_scheduler = torch.optim.lr_scheduler.StepLR(opt, step_size=2, gamma=0.1)
|
110
|
+
summary_writer = SummaryWriter(log_dir=root_dir)
|
111
|
+
|
112
|
+
val_postprocessing = Compose(
|
113
|
+
[
|
114
|
+
Activationsd(keys="pred", sigmoid=True),
|
115
|
+
AsDiscreted(keys="pred", threshold=0.5),
|
116
|
+
KeepLargestConnectedComponentd(keys="pred", applied_labels=[1]),
|
117
|
+
]
|
118
|
+
)
|
119
|
+
|
120
|
+
class _TestEvalIterEvents:
|
121
|
+
def attach(self, engine):
|
122
|
+
engine.add_event_handler(IterationEvents.FORWARD_COMPLETED, self._forward_completed)
|
123
|
+
|
124
|
+
def _forward_completed(self, engine):
|
125
|
+
pass
|
126
|
+
|
127
|
+
val_handlers = [
|
128
|
+
StatsHandler(iteration_log=False),
|
129
|
+
TensorBoardStatsHandler(summary_writer=summary_writer, iteration_log=False),
|
130
|
+
TensorBoardImageHandler(
|
131
|
+
log_dir=root_dir, batch_transform=from_engine(["image", "label"]), output_transform=from_engine("pred")
|
132
|
+
),
|
133
|
+
CheckpointSaver(save_dir=root_dir, save_dict={"net": net}, save_key_metric=True),
|
134
|
+
_TestEvalIterEvents(),
|
135
|
+
]
|
136
|
+
|
137
|
+
evaluator = SupervisedEvaluator(
|
138
|
+
device=device,
|
139
|
+
val_data_loader=val_loader,
|
140
|
+
network=net,
|
141
|
+
inferer=SlidingWindowInferer(roi_size=(96, 96, 96), sw_batch_size=4, overlap=0.5),
|
142
|
+
postprocessing=val_postprocessing,
|
143
|
+
key_val_metric={
|
144
|
+
"val_mean_dice": MeanDice(include_background=True, output_transform=from_engine(["pred", "label"]))
|
145
|
+
},
|
146
|
+
additional_metrics={"val_acc": Accuracy(output_transform=from_engine(["pred", "label"]))},
|
147
|
+
metric_cmp_fn=lambda cur, prev: cur >= prev, # if greater or equal, treat as new best metric
|
148
|
+
val_handlers=val_handlers,
|
149
|
+
amp=bool(amp),
|
150
|
+
to_kwargs={"memory_format": torch.preserve_format},
|
151
|
+
amp_kwargs={"dtype": torch.float16 if bool(amp) else torch.float32},
|
152
|
+
)
|
153
|
+
|
154
|
+
train_postprocessing = Compose(
|
155
|
+
[
|
156
|
+
Activationsd(keys="pred", sigmoid=True),
|
157
|
+
AsDiscreted(keys="pred", threshold=0.5),
|
158
|
+
KeepLargestConnectedComponentd(keys="pred", applied_labels=[1]),
|
159
|
+
]
|
160
|
+
)
|
161
|
+
|
162
|
+
class _TestTrainIterEvents:
|
163
|
+
def attach(self, engine):
|
164
|
+
engine.add_event_handler(IterationEvents.FORWARD_COMPLETED, self._forward_completed)
|
165
|
+
engine.add_event_handler(IterationEvents.LOSS_COMPLETED, self._loss_completed)
|
166
|
+
engine.add_event_handler(IterationEvents.BACKWARD_COMPLETED, self._backward_completed)
|
167
|
+
engine.add_event_handler(IterationEvents.MODEL_COMPLETED, self._model_completed)
|
168
|
+
|
169
|
+
def _forward_completed(self, engine):
|
170
|
+
pass
|
171
|
+
|
172
|
+
def _loss_completed(self, engine):
|
173
|
+
pass
|
174
|
+
|
175
|
+
def _backward_completed(self, engine):
|
176
|
+
pass
|
177
|
+
|
178
|
+
def _model_completed(self, engine):
|
179
|
+
pass
|
180
|
+
|
181
|
+
train_handlers = [
|
182
|
+
LrScheduleHandler(lr_scheduler=lr_scheduler, print_lr=True),
|
183
|
+
ValidationHandler(validator=evaluator, interval=2, epoch_level=True),
|
184
|
+
StatsHandler(tag_name="train_loss", output_transform=from_engine("loss", first=True)),
|
185
|
+
TensorBoardStatsHandler(
|
186
|
+
summary_writer=summary_writer, tag_name="train_loss", output_transform=from_engine("loss", first=True)
|
187
|
+
),
|
188
|
+
CheckpointSaver(save_dir=root_dir, save_dict={"net": net, "opt": opt}, save_interval=2, epoch_level=True),
|
189
|
+
_TestTrainIterEvents(),
|
190
|
+
]
|
191
|
+
|
192
|
+
trainer = SupervisedTrainer(
|
193
|
+
device=device,
|
194
|
+
max_epochs=5,
|
195
|
+
train_data_loader=train_loader,
|
196
|
+
network=net,
|
197
|
+
optimizer=opt,
|
198
|
+
loss_function=loss,
|
199
|
+
inferer=SimpleInferer(),
|
200
|
+
postprocessing=train_postprocessing,
|
201
|
+
key_train_metric={"train_acc": Accuracy(output_transform=from_engine(["pred", "label"]))},
|
202
|
+
train_handlers=train_handlers,
|
203
|
+
amp=bool(amp),
|
204
|
+
optim_set_to_none=True,
|
205
|
+
to_kwargs={"memory_format": torch.preserve_format},
|
206
|
+
amp_kwargs={"dtype": torch.float16 if bool(amp) else torch.float32},
|
207
|
+
)
|
208
|
+
trainer.run()
|
209
|
+
|
210
|
+
# test train and validation stats
|
211
|
+
train_stats = trainer.get_stats("output")
|
212
|
+
assert_allclose(train_stats["output"][0]["loss"], trainer.state.output[0]["loss"])
|
213
|
+
val_stats = evaluator.get_stats("metrics")
|
214
|
+
|
215
|
+
return val_stats["best_validation_metric"]
|
216
|
+
|
217
|
+
|
218
|
+
def run_inference_test(root_dir, model_file, device="cuda:0", amp=False, num_workers=4):
|
219
|
+
images = sorted(glob(os.path.join(root_dir, "im*.nii.gz")))
|
220
|
+
segs = sorted(glob(os.path.join(root_dir, "seg*.nii.gz")))
|
221
|
+
val_files = [{"image": img, "label": seg} for img, seg in zip(images, segs)]
|
222
|
+
|
223
|
+
# define transforms for image and segmentation
|
224
|
+
val_transforms = Compose(
|
225
|
+
[
|
226
|
+
LoadImaged(keys=["image", "label"]),
|
227
|
+
EnsureChannelFirstd(keys=["image", "label"], channel_dim=-1),
|
228
|
+
ScaleIntensityd(keys=["image", "label"]),
|
229
|
+
]
|
230
|
+
)
|
231
|
+
|
232
|
+
# create a validation data loader
|
233
|
+
val_ds = monai.data.Dataset(data=val_files, transform=val_transforms)
|
234
|
+
val_loader = monai.data.DataLoader(val_ds, batch_size=1, num_workers=num_workers)
|
235
|
+
|
236
|
+
# create UNet, DiceLoss and Adam optimizer
|
237
|
+
net = monai.networks.nets.UNet(
|
238
|
+
spatial_dims=3,
|
239
|
+
in_channels=1,
|
240
|
+
out_channels=1,
|
241
|
+
channels=(16, 32, 64, 128, 256),
|
242
|
+
strides=(2, 2, 2, 2),
|
243
|
+
num_res_units=2,
|
244
|
+
).to(device)
|
245
|
+
|
246
|
+
val_postprocessing = Compose(
|
247
|
+
[
|
248
|
+
Activationsd(keys="pred", sigmoid=True),
|
249
|
+
AsDiscreted(keys="pred", threshold=0.5),
|
250
|
+
KeepLargestConnectedComponentd(keys="pred", applied_labels=[1]),
|
251
|
+
# test the case that `pred` in `engine.state.output`, while `image_meta_dict` in `engine.state.batch`
|
252
|
+
SaveImaged(keys="pred", output_dir=root_dir, output_postfix="seg_transform"),
|
253
|
+
]
|
254
|
+
)
|
255
|
+
val_handlers = [
|
256
|
+
StatsHandler(iteration_log=False),
|
257
|
+
CheckpointLoader(load_path=f"{model_file}", load_dict={"net": net}),
|
258
|
+
]
|
259
|
+
|
260
|
+
saver = SaveImage(output_dir=root_dir, output_postfix="seg_handler")
|
261
|
+
|
262
|
+
def save_func(engine):
|
263
|
+
for o in from_engine("pred")(engine.state.output):
|
264
|
+
saver(o)
|
265
|
+
|
266
|
+
evaluator = SupervisedEvaluator(
|
267
|
+
device=device,
|
268
|
+
val_data_loader=val_loader,
|
269
|
+
network=net,
|
270
|
+
inferer=SlidingWindowInferer(roi_size=(96, 96, 96), sw_batch_size=4, overlap=0.5),
|
271
|
+
postprocessing=val_postprocessing,
|
272
|
+
key_val_metric={
|
273
|
+
"val_mean_dice": MeanDice(include_background=True, output_transform=from_engine(["pred", "label"]))
|
274
|
+
},
|
275
|
+
additional_metrics={"val_acc": Accuracy(output_transform=from_engine(["pred", "label"]))},
|
276
|
+
val_handlers=val_handlers,
|
277
|
+
amp=bool(amp),
|
278
|
+
)
|
279
|
+
evaluator.add_event_handler(Events.ITERATION_COMPLETED, save_func)
|
280
|
+
evaluator.run()
|
281
|
+
|
282
|
+
return evaluator.state.best_metric
|
283
|
+
|
284
|
+
|
285
|
+
@skip_if_quick
|
286
|
+
class IntegrationWorkflows(DistTestCase):
|
287
|
+
def setUp(self):
|
288
|
+
set_determinism(seed=0)
|
289
|
+
|
290
|
+
self.data_dir = tempfile.mkdtemp()
|
291
|
+
for i in range(40):
|
292
|
+
im, seg = create_test_image_3d(128, 128, 128, num_seg_classes=1, channel_dim=-1)
|
293
|
+
n = nib.Nifti1Image(im, np.eye(4))
|
294
|
+
nib.save(n, os.path.join(self.data_dir, f"img{i:d}.nii.gz"))
|
295
|
+
n = nib.Nifti1Image(seg, np.eye(4))
|
296
|
+
nib.save(n, os.path.join(self.data_dir, f"seg{i:d}.nii.gz"))
|
297
|
+
|
298
|
+
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu:0")
|
299
|
+
monai.config.print_config()
|
300
|
+
|
301
|
+
def tearDown(self):
|
302
|
+
set_determinism(seed=None)
|
303
|
+
shutil.rmtree(self.data_dir)
|
304
|
+
|
305
|
+
def train_and_infer(self, idx=0):
|
306
|
+
results = []
|
307
|
+
set_determinism(seed=0)
|
308
|
+
best_metric = run_training_test(self.data_dir, device=self.device, amp=(idx == 2))
|
309
|
+
model_file = sorted(glob(os.path.join(self.data_dir, "net_key_metric*.pt")))[-1]
|
310
|
+
infer_metric = run_inference_test(self.data_dir, model_file, device=self.device, amp=(idx == 2))
|
311
|
+
|
312
|
+
print("best metric", best_metric)
|
313
|
+
print("infer metric", infer_metric)
|
314
|
+
if idx == 2:
|
315
|
+
self.assertTrue(test_integration_value(TASK, key="best_metric_2", data=best_metric, rtol=1e-2))
|
316
|
+
else:
|
317
|
+
self.assertTrue(test_integration_value(TASK, key="best_metric", data=best_metric, rtol=1e-2))
|
318
|
+
# check inference properties
|
319
|
+
if idx == 2:
|
320
|
+
self.assertTrue(test_integration_value(TASK, key="infer_metric_2", data=infer_metric, rtol=1e-2))
|
321
|
+
else:
|
322
|
+
self.assertTrue(test_integration_value(TASK, key="infer_metric", data=infer_metric, rtol=1e-2))
|
323
|
+
results.append(best_metric)
|
324
|
+
results.append(infer_metric)
|
325
|
+
|
326
|
+
def _test_saved_files(postfix):
|
327
|
+
output_files = sorted(glob(os.path.join(self.data_dir, "img*", f"*{postfix}.nii.gz")))
|
328
|
+
values = []
|
329
|
+
for output in output_files:
|
330
|
+
ave = np.mean(nib.load(output).get_fdata())
|
331
|
+
values.append(ave)
|
332
|
+
if idx == 2:
|
333
|
+
self.assertTrue(test_integration_value(TASK, key="output_sums_2", data=values, rtol=1e-2))
|
334
|
+
else:
|
335
|
+
self.assertTrue(test_integration_value(TASK, key="output_sums", data=values, rtol=1e-2))
|
336
|
+
|
337
|
+
_test_saved_files(postfix="seg_handler")
|
338
|
+
_test_saved_files(postfix="seg_transform")
|
339
|
+
try:
|
340
|
+
os.remove(model_file)
|
341
|
+
except Exception as e:
|
342
|
+
warnings.warn(f"Fail to remove {model_file}: {e}.")
|
343
|
+
if torch.cuda.is_available():
|
344
|
+
try:
|
345
|
+
torch.cuda.empty_cache()
|
346
|
+
except Exception:
|
347
|
+
pass
|
348
|
+
|
349
|
+
return results
|
350
|
+
|
351
|
+
def test_training(self):
|
352
|
+
repeated = []
|
353
|
+
test_rounds = 3
|
354
|
+
for i in range(test_rounds):
|
355
|
+
results = self.train_and_infer(idx=i)
|
356
|
+
repeated.append(results)
|
357
|
+
np.testing.assert_allclose(repeated[0], repeated[1])
|
358
|
+
|
359
|
+
@TimedCall(seconds=300, skip_timing=not torch.cuda.is_available(), daemon=False)
|
360
|
+
def test_timing(self):
|
361
|
+
self.train_and_infer(idx=2)
|
362
|
+
|
363
|
+
|
364
|
+
if __name__ == "__main__":
|
365
|
+
unittest.main()
|
@@ -0,0 +1,173 @@
|
|
1
|
+
# Copyright (c) MONAI Consortium
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
3
|
+
# you may not use this file except in compliance with the License.
|
4
|
+
# You may obtain a copy of the License at
|
5
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
6
|
+
# Unless required by applicable law or agreed to in writing, software
|
7
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
8
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
9
|
+
# See the License for the specific language governing permissions and
|
10
|
+
# limitations under the License.
|
11
|
+
|
12
|
+
from __future__ import annotations
|
13
|
+
|
14
|
+
import os
|
15
|
+
import shutil
|
16
|
+
import tempfile
|
17
|
+
import unittest
|
18
|
+
from glob import glob
|
19
|
+
|
20
|
+
import numpy as np
|
21
|
+
import torch
|
22
|
+
|
23
|
+
import monai
|
24
|
+
from monai.data import create_test_image_2d
|
25
|
+
from monai.engines import AdversarialTrainer
|
26
|
+
from monai.handlers import CheckpointSaver, StatsHandler, TensorBoardStatsHandler
|
27
|
+
from monai.networks.nets import AutoEncoder, Discriminator
|
28
|
+
from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, RandFlipd, ScaleIntensityd
|
29
|
+
from monai.utils import AdversarialKeys as Keys
|
30
|
+
from monai.utils import CommonKeys, optional_import, set_determinism
|
31
|
+
from tests.test_utils import DistTestCase, TimedCall, skip_if_quick
|
32
|
+
|
33
|
+
nib, has_nibabel = optional_import("nibabel")
|
34
|
+
|
35
|
+
|
36
|
+
def run_training_test(root_dir, device="cuda:0"):
|
37
|
+
learning_rate = 2e-4
|
38
|
+
real_label = 1
|
39
|
+
fake_label = 0
|
40
|
+
|
41
|
+
real_images = sorted(glob(os.path.join(root_dir, "img*.nii.gz")))
|
42
|
+
train_files = [{CommonKeys.IMAGE: img, CommonKeys.LABEL: img} for img in zip(real_images)]
|
43
|
+
|
44
|
+
# prepare real data
|
45
|
+
train_transforms = Compose(
|
46
|
+
[
|
47
|
+
LoadImaged(keys=[CommonKeys.IMAGE, CommonKeys.LABEL]),
|
48
|
+
EnsureChannelFirstd(keys=[CommonKeys.IMAGE, CommonKeys.LABEL], channel_dim=2),
|
49
|
+
ScaleIntensityd(keys=[CommonKeys.IMAGE]),
|
50
|
+
RandFlipd(keys=[CommonKeys.IMAGE, CommonKeys.LABEL], prob=0.5),
|
51
|
+
]
|
52
|
+
)
|
53
|
+
train_ds = monai.data.CacheDataset(data=train_files, transform=train_transforms, cache_rate=0.5)
|
54
|
+
train_loader = monai.data.DataLoader(train_ds, batch_size=2, shuffle=True, num_workers=4)
|
55
|
+
|
56
|
+
# Create Discriminator
|
57
|
+
discriminator_net = Discriminator(
|
58
|
+
in_shape=(1, 64, 64), channels=(8, 16, 32, 64, 1), strides=(2, 2, 2, 2, 1), num_res_units=1, kernel_size=5
|
59
|
+
).to(device)
|
60
|
+
discriminator_opt = torch.optim.Adam(discriminator_net.parameters(), learning_rate)
|
61
|
+
discriminator_loss_criterion = torch.nn.BCELoss()
|
62
|
+
|
63
|
+
def discriminator_loss(real_logits, fake_logits):
|
64
|
+
real_target = real_logits.new_full((real_logits.shape[0], 1), real_label)
|
65
|
+
fake_target = fake_logits.new_full((fake_logits.shape[0], 1), fake_label)
|
66
|
+
real_loss = discriminator_loss_criterion(real_logits, real_target)
|
67
|
+
fake_loss = discriminator_loss_criterion(fake_logits.detach(), fake_target)
|
68
|
+
return torch.div(torch.add(real_loss, fake_loss), 2)
|
69
|
+
|
70
|
+
# Create Generator
|
71
|
+
generator_network = AutoEncoder(
|
72
|
+
spatial_dims=2,
|
73
|
+
in_channels=1,
|
74
|
+
out_channels=1,
|
75
|
+
channels=(8, 16, 32, 64),
|
76
|
+
strides=(2, 2, 2, 2),
|
77
|
+
num_res_units=1,
|
78
|
+
num_inter_units=1,
|
79
|
+
)
|
80
|
+
generator_network = generator_network.to(device)
|
81
|
+
generator_optimiser = torch.optim.Adam(generator_network.parameters(), learning_rate)
|
82
|
+
generator_loss_criterion = torch.nn.MSELoss()
|
83
|
+
|
84
|
+
def reconstruction_loss(recon_images, real_images):
|
85
|
+
return generator_loss_criterion(recon_images, real_images)
|
86
|
+
|
87
|
+
def generator_loss(fake_logits):
|
88
|
+
fake_target = fake_logits.new_full((fake_logits.shape[0], 1), real_label)
|
89
|
+
recon_loss = discriminator_loss_criterion(fake_logits.detach(), fake_target)
|
90
|
+
return recon_loss
|
91
|
+
|
92
|
+
key_train_metric = None
|
93
|
+
|
94
|
+
train_handlers = [
|
95
|
+
StatsHandler(
|
96
|
+
name="training_loss",
|
97
|
+
output_transform=lambda x: {
|
98
|
+
Keys.RECONSTRUCTION_LOSS: x[Keys.RECONSTRUCTION_LOSS],
|
99
|
+
Keys.DISCRIMINATOR_LOSS: x[Keys.DISCRIMINATOR_LOSS],
|
100
|
+
Keys.GENERATOR_LOSS: x[Keys.GENERATOR_LOSS],
|
101
|
+
},
|
102
|
+
),
|
103
|
+
TensorBoardStatsHandler(
|
104
|
+
log_dir=root_dir,
|
105
|
+
tag_name="training_loss",
|
106
|
+
output_transform=lambda x: {
|
107
|
+
Keys.RECONSTRUCTION_LOSS: x[Keys.RECONSTRUCTION_LOSS],
|
108
|
+
Keys.DISCRIMINATOR_LOSS: x[Keys.DISCRIMINATOR_LOSS],
|
109
|
+
Keys.GENERATOR_LOSS: x[Keys.GENERATOR_LOSS],
|
110
|
+
},
|
111
|
+
),
|
112
|
+
CheckpointSaver(
|
113
|
+
save_dir=root_dir,
|
114
|
+
save_dict={"g_net": generator_network, "d_net": discriminator_net},
|
115
|
+
save_interval=2,
|
116
|
+
epoch_level=True,
|
117
|
+
),
|
118
|
+
]
|
119
|
+
|
120
|
+
num_epochs = 5
|
121
|
+
|
122
|
+
trainer = AdversarialTrainer(
|
123
|
+
device=device,
|
124
|
+
max_epochs=num_epochs,
|
125
|
+
train_data_loader=train_loader,
|
126
|
+
g_network=generator_network,
|
127
|
+
g_optimizer=generator_optimiser,
|
128
|
+
g_loss_function=generator_loss,
|
129
|
+
recon_loss_function=reconstruction_loss,
|
130
|
+
d_network=discriminator_net,
|
131
|
+
d_optimizer=discriminator_opt,
|
132
|
+
d_loss_function=discriminator_loss,
|
133
|
+
non_blocking=True,
|
134
|
+
key_train_metric=key_train_metric,
|
135
|
+
train_handlers=train_handlers,
|
136
|
+
)
|
137
|
+
trainer.run()
|
138
|
+
|
139
|
+
return trainer.state
|
140
|
+
|
141
|
+
|
142
|
+
@skip_if_quick
|
143
|
+
@unittest.skipUnless(has_nibabel, "Requires nibabel library.")
|
144
|
+
class IntegrationWorkflowsAdversarialTrainer(DistTestCase):
|
145
|
+
def setUp(self):
|
146
|
+
set_determinism(seed=0)
|
147
|
+
|
148
|
+
self.data_dir = tempfile.mkdtemp()
|
149
|
+
for i in range(40):
|
150
|
+
im, _ = create_test_image_2d(64, 64, num_objs=3, rad_max=14, num_seg_classes=1, channel_dim=-1)
|
151
|
+
n = nib.Nifti1Image(im, np.eye(4))
|
152
|
+
nib.save(n, os.path.join(self.data_dir, f"img{i:d}.nii.gz"))
|
153
|
+
|
154
|
+
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu:0")
|
155
|
+
monai.config.print_config()
|
156
|
+
|
157
|
+
def tearDown(self):
|
158
|
+
set_determinism(seed=None)
|
159
|
+
shutil.rmtree(self.data_dir)
|
160
|
+
|
161
|
+
@TimedCall(seconds=200, daemon=False)
|
162
|
+
def test_training(self):
|
163
|
+
torch.manual_seed(0)
|
164
|
+
|
165
|
+
finish_state = run_training_test(self.data_dir, device=self.device)
|
166
|
+
|
167
|
+
# Assert AdversarialTrainer training finished
|
168
|
+
self.assertEqual(finish_state.iteration, 100)
|
169
|
+
self.assertEqual(finish_state.epoch, 5)
|
170
|
+
|
171
|
+
|
172
|
+
if __name__ == "__main__":
|
173
|
+
unittest.main()
|
@@ -0,0 +1,158 @@
|
|
1
|
+
# Copyright (c) MONAI Consortium
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
3
|
+
# you may not use this file except in compliance with the License.
|
4
|
+
# You may obtain a copy of the License at
|
5
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
6
|
+
# Unless required by applicable law or agreed to in writing, software
|
7
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
8
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
9
|
+
# See the License for the specific language governing permissions and
|
10
|
+
# limitations under the License.
|
11
|
+
|
12
|
+
from __future__ import annotations
|
13
|
+
|
14
|
+
import os
|
15
|
+
import shutil
|
16
|
+
import tempfile
|
17
|
+
import unittest
|
18
|
+
from glob import glob
|
19
|
+
|
20
|
+
import nibabel as nib
|
21
|
+
import numpy as np
|
22
|
+
import torch
|
23
|
+
|
24
|
+
import monai
|
25
|
+
from monai.data import create_test_image_2d
|
26
|
+
from monai.engines import GanTrainer
|
27
|
+
from monai.handlers import CheckpointSaver, StatsHandler, TensorBoardStatsHandler
|
28
|
+
from monai.networks import normal_init
|
29
|
+
from monai.networks.nets import Discriminator, Generator
|
30
|
+
from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, RandFlipd, ScaleIntensityd
|
31
|
+
from monai.utils import GanKeys as Keys
|
32
|
+
from monai.utils import set_determinism
|
33
|
+
from tests.test_utils import DistTestCase, TimedCall, skip_if_quick
|
34
|
+
|
35
|
+
|
36
|
+
def run_training_test(root_dir, device="cuda:0"):
|
37
|
+
real_images = sorted(glob(os.path.join(root_dir, "img*.nii.gz")))
|
38
|
+
train_files = [{"reals": img} for img in zip(real_images)]
|
39
|
+
|
40
|
+
# prepare real data
|
41
|
+
train_transforms = Compose(
|
42
|
+
[
|
43
|
+
LoadImaged(keys=["reals"]),
|
44
|
+
EnsureChannelFirstd(keys=["reals"], channel_dim=-1),
|
45
|
+
ScaleIntensityd(keys=["reals"]),
|
46
|
+
RandFlipd(keys=["reals"], prob=0.5),
|
47
|
+
]
|
48
|
+
)
|
49
|
+
train_ds = monai.data.CacheDataset(data=train_files, transform=train_transforms, cache_rate=0.5)
|
50
|
+
train_loader = monai.data.DataLoader(train_ds, batch_size=2, shuffle=True, num_workers=4)
|
51
|
+
|
52
|
+
learning_rate = 2e-4
|
53
|
+
betas = (0.5, 0.999)
|
54
|
+
real_label = 1
|
55
|
+
fake_label = 0
|
56
|
+
|
57
|
+
# create discriminator
|
58
|
+
disc_net = Discriminator(
|
59
|
+
in_shape=(1, 64, 64), channels=(8, 16, 32, 64, 1), strides=(2, 2, 2, 2, 1), num_res_units=1, kernel_size=5
|
60
|
+
).to(device)
|
61
|
+
disc_net.apply(normal_init)
|
62
|
+
disc_opt = torch.optim.Adam(disc_net.parameters(), learning_rate, betas=betas)
|
63
|
+
disc_loss_criterion = torch.nn.BCELoss()
|
64
|
+
|
65
|
+
def discriminator_loss(gen_images, real_images):
|
66
|
+
real = real_images.new_full((real_images.shape[0], 1), real_label)
|
67
|
+
gen = gen_images.new_full((gen_images.shape[0], 1), fake_label)
|
68
|
+
realloss = disc_loss_criterion(disc_net(real_images), real)
|
69
|
+
genloss = disc_loss_criterion(disc_net(gen_images.detach()), gen)
|
70
|
+
return torch.div(torch.add(realloss, genloss), 2)
|
71
|
+
|
72
|
+
# create generator
|
73
|
+
latent_size = 64
|
74
|
+
gen_net = Generator(
|
75
|
+
latent_shape=latent_size, start_shape=(latent_size, 8, 8), channels=[32, 16, 8, 1], strides=[2, 2, 2, 1]
|
76
|
+
)
|
77
|
+
gen_net.apply(normal_init)
|
78
|
+
gen_net.conv.add_module("activation", torch.nn.Sigmoid())
|
79
|
+
gen_net = gen_net.to(device)
|
80
|
+
gen_opt = torch.optim.Adam(gen_net.parameters(), learning_rate, betas=betas)
|
81
|
+
gen_loss_criterion = torch.nn.BCELoss()
|
82
|
+
|
83
|
+
def generator_loss(gen_images):
|
84
|
+
output = disc_net(gen_images)
|
85
|
+
cats = output.new_full(output.shape, real_label)
|
86
|
+
return gen_loss_criterion(output, cats)
|
87
|
+
|
88
|
+
key_train_metric = None
|
89
|
+
|
90
|
+
train_handlers = [
|
91
|
+
StatsHandler(
|
92
|
+
name="training_loss", output_transform=lambda x: {Keys.GLOSS: x[Keys.GLOSS], Keys.DLOSS: x[Keys.DLOSS]}
|
93
|
+
),
|
94
|
+
TensorBoardStatsHandler(
|
95
|
+
log_dir=root_dir,
|
96
|
+
tag_name="training_loss",
|
97
|
+
output_transform=lambda x: {Keys.GLOSS: x[Keys.GLOSS], Keys.DLOSS: x[Keys.DLOSS]},
|
98
|
+
),
|
99
|
+
CheckpointSaver(
|
100
|
+
save_dir=root_dir, save_dict={"g_net": gen_net, "d_net": disc_net}, save_interval=2, epoch_level=True
|
101
|
+
),
|
102
|
+
]
|
103
|
+
|
104
|
+
disc_train_steps = 2
|
105
|
+
num_epochs = 5
|
106
|
+
|
107
|
+
trainer = GanTrainer(
|
108
|
+
device,
|
109
|
+
num_epochs,
|
110
|
+
train_loader,
|
111
|
+
gen_net,
|
112
|
+
gen_opt,
|
113
|
+
generator_loss,
|
114
|
+
disc_net,
|
115
|
+
disc_opt,
|
116
|
+
discriminator_loss,
|
117
|
+
d_train_steps=disc_train_steps,
|
118
|
+
latent_shape=latent_size,
|
119
|
+
key_train_metric=key_train_metric,
|
120
|
+
train_handlers=train_handlers,
|
121
|
+
to_kwargs={"memory_format": torch.preserve_format, "dtype": torch.float32},
|
122
|
+
)
|
123
|
+
trainer.run()
|
124
|
+
|
125
|
+
return trainer.state
|
126
|
+
|
127
|
+
|
128
|
+
@skip_if_quick
|
129
|
+
class IntegrationWorkflowsGAN(DistTestCase):
|
130
|
+
def setUp(self):
|
131
|
+
set_determinism(seed=0)
|
132
|
+
|
133
|
+
self.data_dir = tempfile.mkdtemp()
|
134
|
+
for i in range(40):
|
135
|
+
im, _ = create_test_image_2d(64, 64, num_objs=3, rad_max=14, num_seg_classes=1, channel_dim=-1)
|
136
|
+
n = nib.Nifti1Image(im, np.eye(4))
|
137
|
+
nib.save(n, os.path.join(self.data_dir, f"img{i:d}.nii.gz"))
|
138
|
+
|
139
|
+
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu:0")
|
140
|
+
monai.config.print_config()
|
141
|
+
|
142
|
+
def tearDown(self):
|
143
|
+
set_determinism(seed=None)
|
144
|
+
shutil.rmtree(self.data_dir)
|
145
|
+
|
146
|
+
@TimedCall(seconds=200, daemon=False)
|
147
|
+
def test_training(self):
|
148
|
+
torch.manual_seed(0)
|
149
|
+
|
150
|
+
finish_state = run_training_test(self.data_dir, device=self.device)
|
151
|
+
|
152
|
+
# assert GAN training finished
|
153
|
+
self.assertEqual(finish_state.iteration, 100)
|
154
|
+
self.assertEqual(finish_state.epoch, 5)
|
155
|
+
|
156
|
+
|
157
|
+
if __name__ == "__main__":
|
158
|
+
unittest.main()
|