示例#1
0
    def implement(self):

        dwi = self.getBackupImage('dwi')
        bEncs = self.getBackupImage('grad', None, 'b')
        bVals = self.getBackupImage('grad', None, 'bvals')
        bVecs = self.getBackupImage('grad', None, 'bvecs')

        (bEncs, bVecs,
         bVals) = self.__produceEncodingFiles(bEncs, bVecs, bVals,
                                              dwi)  # Convert bvecs bval

        expectedLayout = self.get('stride_orientation')
        if not mriutil.isDataStridesOrientationExpected(dwi, expectedLayout) \
                and self.get("force_realign_strides"):

            self.warning("Reorienting strides for image {}".format(dwi))
            self.__stride4DImage(dwi, bEncs, bVecs, bVals, expectedLayout)

        else:
            self.info("Linking {} to {}".format(
                dwi, util.symlink(dwi, self.workingDir)))

        images = Images(
            (self.getBackupImage('anat'), 'high resolution'),
            (self.getBackupImage('b0_pa'), 'B0 posterior to anterior'),
            (self.getBackupImage('b0_ap'), 'B0 anterior to posterior'),
            (self.getBackupImage('mag'), 'MR magnitude'),
            (self.getBackupImage('phase'), 'MR phase '),
            (self.getBackupImage('aparc_aseg'), 'parcellation'),
            (self.getBackupImage('anat',
                                 'freesurfer'), 'freesurfer anatomical'),
            (self.getBackupImage('lh_ribbon'), 'left hemisphere ribbon'),
            (self.getBackupImage('rh_ribbon'), 'right hemisphere ribbon'),
            (self.getBackupImage('brodmann'), 'brodmann'),
        )

        for image, description in images.getData():
            if image:
                if not mriutil.isDataStridesOrientationExpected(image, expectedLayout) \
                        and self.get("force_realign_strides"):
                    self.info(
                        mriutil.stride3DImage(image,
                                              self.buildName(image, "stride"),
                                              expectedLayout))
                else:
                    self.info("Found {} image, linking {} to {}".format(
                        description, image,
                        util.symlink(image, self.workingDir)))

        for directory in [
                os.path.join(self.backupDir, directory)
                for directory in os.listdir(self.backupDir)
                if os.path.isdir(os.path.join(self.backupDir, directory))
        ]:
            if mriutil.isAfreesurferStructure(directory):
                self.info(
                    "{} seem\'s a valid freesurfer structure: linking to {} directory"
                    .format(directory, self.workingDir))
                util.symlink(directory, self.workingDir,
                             self.get("parcellation", "id"))
示例#2
0
    def implement(self):

        self.info("Build directories structure for subject: {}".format(os.path.basename(self.workingDir)))
        #@TODO add description to that struct
        images = Images((self.getSubjectImage('anat'), ""),
                       (self.getSubjectImage('dwi'), ""),
                       (self.getSubjectImage('mag',), ""),
                       (self.getSubjectImage('phase'), ""),
                       (self.getSubjectImage('aparc_aseg'), ""),
                       (self.getSubjectImage('anat', 'freesurfer'), ""),
                       (self.getSubjectImage('lh_ribbon'), ""),
                       (self.getSubjectImage('rh_ribbon'), ""),
                       (self.getSubjectImage('brodmann'), ""),
                       (self.getSubjectImage('b0_ap'), ""),
                       (self.getSubjectImage('b0_pa'), ""),
                       (self.getSubjectImage('grad', None, 'b'), ""),
                       (self.getSubjectImage('grad', None, 'bvals'), ""),
                       (self.getSubjectImage('grad', None, 'bvecs'), ""),
                       (self.getSubjectImage('tq_dict', None, 'qry'), ""),
                       (self.getSubjectImage('queries', None, 'qry'), ""),
                       (self.getSubjectImage('config', None, 'cfg'), ""),)

        for image, description in images.getData():
            if image:
                self.info("Found {} image: moving it to {} directory".format(description, image, self.workingDir))
                shutil.move(image, self.workingDir)

        directories = [os.path.join(self.subjectDir, directory) for directory in os.listdir(self.subjectDir) if os.path.isdir(os.path.join(self.subjectDir, directory))]
        for directory in directories:
            if mriutil.isAfreesurferStructure(directory):
                self.info("{} seem\'s a valid freesurfer structure: moving it to {} directory".format(directory, self.workingDir))
                shutil.move(directory, self.workingDir)
示例#3
0
    def implement(self):

        self.info("Build directories structure for subject: {}".format(
            os.path.basename(self.workingDir)))
        #@TODO add description to that struct
        images = Images((self.getSubjectImage('anat'), ""),
                       (self.getSubjectImage('dwi'), ""),
                       (self.getSubjectImage('mag',), ""),
                       (self.getSubjectImage('phase'), ""),
                       (self.getSubjectImage('aparc_aseg'), ""),
                       (self.getSubjectImage('anat', 'freesurfer'), ""),
                       (self.getSubjectImage('lh_ribbon'), ""),
                       (self.getSubjectImage('rh_ribbon'), ""),
                       (self.getSubjectImage('brodmann'), ""),
                       (self.getSubjectImage('b0_ap'), ""),
                       (self.getSubjectImage('b0_pa'), ""),
                       (self.getSubjectImage('grad', None, 'b'), ""),
                       (self.getSubjectImage('grad', None, 'bvals'), ""),
                       (self.getSubjectImage('grad', None, 'bvecs'), ""),
                       (self.getSubjectImage('tq_dict', None, 'qry'), ""),
                       (self.getSubjectImage('queries', None, 'qry'), ""),
                       (self.getSubjectImage('config', None, 'cfg'), ""),)

        for image, description in images.getData():
            if image:
                self.info("Found {} image: moving it to {} directory".format(
                    description, image, self.workingDir))
                shutil.move(image, self.workingDir)

        directories = []
        for directory in os.listdir(self.subjectDir):
            target = os.path.join(self.subjectDir, directory)
            if os.path.isdir(target):
                directories.append(target)

        for directory in directories:
            if mriutil.isAfreesurferStructure(directory):
                self.info("{} seem\'s a valid freesurfer structure: moving it to {} directory".format(directory, self.workingDir))

                if os.path.islink(directory):
                    os.chdir(self.subjectDir)
                    # We need to chdir because `directory` is in
                    # `self.subjectDir` and we need `os.path.abspath` to
                    # work correctly
                    fsDirName = os.path.basename(directory)
                    linkto = os.path.abspath(os.readlink(directory))
                    newLinkto = os.path.relpath(linkto, self.workingDir)
                    newTarget = os.path.join(self.workingDir, fsDirName)
                    os.symlink(newLinkto, newTarget)
                    os.unlink(directory)
                    os.chdir(self.workingDir)
                else:
                    shutil.move(directory, self.workingDir)
示例#4
0
    def __findAndLinkFreesurferStructure(self):
        """Look if a freesurfer structure already exists in the backup.

        freesurfer structure will be link and id will be update

        Returns:
            Return the linked directory name if a freesurfer structure is found, False otherwise
        """
        freesurferStructure = os.path.join(self.preparationDir, self.id)
        if mriutil.isAfreesurferStructure(freesurferStructure):
           self.info("{} seem\'s a valid freesurfer structure: moving it to {} directory".format(freesurferStructure, self.workingDir))
           util.symlink(freesurferStructure, self.id)
           return True
        return False
示例#5
0
    def __findAndLinkFreesurferStructure(self):
        """Look if a freesurfer structure already exists in the backup.

        freesurfer structure will be link and id will be update

        Returns:
            Return the linked directory name if a freesurfer structure is found, False otherwise
        """
        freesurferStructure = os.path.join(self.preparationDir, self.id)
        if mriutil.isAfreesurferStructure(freesurferStructure):
            self.info(
                "{} seem\'s a valid freesurfer structure: moving it to {} directory"
                .format(freesurferStructure, self.workingDir))
            util.symlink(freesurferStructure, self.workingDir, self.id)
            return True

        return False
示例#6
0
    def implement(self):

        dwi = self.getBackupImage('dwi')
        bEncs = self.getBackupImage('grad', None, 'b')
        bVals = self.getBackupImage('grad', None, 'bvals')
        bVecs = self.getBackupImage('grad', None, 'bvecs')


        (bEncs, bVecs, bVals) = self.__produceEncodingFiles(bEncs, bVecs, bVals, dwi)  # Convert bvecs bval

        expectedLayout = self.get('stride_orientation')
        if not mriutil.isDataStridesOrientationExpected(dwi, expectedLayout) \
                and self.get("force_realign_strides"):

            self.warning("Reorienting strides for image {}".format(dwi))
            self.__stride4DImage(dwi, bEncs, bVecs, bVals, expectedLayout)

        else:
            self.info("Linking {} to {}".format(dwi, util.symlink(dwi, self.workingDir)))

        images = Images(
                    (self.getBackupImage('anat'),'high resolution'),
                    (self.getBackupImage('b0_pa'),'B0 posterior to anterior'),
                    (self.getBackupImage('b0_ap'),'B0 anterior to posterior'),
                    (self.getBackupImage('mag'),'MR magnitude'),
                    (self.getBackupImage('phase'),'MR phase '),
                    (self.getBackupImage('aparc_aseg'),'parcellation'),
                    (self.getBackupImage('anat', 'freesurfer'),'freesurfer anatomical'),
                    (self.getBackupImage('lh_ribbon'),'left hemisphere ribbon'),
                    (self.getBackupImage('rh_ribbon'),'right hemisphere ribbon'),
                    (self.getBackupImage('brodmann'),'brodmann'),
                    )

        for image, description in images.getData():
            if image:
                if not mriutil.isDataStridesOrientationExpected(image, expectedLayout) \
                        and self.get("force_realign_strides"):
                    self.info(mriutil.stride3DImage(image, self.buildName(image, "stride"), expectedLayout))
                else:
                    self.info("Found {} image, linking {} to {}".format(description, image, util.symlink(image, self.workingDir)))

        for directory in [os.path.join(self.backupDir, directory) for directory in os.listdir(self.backupDir) if os.path.isdir(os.path.join(self.backupDir, directory))]:
            if mriutil.isAfreesurferStructure(directory):
                self.info("{} seem\'s a valid freesurfer structure: linking to {} directory".format(directory, self.workingDir))
                util.symlink(directory, self.workingDir, self.get("parcellation", "id"))
示例#7
0
    def implement(self):

        self.info("Build directories structure for subject: {}".format(os.path.basename(self.workingDir)))
        # @TODO add description to that struct
        images = Images(
            (self.getSubjectImage("anat"), ""),
            (self.getSubjectImage("dwi"), ""),
            (self.getSubjectImage("mag"), ""),
            (self.getSubjectImage("phase"), ""),
            (self.getSubjectImage("aparc_aseg"), ""),
            (self.getSubjectImage("anat", "freesurfer"), ""),
            (self.getSubjectImage("lh_ribbon"), ""),
            (self.getSubjectImage("rh_ribbon"), ""),
            (self.getSubjectImage("brodmann"), ""),
            (self.getSubjectImage("b0_ap"), ""),
            (self.getSubjectImage("b0_pa"), ""),
            (self.getSubjectImage("grad", None, "b"), ""),
            (self.getSubjectImage("grad", None, "bvals"), ""),
            (self.getSubjectImage("grad", None, "bvecs"), ""),
            (self.getSubjectImage("config", None, "cfg"), ""),
        )

        for image, description in images.getData():
            if image:
                self.info("Found {} image: moving it to {} directory".format(description, image, self.workingDir))
                shutil.move(image, self.workingDir)

        directories = [
            os.path.join(self.subjectDir, directory)
            for directory in os.listdir(self.subjectDir)
            if os.path.isdir(os.path.join(self.subjectDir, directory))
        ]
        for directory in directories:
            if mriutil.isAfreesurferStructure(directory):
                self.info(
                    "{} seem's a valid freesurfer structure: moving it to {} directory".format(
                        directory, self.workingDir
                    )
                )
                shutil.move(directory, self.workingDir)
示例#8
0
 def meetRequirement(self):
     freesurferStructure = os.path.join(self.preparationDir, self.id)
     if not mriutil.isAfreesurferStructure(freesurferStructure):
         return False
     else:
         return Images((self.getPreparationImage('anat'), 'high resolution'))
示例#9
0
    def __isAValidStructure(self):
        """Determine if the directory is a valid structure

        Returns:
            a Boolean that represent if the subject integrity test pass for that directory

        """

        #Anatomical, Dwi and gradient encoding direction are mandatory input
        anat = util.getImage(self.config, self.workingDir, 'anat')
        if not anat:
            if util.getImage(self.config, self.workingDir, 'anat', None, 'nii'):
                self.warning("Found some uncompressed nifti images into {} directory. "
                           "Please gzip those images and resubmit the pipeline again".format(self.workingDir))
                return False
            self.warning("No high resolution image found into {} directory".format(self.workingDir))
            return False

        dwi = util.getImage(self.config, self.workingDir, 'dwi')
        if not dwi:
            if util.getImage(self.config, self.workingDir, 'dwi', None, 'nii'):
                self.warning("Found some uncompressed  nifti image into {} directory. "
                           "Please gzip those images and resubmit the pipeline again".format(self.workingDir))
                return False
            self.warning("No diffusion weight image found into {} directory".format(self.workingDir))
            return False

        bEnc = util.getImage(self.config, self.workingDir,'grad', None, 'b')
        bVals = util.getImage(self.config, self.workingDir,'grad', None, 'bvals')
        bVecs = util.getImage(self.config, self.workingDir,'grad', None, 'bvecs')

        directories = []

        for directory in os.listdir(self.workingDir):
            target = os.path.join(self.workingDir, directory)
            if os.path.isdir(target):
                directories.append(target)

        validFS = False
        for directory in directories:
            if mriutil.isAfreesurferStructure(directory):
                validFS = True

        if not validFS:
            self.warning("No valid freesurfer directory found in: {}".format(self.workingDir))
            return False

        if (not bEnc) and (not bVals or not bVecs):
            self.warning("No valid .b encoding or (.bvals, .bvecs) files found in directory: {}".format(self.workingDir))
            return False

        else:

            nbDirections = mriutil.getNbDirectionsFromDWI(dwi)
            if nbDirections <= 45:
                msg = "Found only {} directions into {} image. Hardi model will not be accurate with diffusion weighted image " \
                      "that contain less than 45 directions\n\n".format(nbDirections, dwi)
                self.warning(msg)
                #return False

            if bEnc and not self.__isValidEncoding(nbDirections, '.b'):
                self.warning("Encoding file {} is invalid".format(bEnc))
                return False

            if bVals and not self.__isValidEncoding(nbDirections, '.bvals'):
                self.warning("Encoding file {} is invalid".format(bEnc))
                return False

            if bVecs and not self.__isValidEncoding(nbDirections, '.bvecs'):
                self.warning("Encoding file {} is invalid".format(bVecs))
                return False

        #Validate optionnal images
        images = {
                  'anat': (anat, 'high resolution'),
                  'dwi': (dwi,'diffusion weighted'),
                  'mag': (util.getImage(self.config, self.workingDir, 'mag'), 'MR magnitude '),
                  'phase': (util.getImage(self.config, self.workingDir, 'phase'), 'MR phase '),
                  'b0_ap': (util.getImage(self.config, self.workingDir, 'b0_ap'), "posterior to anterior b0 "),
                  'b0_pa': (util.getImage(self.config, self.workingDir, 'b0_pa'), "anterior to posterior b0")}


        if self.config.get('arguments', 'debug') == 'True':
            self.debug("Images found into {} directory: {}".format(self.workingDir, images))


        if self.config.getboolean('arguments', 'prompt'):

            for key, (value, description) in images.iteritems():
                if value:
                    if not mriutil.isDataStridesOrientationExpected(value, self.config.get('preparation', 'stride_orientation'))\
                            and self.config.getboolean("preparation", "force_realign_strides"):
                        msg = "Data strides layout for {} is unexpected and force_realign_strides is set to True.\n \
                               If you continue, all unexpected images will be realign accordingly.\n\
                               Only a copy of the original images will be alter.".format(value)
                        if not util.displayYesNoMessage(msg):
                            self.warning("Remove this subject from the list?")
                            return False
                        else:
                            break

            #if one and only one b0 image is given, make sure that the b0 image is not on same direction than the dwi.
            if (not (images['b0_ap'][0] and images['b0_pa'][0])) and (images['b0_ap'][0] or images['b0_pa'][0])  \
                and (self.config.get("correction", "ignore") == "False"):
                if ((self.config.get("correction", "phase_enc_dir") == "0") and images['b0_pa'][0]) \
                    or ((self.config.get("correction", "phase_enc_dir") == "1")  and images['b0_ap'][0]):
                        msg = "Found only one B0 image into the subject directory and that B0 is in " \
                              "the same phase encoding direction than the DWI.\n" \
                              "We recommend to remove the B0 image so at least a motion correction will be perform"
                        if not util.displayYesNoMessage(msg):
                            self.warning("Remove this subject from the list?")
                            return False

            if images['mag'][0] and images['phase'][0] and (images['b0_ap'][0] or images['b0_pa'][0]):
                msg = "Found both Fieldmap and B0 images into the subject directory\n" \
                      "We recommend to disabled fieldmap correction?"
                if not util.displayYesNoMessage(msg):
                    self.warning("Remove this subject from the list?")
                    return False

        return True