Exemplo n.º 1
0
    def reveal_anonymized_files(self, directory):
        ph.create_directory(directory)

        filenames_revealed = []
        for i in range(0, len(self._filenames)):
            basename_anonymized = os.path.basename(self._filenames[i])
            filename_anonymized = ph.strip_filename_extension(
                basename_anonymized)[0]
            try:
                basename_revealed = self._dictionary[basename_anonymized]
            except KeyError:
                raise IOError(
                    "Dictionary does not match given (anonymized) filenames")
            filename_revealed = "%s_%s" % (filename_anonymized,
                                           basename_revealed)

            # filename_anonymized = self._identifiers[i] + filename_extension
            # filename_revealed = self._identifiers[i] + "_" + \
            #     self._dictionary[self._identifiers[i]] + filename_extension
            # filename_revealed = re.sub("_masked_srr", "", filename_revealed)

            # path_to_file_anon = os.path.join(directory, filename_anonymized)
            path_to_file_reve = os.path.join(directory, filename_revealed)

            # if not os.path.isfile(path_to_file_anon):
            #     print("%s: Nothing to reveal" % (filename_anonymized))

            cmd = "cp -p "
            cmd += self._filenames[i] + " "
            cmd += path_to_file_reve + " "
            # print(cmd)
            ph.execute_command(cmd)

            filenames_revealed.append(filename_revealed)
        return filenames_revealed
Exemplo n.º 2
0
def _resize_image(path_to_file, resize):

    factor = resize * 100
    cmd_args = []
    cmd_args.append("%s" % path_to_file)
    cmd_args.append("-resize %dx%d%%\\!" % (factor, factor))
    cmd = "convert %s %s" % ((" ").join(cmd_args), path_to_file)
    ph.execute_command(cmd, verbose=False)
Exemplo n.º 3
0
    def create_video(self, path_to_video, dir_input_slices, fps=1):

        dir_output_video = os.path.dirname(path_to_video)
        filename = os.path.basename(path_to_video).split(".")[0]
        path_to_slices = "%s*.png" % os.path.join(dir_input_slices, filename)
        path_to_video = os.path.join(dir_output_video, "%s.mp4" % filename)

        path_to_video_tmp = os.path.join(
            dir_output_video, "%s_tmp.mp4" % filename)

        # Check that folder containing the slices exist
        if not ph.directory_exists(dir_input_slices):
            raise IOError("Folder '%s' meant to contain exported slices does "
                          "not exist" % dir_input_slices)

        # Check that the folder contains exported slices as png files        
        # if not ph.file_exists(os.path.join(
        #         dir_input_slices, self._get_filename_slice(filename, 1))):
        #     raise IOError(
        #         "Slices '%s' need to be generated first using "
        #         "'export_slices'" % (path_to_slices))

        # Create output folder for video
        ph.create_directory(dir_output_video)

        # ---------------Create temp video from exported slices----------------
        cmd_args = []
        cmd_args.append("-monitor")
        cmd_args.append("-delay %d" % (100. / fps))

        cmd_exe = "convert"

        cmd = "%s %s %s %s" % (
            cmd_exe, (" ").join(cmd_args), path_to_slices, path_to_video_tmp)
        flag = ph.execute_command(cmd)
        if flag != 0:
            raise RuntimeError("Unable to create video from slices")

        # ----------------------Use more common codec (?)----------------------
        cmd_args = []
        # overwrite possibly existing image
        cmd_args.append("-y")
        # Define input video to be converted
        cmd_args.append("-i %s" % path_to_video_tmp)
        # Use H.264 codec for video compression of MP4 file
        cmd_args.append("-vcodec libx264")
        # Define used pixel format
        cmd_args.append("-pix_fmt yuv420p")
        # Avoid error message associated to odd rows
        # (https://stackoverflow.com/questions/20847674/ffmpeg-libx264-height-not-divisible-by-2)
        cmd_args.append("-vf 'scale=trunc(iw/2)*2:trunc(ih/2)*2'")
        cmd = "ffmpeg %s %s" % ((" ").join(cmd_args), path_to_video)
        ph.execute_command(cmd)

        # Delete temp video
        os.remove(path_to_video_tmp)
Exemplo n.º 4
0
def _export_pdf_from_side_by_side_images(directory, path_to_file, extension):

    # Read all sidy-by-side (png) images in directory
    pattern = "[a-zA-Z0-9_]+[.]%s" % extension
    p = re.compile(pattern)
    files = [
        os.path.join(directory, f) for f in os.listdir(directory) if p.match(f)
    ]

    # Convert consecutive sequence of images into single pdf
    files = natsort.natsorted(files, key=lambda y: y.lower())
    cmd = "convert %s %s" % ((" ").join(files), path_to_file)
    ph.execute_command(cmd, verbose=False)
Exemplo n.º 5
0
    def test_reconstruct_volume_from_slices(self):
        filename = "SRR_stacks3_TK1_lsmr_alpha0p02_itermax5.nii.gz"
        output = os.path.join(self.dir_output, filename)
        dir_reference = os.path.join(self.dir_data,
                                     "reconstruct_volume_from_slices")
        dir_input_mc = os.path.join(self.dir_data,
                                    "reconstruct_volume_from_slices",
                                    "motion_correction")
        path_to_reference = os.path.join(dir_reference, filename)

        iter_max = 5
        alpha = 0.02
        intensity_correction = 1

        cmd_args = []
        cmd_args.append("--filenames %s" % " ".join(self.filenames))
        cmd_args.append("--dir-input-mc %s" % dir_input_mc)
        cmd_args.append("--output %s" % output)
        cmd_args.append("--iter-max %d" % iter_max)
        cmd_args.append("--intensity-correction %d" % intensity_correction)
        cmd_args.append("--alpha %f" % alpha)
        cmd_args.append("--reconstruction-space %s" % path_to_reference)

        cmd = "niftymic_reconstruct_volume_from_slices %s" % (
            " ").join(cmd_args)
        self.assertEqual(ph.execute_command(cmd), 0)

        # Check whether identical reconstruction has been created
        reconstruction_sitk = sitkh.read_nifti_image_sitk(output)
        reference_sitk = sitkh.read_nifti_image_sitk(path_to_reference)

        difference_sitk = reconstruction_sitk - reference_sitk
        error = np.linalg.norm(sitk.GetArrayFromImage(difference_sitk))

        self.assertAlmostEqual(error, 0, places=self.precision)
Exemplo n.º 6
0
    def test_reconstruct_volume_from_slices(self):
        filename = "bold_s2v.nii.gz"
        output = os.path.join(self.dir_output, filename)
        dir_reference = os.path.join(
            self.dir_data, "reconstruct_volume_from_slices")
        dir_input_mc = os.path.join(
            self.dir_data, "reconstruct_volume_from_slices", "motion_correction")
        path_to_reference = os.path.join(dir_reference, filename)

        iter_max = 3
        alpha = 0.05

        cmd_args = []
        exe = os.path.abspath(rsfmri_reconstruct_volume_from_slices.__file__)
        cmd_args = ["python %s" % exe]
        cmd_args.append("--filename %s" % self.filename)
        cmd_args.append("--filename-mask %s" % ph.append_to_filename(
            self.filename, self.suffix_mask))
        cmd_args.append("--dir-input-mc %s" % dir_input_mc)
        cmd_args.append("--output %s" % output)
        cmd_args.append("--iter-max %d" % iter_max)
        cmd_args.append("--alpha %f" % alpha)
        cmd = (" ").join(cmd_args)
        self.assertEqual(ph.execute_command(cmd), 0)

        # Check whether identical reconstruction has been created
        reconstruction_sitk = sitkh.read_sitk_vector_image(output)
        reference_sitk = sitkh.read_sitk_vector_image(path_to_reference)

        difference_sitk = reconstruction_sitk - reference_sitk
        error = np.linalg.norm(sitk.GetArrayFromImage(difference_sitk))

        self.assertAlmostEqual(error, 0, places=self.precision)
Exemplo n.º 7
0
def main():
    pid = "49"
    method     = "manual" #auto, manual
    input_dir  = "{0:}/input".format(pid)
    mask_dir   = "{0:}/mask_{1:}/mask".format(pid, method)
    output_dir = "{0:}/input_preprocess".format(pid)

    # get input stack names
    files = os.listdir(input_dir)
    input_files = []
    mask_files  = []
    for file in files:
        if (("nii.gz" in file)):
            input_files.append("{0:}/{1:}".format(input_dir, file))
            mask_name = "{0:}/{1:}".format(mask_dir, file)
            assert(os.path.isfile(mask_name))
            mask_files.append(mask_name)

    cmd_args = []
    cmd_args.append("--filenames %s" % (" ").join(input_files))
    cmd_args.append("--filenames-masks %s" % (" ").join(mask_files))
    cmd_args.append("--dir-output %s" % output_dir)
    cmd_args.append("--prefix-output ''")
    cmd = "niftymic_correct_bias_field %s" % (" ").join(cmd_args)
    time_start_bias = ph.start_timing()
    exit_code = ph.execute_command(cmd)
    elapsed_time_bias = ph.stop_timing(time_start_bias)
    print("Computational Time for Bias Field Correction: %s" %
          elapsed_time_bias)
    if exit_code != 0:
        raise RuntimeError("Bias field correction failed")
    return 0
Exemplo n.º 8
0
    def test_reconstruct_volume(self):
        dir_root = os.path.join(self.dir_data, "reconstruct_volume")
        dir_input = os.path.join(dir_root, "input-data")
        dir_reference = os.path.join(dir_root, "result-comparison")
        filename_reference = "SRR_stacks3_TK1_lsmr_alpha0p02_itermax5.nii.gz"
        path_to_reference = os.path.join(dir_reference, filename_reference)

        two_step_cycles = 1
        iter_max = 5

        cmd_args = []
        cmd_args.append("--dir-input %s" % dir_input)
        cmd_args.append("--dir-output %s" % self.dir_output)
        cmd_args.append("--two-step-cycles %s" % two_step_cycles)
        cmd_args.append("--iter-max %s" % iter_max)

        cmd = "niftymic_reconstruct_volume %s" % (
            " ").join(cmd_args)
        self.assertEqual(ph.execute_command(cmd), 0)

        # Check whether identical reconstruction has been created
        path_to_reconstruction = os.path.join(
            self.dir_output, filename_reference)
        reconstruction_sitk = sitk.ReadImage(path_to_reconstruction)
        reference_sitk = sitk.ReadImage(path_to_reference)

        difference_sitk = reconstruction_sitk - reference_sitk
        error = np.linalg.norm(sitk.GetArrayFromImage(difference_sitk))

        self.assertAlmostEqual(error, 0, places=self.precision)
    def test_register_landmarks(self):
        path_to_fixed_landmarks = os.path.join(
            DIR_TEST, "3D_Brain_Template_landmarks.txt")
        path_to_moving_landmarks = os.path.join(DIR_TEST,
                                                "3D_Brain_AD_landmarks.txt")
        path_to_reference = os.path.join(
            DIR_TEST, "landmark_transform_3D_Brain_Source_to_Target_CPD.txt")
        path_to_result = os.path.join(DIR_TMP, "registration_transform.txt")

        exe = re.sub(".pyc", ".py",
                     os.path.abspath(register_landmarks.__file__))
        cmd_args = ["python %s" % exe]
        cmd_args.append("--output %s" % path_to_result)
        cmd_args.append("--fixed %s" % path_to_fixed_landmarks)
        cmd_args.append("--moving %s" % path_to_moving_landmarks)
        cmd_args.append("--verbose %s" % self.verbose)
        cmd = " ".join(cmd_args)
        flag = ph.execute_command(cmd, verbose=self.verbose)
        if flag != 0:
            raise RuntimeError("Cannot execute command '%s'" % cmd)

        transform_result_sitk = sitk.Euler3DTransform(
            sitk.ReadTransform(path_to_result))
        transform_reference_sitk = sitk.Euler3DTransform(
            sitk.ReadTransform(path_to_reference))
        result = np.array(transform_result_sitk.GetParameters())
        reference = np.array(transform_reference_sitk.GetParameters())

        self.assertAlmostEqual(np.sum(np.abs(result - reference)),
                               0,
                               places=self.precision)
    def test_estimate_landmarks(self):
        for image in ["3D_Brain_Template", "3D_Brain_AD"]:
            path_to_image_fiducials = os.path.join(
                DIR_TEST, "%s_fiducials.nii.gz" % image)
            path_to_reference = os.path.join(DIR_TEST,
                                             "%s_landmarks.txt" % image)
            path_to_result = os.path.join(DIR_TMP, "%s_result.txt" % image)

            exe = re.sub(".pyc", ".py",
                         os.path.abspath(estimate_landmarks.__file__))
            cmd_args = ["python %s" % exe]
            cmd_args.append("--output %s" % path_to_result)
            cmd_args.append("--filename %s" % path_to_image_fiducials)
            # cmd_args.append("--clusters 4")
            cmd_args.append("--verbose %s" % self.verbose)
            cmd = " ".join(cmd_args)
            flag = ph.execute_command(cmd, verbose=self.verbose)
            if flag != 0:
                raise RuntimeError("Cannot execute command '%s'" % cmd)

            result = np.loadtxt(path_to_result)
            reference = np.loadtxt(path_to_reference)

            # Find closest point
            indices = [
                np.argmin(np.linalg.norm(result[i, :] - reference, axis=1))
                for i in range(result.shape[0])
            ]
            reference = [reference[i, :] for i in indices]

            self.assertAlmostEqual(np.sum(np.abs(result - reference)),
                                   0,
                                   places=self.precision)
Exemplo n.º 11
0
    def test_resample_oriented_gaussian_spacing_atg(self):
        moving = os.path.join(DIR_DATA, "3D_SheppLoganPhantom_64.nii.gz")
        fixed = os.path.join(DIR_TMP, "3D_SheppLoganPhantom_64_rotated.nii.gz")
        rotation = sitk.Euler3DTransform()
        rotation.SetRotation(0.3, -0.2, -0.3)
        rotation.SetCenter((-40, -25, 17))
        image_rotated = utils.update_image_header(sitk.ReadImage(moving),
                                                  rotation)
        sitk.WriteImage(image_rotated, fixed)

        reference = os.path.join(
            DIR_TEST,
            "3D_SheppLoganPhantom_64_OrientedGaussian_s113_atg4.nii.gz")

        cmd_args = ["python simplereg_resample.py"]
        cmd_args.append("-m %s" % moving)
        cmd_args.append("-f %s" % fixed)
        cmd_args.append("-i OrientedGaussian")
        cmd_args.append("-s 1 1 3")
        cmd_args.append("-atg 4")
        cmd_args.append("-p -1000")
        cmd_args.append("-o %s" % self.output_image)
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_sitk = sitk.ReadImage(self.output_image)
        ref_sitk = sitk.ReadImage(reference)
        diff_nda = sitk.GetArrayFromImage(res_sitk - ref_sitk)
        self.assertAlmostEqual(np.linalg.norm(diff_nda),
                               0,
                               places=self.precision)
    def test_fetal_brain_seg(self):

        dir_output = os.path.join(DIR_TMP, "seg")
        cmd_args = ["niftymic_segment_fetal_brains"]
        cmd_args.append("--filenames %s" % self.path_to_image)
        cmd_args.append("--dir-output %s" % dir_output)
        # cmd_args.append("--verbose 1")
        cmd = " ".join(cmd_args)

        flag = ph.execute_command(cmd)
Exemplo n.º 13
0
def _export_image_side_by_side(
    nda_left,
    nda_right,
    label_left,
    label_right,
    path_to_file,
    ctr,
    resize,
    extension,
    border=10,
    background="black",
    fill_ctr="orange",
    fill_label="white",
    font="Arial",
    pointsize=12,
):

    dir_output = os.path.join(DIR_TMP, "ImageMagick", "side-by-side")
    ph.clear_directory(dir_output, verbose=False)

    path_to_left = os.path.join(dir_output, "left.%s" % extension)
    path_to_right = os.path.join(dir_output, "right.%s" % extension)

    ph.write_image(nda_left, path_to_left, verbose=False)
    ph.write_image(nda_right, path_to_right, verbose=False)

    _resize_image(path_to_left, resize=resize)
    _resize_image(path_to_right, resize=resize)

    cmd_args = []
    cmd_args.append("-geometry +%d+%d" % (border, border))
    cmd_args.append("-background %s" % background)
    cmd_args.append("-font %s" % font)
    cmd_args.append("-pointsize %s" % pointsize)
    cmd_args.append("-fill %s" % fill_ctr)
    cmd_args.append("-gravity SouthWest -draw \"text 0,0 '%d'\"" % ctr)
    cmd_args.append("-fill %s" % fill_label)
    cmd_args.append("-label '%s' %s" % (label_left, path_to_left))
    cmd_args.append("-label '%s' %s" % (label_right, path_to_right))
    cmd_args.append("%s" % path_to_file)
    cmd = "montage %s" % (" ").join(cmd_args)
    ph.execute_command(cmd, verbose=False)
Exemplo n.º 14
0
    def test_transform_sitk_to_regaladin(self):
        cmd_args = ["python simplereg_transform.py"]
        cmd_args.append("-sitk2nreg %s %s" %
                        (self.transform_3D_sitk, self.output_transform))
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_nda = dr.DataReader.read_transform_nreg(self.output_transform)
        ref_nda = dr.DataReader.read_transform_nreg(self.transform_3D_nreg)
        self.assertAlmostEqual(np.linalg.norm(ref_nda - res_nda),
                               0,
                               places=self.precision)
Exemplo n.º 15
0
    def test_estimate_motion(self):
        filename = "SRR_reference.nii.gz"
        output = os.path.join(self.dir_output, filename)
        dir_reference = os.path.join(self.dir_data, "estimate_motion")
        dir_reference_mc = os.path.join(dir_reference, "motion_correction")
        path_to_reference = os.path.join(dir_reference, filename)
        path_to_reference_mask = ph.append_to_filename(
            os.path.join(dir_reference, filename), self.suffix_mask)

        two_step_cycles = 1
        iter_max = 5

        exe = os.path.abspath(rsfmri_estimate_motion.__file__)
        cmd_args = ["python %s" % exe]
        cmd_args.append("--filename %s" % self.filename)
        cmd_args.append("--filename-mask %s" % ph.append_to_filename(
            self.filename, self.suffix_mask))
        cmd_args.append("--dir-output %s" % self.dir_output)
        cmd_args.append("--two-step-cycles %s" % two_step_cycles)
        cmd_args.append("--iter-max %d" % iter_max)
        cmd = (" ").join(cmd_args)
        self.assertEqual(ph.execute_command(cmd), 0)

        # Check SRR volume
        res_sitk = sitkh.read_nifti_image_sitk(output)
        ref_sitk = sitkh.read_nifti_image_sitk(path_to_reference)
        diff_sitk = res_sitk - ref_sitk
        error = np.linalg.norm(sitk.GetArrayFromImage(diff_sitk))
        self.assertAlmostEqual(error, 0, places=self.precision)

        # Check SRR mask volume
        res_sitk = sitkh.read_nifti_image_sitk(
            ph.append_to_filename(output, self.suffix_mask))
        ref_sitk = sitkh.read_nifti_image_sitk(path_to_reference_mask)
        diff_sitk = res_sitk - ref_sitk
        error = np.linalg.norm(sitk.GetArrayFromImage(diff_sitk))
        self.assertAlmostEqual(error, 0, places=self.precision)

        # Check transforms
        pattern = REGEX_FILENAMES + "[.]tfm"
        p = re.compile(pattern)
        dir_res_mc = os.path.join(self.dir_output, "motion_correction")
        trafos_res = sorted(
            [os.path.join(dir_res_mc, t)
             for t in os.listdir(dir_res_mc) if p.match(t)])
        trafos_ref = sorted(
            [os.path.join(dir_reference_mc, t)
             for t in os.listdir(dir_reference_mc) if p.match(t)])
        self.assertEqual(len(trafos_res), len(trafos_ref))
        for i in range(len(trafos_ref)):
            nda_res = sitkh.read_transform_sitk(trafos_res[i]).GetParameters()
            nda_ref = sitkh.read_transform_sitk(trafos_ref[i]).GetParameters()
            nda_diff = np.linalg.norm(np.array(nda_res) - nda_ref)
            self.assertAlmostEqual(nda_diff, 0, places=self.precision)
Exemplo n.º 16
0
    def test_transform_flirt_to_sitk(self):
        cmd_args = ["python simplereg_transform.py"]
        cmd_args.append("-flirt2sitk %s %s %s %s" %
                        (self.transform_3D_flirt, self.image_3D,
                         self.image_3D_moving, self.output_transform))
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_sitk = dr.DataReader.read_transform(self.output_transform)
        ref_sitk = dr.DataReader.read_transform(self.transform_3D_sitk)
        res_nda = np.array(res_sitk.GetParameters())
        ref_nda = np.array(ref_sitk.GetParameters())
        self.assertAlmostEqual(np.linalg.norm(ref_nda - res_nda), 0, places=2)
Exemplo n.º 17
0
    def test_transform_swap_sitk_nii(self):
        cmd_args = ["python simplereg_transform.py"]
        cmd_args.append("-sitk2nii %s %s" %
                        (self.landmarks_3D, self.output_landmarks))
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_nda = dr.DataReader.read_landmarks(self.output_landmarks)
        ref_nda = dr.DataReader.read_landmarks(self.landmarks_3D)
        ref_nda[:, 0:2] *= -1
        self.assertAlmostEqual(np.linalg.norm(ref_nda - res_nda),
                               0,
                               places=self.precision)
Exemplo n.º 18
0
    def test_transform_nreg_to_sitk_regaladin(self):
        cmd_args = ["python simplereg_transform.py"]
        cmd_args.append("-nreg2sitk %s %s" %
                        (self.transform_3D_nreg, self.output_transform))
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_sitk = dr.DataReader.read_transform(self.output_transform)
        ref_sitk = dr.DataReader.read_transform(self.transform_3D_sitk)
        res_nda = np.array(res_sitk.GetParameters())
        ref_nda = np.array(ref_sitk.GetParameters())
        self.assertAlmostEqual(np.linalg.norm(ref_nda - res_nda),
                               0,
                               places=self.precision)
Exemplo n.º 19
0
    def test_transform_nreg_to_sitk_regf3d(self):
        cmd_args = ["python simplereg_transform.py"]
        cmd_args.append(
            "-nreg2sitk %s %s" %
            (self.transform_3D_nreg_disp, self.output_transform_disp))
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_sitk = sitk.ReadImage(self.output_transform_disp)
        ref_sitk = sitk.ReadImage(self.transform_3D_sitk_disp)
        diff_nda = sitk.GetArrayFromImage(res_sitk - ref_sitk)
        self.assertAlmostEqual(np.linalg.norm(diff_nda),
                               0,
                               places=self.precision)
Exemplo n.º 20
0
    def anonymize_files(self, dir_output):
        ph.create_directory(dir_output)

        filenames_in = [os.path.basename(f) for f in self._filenames]

        for i in range(0, len(self._filenames)):
            filename_anonymized = self._identifiers[i]
            filename_original = self._dictionary[self._identifiers[i]]
            try:
                index = filenames_in.index(filename_original)
            except ValueError:
                raise IOError(
                    "Given filenames (--filenames) do not match the ones given in the dictionary"
                )

            path_to_file_anon = os.path.join(dir_output, filename_anonymized)

            cmd = "cp -p "
            cmd += self._filenames[index] + " "
            cmd += path_to_file_anon + " "
            # print(cmd)
            ph.execute_command(cmd)
Exemplo n.º 21
0
    def run(self):
        ph.create_directory(dir_tmp, delete_files=True)

        # Write images
        sitkh.write_nifti_image_sitk(
            self._stack1.sitk,
            self._dir_tmp + self._stack1.get_filename() + ".nii.gz")
        sitkh.write_nifti_image_sitk(
            self._stack2.sitk,
            self._dir_tmp + self._stack2.get_filename() + ".nii.gz")

        cmd = "siena "
        cmd += self._dir_tmp + self._stack1.get_filename() + ".nii.gz "
        cmd += self._dir_tmp + self._stack2.get_filename() + ".nii.gz "
        cmd += "-o " + self._dir_output + " "
        cmd += self._options

        time_start = ph.start_timing()
        ph.execute_command(cmd)
        self._elapsed_time = ph.stop_timing(time_start)

        # Extract measures from report
        self._extract_percentage_brain_volume_change()
def main():
    for patient_i in range(len(patients)):
        for mask_i in mask_indices:
            for srr_i in srr_indices:
                patient = patients[patient_i]
                method_mask = mask_names[mask_i]
                method_srr = srr_names[srr_i]
                dir_input = "{0:}/input_preprocess".format(patient)
                if (not os.path.isdir(dir_input)):
                    dir_input = "{0:}/input".format(patient)
                cmd_args = []
                cmd_args.append(" --dir-input {0:}".format(dir_input))
                cmd_args.append(" --dir-mask {0:}/mask_{1:}/mask".format(
                    patient, method_mask))

                dir_output = "{0:}/mask_{1:}/reconstruct_{2:}".format(
                    patient, method_mask, method_srr)
                cmd_args.append(" --dir-output {0:}".format(dir_output))

                patient_prefix = patient
                if ("_" in patient):
                    patient_prefix = patient.split("_")[0]
                subject_space_arg = 1 if 0 in space_indices else 0
                template_space_arg = 1 if 1 in space_indices else 0
                cmd_args.append(" --gestational-age {0:}".format(
                    ages[patient_i]))
                cmd_args.append(" --suffix-mask _mask")
                cmd_args.append(" --alpha 0.02")
                cmd_args.append(" --bias-field-correction 0")
                cmd_args.append(" --run-data-vs-simulated-data 0")
                cmd_args.append(" --run-recon-subject-space {0:}".format(
                    subject_space_arg))
                cmd_args.append(" --run-recon-template-space {0:}".format(
                    template_space_arg))

                outlier_rejct = 0
                gaussian_smooth = 0
                if (srr_i == 1):
                    outlier_rejct = 1
                elif (srr_i == 2):
                    outlier_rejct = 1
                    gaussian_smooth = 1
                cmd_args.append(
                    " --outlier-rejection {0:}".format(outlier_rejct))
                cmd_args.append(
                    " --use-robust-registration {0:}".format(gaussian_smooth))
                cmd = "python reconstruction.py {0:}".format(
                    ' '.join(cmd_args))
                exit_code = ph.execute_command(cmd)
Exemplo n.º 23
0
    def test_simulate_stacks_from_slices(self):

        cmd_args = []
        cmd_args.append("--dir-input %s" %
                        os.path.join(self.dir_data, "motion_correction"))
        cmd_args.append("--reconstruction %s" % self.path_to_recon)
        cmd_args.append("--reconstruction-mask %s" % self.path_to_recon_mask)
        cmd_args.append("--copy-data 1")
        cmd_args.append("--suffix-mask _brain")
        # cmd_args.append("--verbose 1")
        cmd_args.append("--dir-output %s" % self.dir_output)

        exe = os.path.abspath(simulate_stacks_from_reconstruction.__file__)
        cmd = "python %s %s" % (exe, (" ").join(cmd_args))
        self.assertEqual(ph.execute_command(cmd), 0)
Exemplo n.º 24
0
    def _run_registrations(self, transformations):
        path_to_fixed = os.path.join(DIR_TMP, "fixed.nii.gz")
        path_to_moving = os.path.join(DIR_TMP, "moving.nii.gz")
        path_to_fixed_mask = os.path.join(DIR_TMP, "fixed_mask.nii.gz")
        path_to_moving_mask = os.path.join(DIR_TMP, "moving_mask.nii.gz")
        path_to_tmp_output = os.path.join(DIR_TMP, "foo.nii.gz")
        path_to_transform_regaladin = os.path.join(DIR_TMP,
                                                   "transform_regaladin.txt")
        path_to_transform_sitk = os.path.join(DIR_TMP, "transform_sitk.txt")

        sitkh.write_nifti_image_sitk(self._fixed.sitk, path_to_fixed)
        sitkh.write_nifti_image_sitk(self._moving.sitk, path_to_moving)
        sitkh.write_nifti_image_sitk(self._fixed.sitk_mask, path_to_fixed_mask)
        # sitkh.write_nifti_image_sitk(
        #     self._moving.sitk_mask, path_to_moving_mask)

        for i in range(len(transformations)):
            sitk.WriteTransform(transformations[i], path_to_transform_sitk)

            # Convert SimpleITK to RegAladin transform
            cmd = "simplereg_transform -sitk2nreg %s %s" % (
                path_to_transform_sitk, path_to_transform_regaladin)
            ph.execute_command(cmd, verbose=False)

            # Run NiftyReg
            cmd_args = ["reg_aladin"]
            cmd_args.append("-ref %s" % path_to_fixed)
            cmd_args.append("-flo %s" % path_to_moving)
            cmd_args.append("-res %s" % path_to_tmp_output)
            cmd_args.append("-inaff %s" % path_to_transform_regaladin)
            cmd_args.append("-aff %s" % path_to_transform_regaladin)
            cmd_args.append("-rigOnly")
            cmd_args.append("-ln 2")
            cmd_args.append("-voff")
            cmd_args.append("-rmask %s" % path_to_fixed_mask)
            # To avoid error "0 correspondences between blocks were found" that can
            # occur for some cases. Also, disable moving mask, as this would be ignored
            # anyway
            cmd_args.append("-noSym")
            ph.print_info(
                "Run Registration (RegAladin) based on PCA-init %d ... " %
                (i + 1))
            ph.execute_command(" ".join(cmd_args), verbose=False)

            # Convert RegAladin to SimpleITK transform
            cmd = "simplereg_transform -nreg2sitk %s %s" % (
                path_to_transform_regaladin, path_to_transform_sitk)
            ph.execute_command(cmd, verbose=False)

            transformations[i] = sitkh.read_transform_sitk(
                path_to_transform_sitk)

        return transformations
Exemplo n.º 25
0
    def test_transform_sitk_to_regf3d(self):
        cmd_args = ["python simplereg_transform.py"]
        cmd_args.append(
            "-sitk2nreg %s %s" %
            (self.transform_3D_sitk_disp, self.output_transform_disp))
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_nib = nib.load(self.output_transform_disp)
        ref_nib = nib.load(self.transform_3D_nreg_disp)

        HEADERS = ['intent_p1']
        for h in HEADERS:
            self.assertEqual(res_nib.header[h], res_nib.header[h])

        diff_nda = res_nib.get_data() - ref_nib.get_data()
        self.assertAlmostEqual(np.linalg.norm(diff_nda),
                               0,
                               places=self.precision)
    def test_simulate_stacks_from_slices(self):

        cmd_args = []
        cmd_args.append("--filenames %s" % self.path_to_file)
        cmd_args.append("--dir-input-mc %s" % os.path.join(
            self.dir_data, "recon_projections", "motion_correction"))
        cmd_args.append("--reconstruction %s" % self.path_to_recon)
        cmd_args.append("--reconstruction-mask %s" % self.path_to_recon_mask)
        cmd_args.append("--copy-data 1")
        cmd_args.append("--suffix-mask %s" % self.suffix_mask)
        cmd_args.append("--dir-output %s" % self.dir_output)

        exe = os.path.abspath(simulate_stacks_from_reconstruction.__file__)
        cmd = "python %s %s" % (exe, (" ").join(cmd_args))
        self.assertEqual(ph.execute_command(cmd), 0)

        path_orig = os.path.join(self.dir_output, "%s.nii.gz" % self.filename)
        path_sim = os.path.join(self.dir_output,
                                "Simulated_%s.nii.gz" % self.filename)
        path_sim_mask = os.path.join(
            self.dir_output,
            "Simulated_%s%s.nii.gz" % (self.filename, self.suffix_mask))

        path_orig_ref = os.path.join(self.dir_data, "recon_projections",
                                     "slices", "%s.nii.gz" % self.filename)
        path_sim_ref = os.path.join(self.dir_data, "recon_projections",
                                    "slices",
                                    "Simulated_%s.nii.gz" % self.filename)
        path_sim_mask_ref = os.path.join(
            self.dir_data, "recon_projections", "slices",
            "Simulated_%s%s.nii.gz" % (self.filename, self.suffix_mask))

        for res, ref in zip([path_orig, path_sim, path_sim_mask],
                            [path_orig_ref, path_sim_ref, path_sim_mask_ref]):
            res_sitk = sitk.ReadImage(res)
            ref_sitk = sitk.ReadImage(ref)

            nda_diff = np.nan_to_num(
                sitk.GetArrayFromImage(res_sitk - ref_sitk))
            self.assertAlmostEqual(np.linalg.norm(nda_diff),
                                   0,
                                   places=self.precision)
Exemplo n.º 27
0
    def test_resample_bspline_spacing_atg(self):
        image = os.path.join(DIR_DATA, "3D_SheppLoganPhantom_64.nii.gz")
        reference = os.path.join(
            DIR_TEST, "3D_SheppLoganPhantom_64_BSpline_s113_atg-4.nii.gz")

        cmd_args = ["python simplereg_resample.py"]
        cmd_args.append("-m %s" % image)
        cmd_args.append("-f same")
        cmd_args.append("-i BSpline")
        cmd_args.append("-t %s" % self.transform_3D_sitk)
        cmd_args.append("-s 1 1 3")
        cmd_args.append("-atg -4")
        cmd_args.append("-o %s" % self.output_image)
        self.assertEqual(ph.execute_command(" ".join(cmd_args)), 0)

        res_sitk = sitk.ReadImage(self.output_image)
        ref_sitk = sitk.ReadImage(reference)
        diff_nda = sitk.GetArrayFromImage(res_sitk - ref_sitk)
        self.assertAlmostEqual(np.linalg.norm(diff_nda),
                               0,
                               places=self.precision)
Exemplo n.º 28
0
def main():

    input_parser = InputArgparser(description="Convert NIfTI to DICOM image", )
    input_parser.add_filename(required=True)
    input_parser.add_option(
        option_string="--template",
        type=str,
        required=True,
        help="Template DICOM to extract relevant DICOM tags.",
    )
    input_parser.add_dir_output(required=True)
    input_parser.add_label(
        help="Label used for series description of DICOM output.",
        default="SRR_NiftyMIC")
    input_parser.add_argument(
        "--volume",
        "-volume",
        action='store_true',
        help="If given, the output DICOM file is combined as 3D volume")
    args = input_parser.parse_args()
    input_parser.print_arguments(args)

    # Prepare for final DICOM output
    ph.create_directory(args.dir_output)

    if args.volume:
        dir_output_2d_slices = os.path.join(DIR_TMP, "dicom_slices")
    else:
        dir_output_2d_slices = os.path.join(args.dir_output, args.label)
    ph.create_directory(dir_output_2d_slices, delete_files=True)

    # read NiftyMIC version (if available)
    data_reader = dr.ImageHeaderReader(args.filename)
    data_reader.read_data()
    niftymic_version = data_reader.get_niftymic_version()
    if niftymic_version is None:
        niftymic_version = "NiftyMIC"
    else:
        niftymic_version = "NiftyMIC-v%s" % niftymic_version

    # Create set of 2D DICOM slices from 3D NIfTI image
    # (correct image orientation!)
    ph.print_title("Create set of 2D DICOM slices from 3D NIfTI image")
    cmd_args = ["nifti2dicom"]
    cmd_args.append("-i '%s'" % args.filename)
    cmd_args.append("-o '%s'" % dir_output_2d_slices)
    cmd_args.append("-d '%s'" % args.template)
    cmd_args.append("--prefix ''")
    cmd_args.append("--seriesdescription '%s'" % args.label)
    cmd_args.append("--accessionnumber '%s'" % ACCESSION_NUMBER)
    cmd_args.append("--seriesnumber '%s'" % SERIES_NUMBER)
    cmd_args.append("--institutionname '%s'" % IMAGE_COMMENTS)

    # Overwrite default "nifti2dicom" tags which would be added otherwise
    # (no deletion/update with empty '' sufficient to overwrite them)
    cmd_args.append("--manufacturersmodelname '%s'" % "NiftyMIC")
    cmd_args.append("--protocolname '%s'" % niftymic_version)

    cmd_args.append("-y")
    ph.execute_command(" ".join(cmd_args))

    if args.volume:
        path_to_output = os.path.join(args.dir_output, "%s.dcm" % args.label)
        # Combine set of 2D DICOM slices to form 3D DICOM image
        # (image orientation stays correct)
        ph.print_title("Combine set of 2D DICOM slices to form 3D DICOM image")
        cmd_args = ["medcon"]
        cmd_args.append("-f '%s'/*.dcm" % dir_output_2d_slices)
        cmd_args.append("-o '%s'" % path_to_output)
        cmd_args.append("-c dicom")
        cmd_args.append("-stack3d")
        cmd_args.append("-n")
        cmd_args.append("-qc")
        cmd_args.append("-w")
        ph.execute_command(" ".join(cmd_args))

        # Update all relevant DICOM tags accordingly
        ph.print_title("Update all relevant DICOM tags accordingly")
        print("")
        dataset_template = pydicom.dcmread(args.template)
        dataset = pydicom.dcmread(path_to_output)

        # Copy tags from template (to guarantee grouping with original data)
        update_dicom_tags = {}
        for tag in COPY_DICOM_TAGS:
            try:
                update_dicom_tags[tag] = getattr(dataset_template, tag)
            except:
                update_dicom_tags[tag] = ""

        # Additional tags
        update_dicom_tags["SeriesDescription"] = args.label
        update_dicom_tags["InstitutionName"] = institution_name
        update_dicom_tags["ImageComments"] = IMAGE_COMMENTS
        update_dicom_tags["AccessionNumber"] = ACCESSION_NUMBER
        update_dicom_tags["SeriesNumber"] = SERIES_NUMBER

        for tag in sorted(update_dicom_tags.keys()):
            value = update_dicom_tags[tag]
            setattr(dataset, tag, value)
            ph.print_info("%s: '%s'" % (tag, value))

        dataset.save_as(path_to_output)
        print("")
        ph.print_info("3D DICOM image written to '%s'" % path_to_output)

    else:
        ph.print_info("DICOM images written to '%s'" % dir_output_2d_slices)

    return 0
def main():

    time_start = ph.start_timing()

    np.set_printoptions(precision=3)

    input_parser = InputArgparser(
        description="Run reconstruction pipeline including "
        "(i) bias field correction, "
        "(ii) volumetric reconstruction in subject space, "
        "(iii) volumetric reconstruction in template space, "
        "and (iv) some diagnostics to assess the obtained reconstruction.", )
    input_parser.add_filenames(required=True)
    input_parser.add_filenames_masks(required=True)
    input_parser.add_target_stack(required=False)
    input_parser.add_suffix_mask(default="")
    input_parser.add_dir_output(required=True)
    input_parser.add_alpha(default=0.01)
    input_parser.add_verbose(default=0)
    input_parser.add_gestational_age(required=False)
    input_parser.add_prefix_output(default="")
    input_parser.add_search_angle(default=180)
    input_parser.add_multiresolution(default=0)
    input_parser.add_log_config(default=1)
    input_parser.add_isotropic_resolution()
    input_parser.add_reference()
    input_parser.add_reference_mask()
    input_parser.add_bias_field_correction(default=1)
    input_parser.add_intensity_correction(default=1)
    input_parser.add_iter_max(default=10)
    input_parser.add_two_step_cycles(default=3)
    input_parser.add_slice_thicknesses(default=None)
    input_parser.add_option(
        option_string="--run-bias-field-correction",
        type=int,
        help="Turn on/off bias field correction. "
        "If off, it is assumed that this step was already performed "
        "if --bias-field-correction is active.",
        default=1)
    input_parser.add_option(
        option_string="--run-recon-subject-space",
        type=int,
        help="Turn on/off reconstruction in subject space. "
        "If off, it is assumed that this step was already performed.",
        default=1)
    input_parser.add_option(
        option_string="--run-recon-template-space",
        type=int,
        help="Turn on/off reconstruction in template space. "
        "If off, it is assumed that this step was already performed.",
        default=1)
    input_parser.add_option(
        option_string="--run-diagnostics",
        type=int,
        help="Turn on/off diagnostics of the obtained volumetric "
        "reconstruction. ",
        default=0)
    input_parser.add_option(
        option_string="--initial-transform",
        type=str,
        help="Set initial transform to be used for register_image.",
        default=None)
    input_parser.add_outlier_rejection(default=1)
    input_parser.add_threshold_first(default=0.5)
    input_parser.add_threshold(default=0.8)
    input_parser.add_argument(
        "--sda",
        "-sda",
        action='store_true',
        help="If given, the volume is reconstructed using "
        "Scattered Data Approximation (Vercauteren et al., 2006). "
        "--alpha is considered the value for the standard deviation then. "
        "Recommended value is, e.g., --alpha 0.8")
    input_parser.add_argument(
        "--v2v-robust",
        "-v2v-robust",
        action='store_true',
        help="If given, a more robust volume-to-volume registration step is "
        "performed, i.e. four rigid registrations are performed using four "
        "rigid transform initializations based on "
        "principal component alignment of associated masks.")
    input_parser.add_interleave(default=3)
    input_parser.add_argument(
        "--s2v-hierarchical",
        "-s2v-hierarchical",
        action='store_true',
        help="If given, a hierarchical approach for the first slice-to-volume "
        "registration cycle is used, i.e. sub-packages defined by the "
        "specified interleave (--interleave) are registered until each "
        "slice is registered independently.")

    args = input_parser.parse_args()
    input_parser.print_arguments(args)

    if args.log_config:
        input_parser.log_config(os.path.abspath(__file__))

    filename_srr = "srr"
    dir_output_preprocessing = os.path.join(args.dir_output,
                                            "preprocessing_n4itk")
    dir_output_recon_subject_space = os.path.join(args.dir_output,
                                                  "recon_subject_space")
    dir_output_recon_template_space = os.path.join(args.dir_output,
                                                   "recon_template_space")
    dir_output_diagnostics = os.path.join(args.dir_output, "diagnostics")

    srr_subject = os.path.join(dir_output_recon_subject_space,
                               "%s_subject.nii.gz" % filename_srr)
    srr_subject_mask = ph.append_to_filename(srr_subject, "_mask")
    srr_template = os.path.join(dir_output_recon_template_space,
                                "%s_template.nii.gz" % filename_srr)
    srr_template_mask = ph.append_to_filename(srr_template, "_mask")
    trafo_template = os.path.join(dir_output_recon_template_space,
                                  "registration_transform_sitk.txt")
    srr_slice_coverage = os.path.join(
        dir_output_diagnostics,
        "%s_template_slicecoverage.nii.gz" % filename_srr)

    if args.bias_field_correction and args.run_bias_field_correction:
        for i, f in enumerate(args.filenames):
            output = os.path.join(dir_output_preprocessing,
                                  os.path.basename(f))
            cmd_args = []
            cmd_args.append("--filename '%s'" % f)
            cmd_args.append("--filename-mask '%s'" % args.filenames_masks[i])
            cmd_args.append("--output '%s'" % output)
            # cmd_args.append("--verbose %d" % args.verbose)
            cmd_args.append("--log-config %d" % args.log_config)
            cmd = "niftymic_correct_bias_field %s" % (" ").join(cmd_args)
            time_start_bias = ph.start_timing()
            exit_code = ph.execute_command(cmd)
            if exit_code != 0:
                raise RuntimeError("Bias field correction failed")
        elapsed_time_bias = ph.stop_timing(time_start_bias)
        filenames = [
            os.path.join(dir_output_preprocessing, os.path.basename(f))
            for f in args.filenames
        ]
    elif args.bias_field_correction and not args.run_bias_field_correction:
        elapsed_time_bias = ph.get_zero_time()
        filenames = [
            os.path.join(dir_output_preprocessing, os.path.basename(f))
            for f in args.filenames
        ]
    else:
        elapsed_time_bias = ph.get_zero_time()
        filenames = args.filenames

    # Specify target stack for intensity correction and reconstruction space
    if args.target_stack is None:
        target_stack = filenames[0]
    else:
        try:
            target_stack_index = args.filenames.index(args.target_stack)
        except ValueError as e:
            raise ValueError(
                "--target-stack must correspond to an image as provided by "
                "--filenames")
        target_stack = filenames[target_stack_index]

    # Add single quotes around individual filenames to account for whitespaces
    filenames = ["'" + f + "'" for f in filenames]
    filenames_masks = ["'" + f + "'" for f in args.filenames_masks]

    if args.run_recon_subject_space:

        cmd_args = ["niftymic_reconstruct_volume"]
        cmd_args.append("--filenames %s" % (" ").join(filenames))
        cmd_args.append("--filenames-masks %s" % (" ").join(filenames_masks))
        cmd_args.append("--multiresolution %d" % args.multiresolution)
        cmd_args.append("--target-stack '%s'" % target_stack)
        cmd_args.append("--output '%s'" % srr_subject)
        cmd_args.append("--suffix-mask '%s'" % args.suffix_mask)
        cmd_args.append("--intensity-correction %d" %
                        args.intensity_correction)
        cmd_args.append("--alpha %s" % args.alpha)
        cmd_args.append("--iter-max %d" % args.iter_max)
        cmd_args.append("--two-step-cycles %d" % args.two_step_cycles)
        cmd_args.append("--outlier-rejection %d" % args.outlier_rejection)
        cmd_args.append("--threshold-first %f" % args.threshold_first)
        cmd_args.append("--threshold %f" % args.threshold)
        if args.slice_thicknesses is not None:
            cmd_args.append("--slice-thicknesses %s" %
                            " ".join(map(str, args.slice_thicknesses)))
        cmd_args.append("--verbose %d" % args.verbose)
        cmd_args.append("--log-config %d" % args.log_config)
        if args.isotropic_resolution is not None:
            cmd_args.append("--isotropic-resolution %f" %
                            args.isotropic_resolution)
        if args.reference is not None:
            cmd_args.append("--reference %s" % args.reference)
        if args.reference_mask is not None:
            cmd_args.append("--reference-mask %s" % args.reference_mask)
        if args.sda:
            cmd_args.append("--sda")
        if args.v2v_robust:
            cmd_args.append("--v2v-robust")
        if args.s2v_hierarchical:
            cmd_args.append("--s2v-hierarchical")

        cmd = (" ").join(cmd_args)
        time_start_volrec = ph.start_timing()
        exit_code = ph.execute_command(cmd)
        if exit_code != 0:
            raise RuntimeError("Reconstruction in subject space failed")

        # Compute SRR mask in subject space
        # (Approximated using SDA within reconstruct_volume)
        if 0:
            dir_motion_correction = os.path.join(
                dir_output_recon_subject_space, "motion_correction")
            cmd_args = ["niftymic_reconstruct_volume_from_slices"]
            cmd_args.append("--filenames %s" % " ".join(filenames_masks))
            cmd_args.append("--dir-input-mc '%s'" % dir_motion_correction)
            cmd_args.append("--output '%s'" % srr_subject_mask)
            cmd_args.append("--reconstruction-space '%s'" % srr_subject)
            cmd_args.append("--suffix-mask '%s'" % args.suffix_mask)
            cmd_args.append("--mask")
            cmd_args.append("--log-config %d" % args.log_config)
            if args.slice_thicknesses is not None:
                cmd_args.append("--slice-thicknesses %s" %
                                " ".join(map(str, args.slice_thicknesses)))
            if args.sda:
                cmd_args.append("--sda")
                cmd_args.append("--alpha 1")
            else:
                cmd_args.append("--alpha 0.1")
                cmd_args.append("--iter-max 5")
            cmd = (" ").join(cmd_args)
            ph.execute_command(cmd)

        elapsed_time_volrec = ph.stop_timing(time_start_volrec)
    else:
        elapsed_time_volrec = ph.get_zero_time()

    if args.run_recon_template_space:

        if args.gestational_age is None:
            template_stack_estimator = \
                tse.TemplateStackEstimator.from_mask(srr_subject_mask)
            gestational_age = template_stack_estimator.get_estimated_gw()
            ph.print_info("Estimated gestational age: %d" % gestational_age)
        else:
            gestational_age = args.gestational_age

        template = os.path.join(DIR_TEMPLATES,
                                "STA%d.nii.gz" % gestational_age)
        template_mask = os.path.join(DIR_TEMPLATES,
                                     "STA%d_mask.nii.gz" % gestational_age)

        # Register SRR to template space
        cmd_args = ["niftymic_register_image"]
        cmd_args.append("--fixed '%s'" % template)
        cmd_args.append("--moving '%s'" % srr_subject)
        cmd_args.append("--fixed-mask '%s'" % template_mask)
        cmd_args.append("--moving-mask '%s'" % srr_subject_mask)
        cmd_args.append(
            "--dir-input-mc '%s'" %
            os.path.join(dir_output_recon_subject_space, "motion_correction"))
        cmd_args.append("--output '%s'" % trafo_template)
        cmd_args.append("--verbose %s" % args.verbose)
        cmd_args.append("--log-config %d" % args.log_config)
        cmd_args.append("--refine-pca")
        if args.initial_transform is not None:
            cmd_args.append("--initial-transform '%s'" %
                            args.initial_transform)
        cmd = (" ").join(cmd_args)
        exit_code = ph.execute_command(cmd)
        if exit_code != 0:
            raise RuntimeError("Registration to template space failed")

        # Compute SRR in template space
        dir_input_mc = os.path.join(dir_output_recon_template_space,
                                    "motion_correction")
        cmd_args = ["niftymic_reconstruct_volume_from_slices"]
        cmd_args.append("--filenames %s" % (" ").join(filenames))
        cmd_args.append("--filenames-masks %s" % (" ").join(filenames_masks))
        cmd_args.append("--dir-input-mc '%s'" % dir_input_mc)
        cmd_args.append("--output '%s'" % srr_template)
        cmd_args.append("--reconstruction-space '%s'" % template)
        cmd_args.append("--target-stack '%s'" % target_stack)
        cmd_args.append("--iter-max %d" % args.iter_max)
        cmd_args.append("--alpha %s" % args.alpha)
        cmd_args.append("--suffix-mask '%s'" % args.suffix_mask)
        cmd_args.append("--verbose %s" % args.verbose)
        cmd_args.append("--log-config %d" % args.log_config)
        if args.slice_thicknesses is not None:
            cmd_args.append("--slice-thicknesses %s" %
                            " ".join(map(str, args.slice_thicknesses)))
        if args.sda:
            cmd_args.append("--sda")

        cmd = (" ").join(cmd_args)
        exit_code = ph.execute_command(cmd)
        if exit_code != 0:
            raise RuntimeError("Reconstruction in template space failed")

        # Compute SRR mask in template space
        if 1:
            dir_motion_correction = os.path.join(
                dir_output_recon_template_space, "motion_correction")
            cmd_args = ["niftymic_reconstruct_volume_from_slices"]
            cmd_args.append("--filenames %s" % " ".join(filenames_masks))
            cmd_args.append("--dir-input-mc '%s'" % dir_motion_correction)
            cmd_args.append("--output '%s'" % srr_template_mask)
            cmd_args.append("--reconstruction-space '%s'" % srr_template)
            cmd_args.append("--suffix-mask '%s'" % args.suffix_mask)
            cmd_args.append("--log-config %d" % args.log_config)
            cmd_args.append("--mask")
            if args.slice_thicknesses is not None:
                cmd_args.append("--slice-thicknesses %s" %
                                " ".join(map(str, args.slice_thicknesses)))
            if args.sda:
                cmd_args.append("--sda")
                cmd_args.append("--alpha 1")
            else:
                cmd_args.append("--alpha 0.1")
                cmd_args.append("--iter-max 5")
            cmd = (" ").join(cmd_args)
            ph.execute_command(cmd)

        # Copy SRR to output directory
        if 0:
            output = "%sSRR_Stacks%d.nii.gz" % (args.prefix_output,
                                                len(args.filenames))
            path_to_output = os.path.join(args.dir_output, output)
            cmd = "cp -p '%s' '%s'" % (srr_template, path_to_output)
            exit_code = ph.execute_command(cmd)
            if exit_code != 0:
                raise RuntimeError("Copy of SRR to output directory failed")

        # Multiply template mask with reconstruction
        if 0:
            cmd_args = ["niftymic_multiply"]
            fnames = [
                srr_template,
                srr_template_mask,
            ]
            output_masked = "Masked_%s" % output
            path_to_output_masked = os.path.join(args.dir_output,
                                                 output_masked)
            cmd_args.append("--filenames %s" % " ".join(fnames))
            cmd_args.append("--output '%s'" % path_to_output_masked)
            cmd = (" ").join(cmd_args)
            exit_code = ph.execute_command(cmd)
            if exit_code != 0:
                raise RuntimeError("SRR brain masking failed")

    else:
        elapsed_time_template = ph.get_zero_time()

    if args.run_diagnostics:

        dir_input_mc = os.path.join(dir_output_recon_template_space,
                                    "motion_correction")
        dir_output_orig_vs_proj = os.path.join(dir_output_diagnostics,
                                               "original_vs_projected")
        dir_output_selfsimilarity = os.path.join(dir_output_diagnostics,
                                                 "selfsimilarity")
        dir_output_orig_vs_proj_pdf = os.path.join(dir_output_orig_vs_proj,
                                                   "pdf")

        # Show slice coverage over reconstruction space
        exe = os.path.abspath(show_slice_coverage.__file__)
        cmd_args = ["python %s" % exe]
        cmd_args.append("--filenames %s" % (" ").join(filenames))
        cmd_args.append("--dir-input-mc '%s'" % dir_input_mc)
        cmd_args.append("--reconstruction-space '%s'" % srr_template)
        cmd_args.append("--output '%s'" % srr_slice_coverage)
        cmd = (" ").join(cmd_args)
        exit_code = ph.execute_command(cmd)
        if exit_code != 0:
            raise RuntimeError("Slice coverage visualization failed")

        # Get simulated/projected slices
        exe = os.path.abspath(simulate_stacks_from_reconstruction.__file__)
        cmd_args = ["python %s" % exe]
        cmd_args.append("--filenames %s" % (" ").join(filenames))
        if args.filenames_masks is not None:
            cmd_args.append("--filenames-masks %s" %
                            (" ").join(filenames_masks))
        cmd_args.append("--dir-input-mc '%s'" % dir_input_mc)
        cmd_args.append("--dir-output '%s'" % dir_output_orig_vs_proj)
        cmd_args.append("--reconstruction '%s'" % srr_template)
        cmd_args.append("--copy-data 1")
        if args.slice_thicknesses is not None:
            cmd_args.append("--slice-thicknesses %s" %
                            " ".join(map(str, args.slice_thicknesses)))
        # cmd_args.append("--verbose %s" % args.verbose)
        cmd = (" ").join(cmd_args)
        exit_code = ph.execute_command(cmd)
        if exit_code != 0:
            raise RuntimeError("SRR slice projections failed")

        filenames_simulated = [
            "'%s" % os.path.join(dir_output_orig_vs_proj, os.path.basename(f))
            for f in filenames
        ]

        # Evaluate slice similarities to ground truth
        exe = os.path.abspath(evaluate_simulated_stack_similarity.__file__)
        cmd_args = ["python %s" % exe]
        cmd_args.append("--filenames %s" % (" ").join(filenames_simulated))
        if args.filenames_masks is not None:
            cmd_args.append("--filenames-masks %s" %
                            (" ").join(filenames_masks))
        cmd_args.append("--measures NCC SSIM")
        cmd_args.append("--dir-output '%s'" % dir_output_selfsimilarity)
        cmd = (" ").join(cmd_args)
        exit_code = ph.execute_command(cmd)
        if exit_code != 0:
            raise RuntimeError("Evaluation of stack similarities failed")

        # Generate figures showing the quantitative comparison
        exe = os.path.abspath(
            show_evaluated_simulated_stack_similarity.__file__)
        cmd_args = ["python %s" % exe]
        cmd_args.append("--dir-input '%s'" % dir_output_selfsimilarity)
        cmd_args.append("--dir-output '%s'" % dir_output_selfsimilarity)
        cmd = (" ").join(cmd_args)
        exit_code = ph.execute_command(cmd)
        if exit_code != 0:
            ph.print_warning("Visualization of stack similarities failed")

        # Generate pdfs showing all the side-by-side comparisons
        if 0:
            exe = os.path.abspath(
                export_side_by_side_simulated_vs_original_slice_comparison.
                __file__)
            cmd_args = ["python %s" % exe]
            cmd_args.append("--filenames %s" % (" ").join(filenames_simulated))
            cmd_args.append("--dir-output '%s'" % dir_output_orig_vs_proj_pdf)
            cmd = "python %s %s" % (exe, (" ").join(cmd_args))
            cmd = (" ").join(cmd_args)
            exit_code = ph.execute_command(cmd)
            if exit_code != 0:
                raise RuntimeError("Generation of PDF overview failed")

    ph.print_title("Summary")
    print("Computational Time for Bias Field Correction: %s" %
          elapsed_time_bias)
    print("Computational Time for Volumetric Reconstruction: %s" %
          elapsed_time_volrec)
    print("Computational Time for Pipeline: %s" % ph.stop_timing(time_start))

    return 0
Exemplo n.º 30
0
 def write_function_call_to_file(function_call, path_to_file):
     text = "#!/bin/zsh\n\n%s" % function_call
     ph.write_to_file(path_to_file, text, verbose=False)
     ph.execute_command("chmod +x %s" % path_to_file, verbose=False)