def __convertDicomToNrrd(self, dicomDir, convertedFileNameWithPath, seriesNumber):
        nrrdList = glob.glob(os.path.dirname(convertedFileNameWithPath) + "/*_" + seriesNumber + ".nrrd")
        if os.path.exists(convertedFileNameWithPath) or len(nrrdList) > 0:
            self.logger.info(convertedFileNameWithPath + " already exists, no conversion needed.")
            numVols = re.search("DWI-(\d+)", convertedFileNameWithPath).group(1)
            return numVols
        # commandList = ["/scratch/msscully/development/DicomToNrrd/StandAloneDicomToNrrdConverter-build/bin/DicomToNrrdConverter"]
        commandList = [self.dicomToNrrdPath]
        commandList.append("--inputDicomDirectory")
        commandList.append(dicomDir)
        commandList.append("--outputVolume")
        commandList.append(convertedFileNameWithPath)
        # Will only affect Seimens data
        commandList.append("--useBMatrixGradientDirections")
        self.logger.info(" ".join(commandList))
        self.logger.info("Converting " + dicomDir + " to " + convertedFileNameWithPath)
        my_env = os.environ
        my_env["FREESURFER_HOME"] = "/opt/freesurfer"
        # output = phdUtils.check_output(commandList,stderr=sys.stdout,env=my_env)
        output = phdUtils.check_output(commandList, env=my_env)
        self.logger.info(output)

        searchMatch = re.search("Number of usable volumes\: (\d+)", output)
        if searchMatch:
            numberVolumes = searchMatch.group(1)
            return numberVolumes
        else:
            # TODO Decide if this is really an error and handle it more gracefully
            self.logger.warn("Couldn't find number of volumes. Error?")
            exit(1)
    def __convertNiftiToMGZ(self, niftiGZFileNameWithPath, newMGZFileNameWithPath, tempDir):
        if os.path.exists(newMGZFileNameWithPath):
            self.logger.info(newMGZFileNameWithPath + " already exists, no conversion needed.")
            return
        # Need to unzip the .nii.gz version
        commandList = ["gunzip", "-f", niftiGZFileNameWithPath]
        self.logger.info(phdUtils.check_output(commandList, stderr=sys.stdout))

        niftiFileName = niftiGZFileNameWithPath.rstrip(".gz")

        dicomFiles = os.listdir(tempDir)
        data = dicom.read_file(os.path.join(tempDir, dicomFiles[0]))
        te = data.EchoTime
        tr = data.RepetitionTime
        flip = data.FlipAngle

        # Pass all the above to mri_convert
        commandList = ["/opt/freesurfer/bin/mri_convert"]
        commandList.append("-te")
        commandList.append(str(te))
        commandList.append("-tr")
        commandList.append(str(tr))
        if "InversionTime" in data:
            commandList.append("-TI")
            commandList.append(str(data.InversionTime))
        commandList.append("-flip_angle")
        commandList.append(str(flip))
        commandList.append("-it")
        commandList.append("nii")
        commandList.append(niftiFileName)
        commandList.append(newMGZFileNameWithPath)
        self.logger.info("Converting " + niftiGZFileNameWithPath + " to " + newMGZFileNameWithPath)
        # print " ".join(commandList)
        self.logger.info(phdUtils.check_output(commandList, stderr=sys.stdout))

        # Re-zip the .nii file
        commandList = ["gzip", niftiFileName]
        self.logger.info(phdUtils.check_output(commandList, stderr=sys.stdout))
 def __convertDicomToNifti(self, dicomDir, convertedFileNameWithPath):
     if os.path.exists(convertedFileNameWithPath):
         self.logger.info(convertedFileNameWithPath + " already exists, no conversion needed.")
         return
     # commandList = ["/opt/brains2/bin/ConvertBetweenFileFormats"]
     commandList = [self.convertBetweenFormatsPath]
     commandList.append(dicomDir)
     commandList.append(convertedFileNameWithPath)
     self.logger.info(" ".join(commandList))
     self.logger.info("Converting " + dicomDir + " to " + convertedFileNameWithPath)
     try:
         self.logger.info(phdUtils.check_output(commandList, stderr=sys.stdout))
     except subprocess.CalledProcessError as e:
         self.logger.error("ConvertBetweenFileFormats threw an exception.")
         self.logger.error(e)
 def __convertDicomToMGZ(self, dicomDir, convertedFileNameWithPath):
     if os.path.exists(convertedFileNameWithPath):
         self.logger.info(convertedFileNameWithPath + " already exists, no conversion needed.")
         return
     # commandList = ["/opt/freesurfer/bin/mri_convert"]
     commandList = [self.mriConvertPath]
     commandList.append("-it")
     commandList.append("dicom")
     commandList.append(dicomDir)
     commandList.append(convertedFileNameWithPath)
     self.logger.info("Converting " + dicomDir + " to " + convertedFileNameWithPath)
     self.logger.info(" ".join(commandList))
     my_env = os.environ
     my_env["FREESURFER_HOME"] = "/opt/freesurfer"
     try:
         self.logger.info(phdUtils.check_output(commandList, stderr=sys.stdout, env=my_env))
     except subprocess.CalledProcessError as e:
         self.logger.warn("mri_convert threw an exception." + str(e), exc_info=True)
    def __uploadScanToPredict(self,dicomDirs,newScanID,predictProjectName,rpacsSubjectLabel):
        " upload images to predict xnat"
        self.logger.info("Starting upload of {0} to predict project {1}".format(
            newScanID, predictProjectName))
        dicomRemap = self.predictDicomRemap
        baseAnon = self.predictBaseAnon
        dicomScp = self.predictDicomScp
        tempAnonDir = tempfile.mkdtemp()
        anonScript = tempAnonDir+"/anon-"+predictProjectName+"_"+rpacsSubjectLabel+"_"+str(newScanID)+".das"
        shutil.copy(baseAnon,anonScript)
        anonOut = open(anonScript,'a')
        anonOut.write("// TODO: fix this later\n")
        anonOut.write("//(0008,103e) := $ { SERIES_DESCRIPTION }\n")
        anonOut.write('\n')
        anonOut.write("// Note: this part isn't suitable for DicomRemap, which doesn't\n")
        anonOut.write("// yet handle user-assigned variables.\n")
        anonOut.write("(0020,0010) := \"{0}\"\n".format('site-024'))
        anonOut.write("(0008,0050) := \"{0}\"\n".format(predictProjectName))
        anonOut.write("(0008,1030) := \"{0}\"\n".format(predictProjectName))
        anonOut.write("(0010,0010) := \"{0}\"\n".format(rpacsSubjectLabel))
        anonOut.write("(0010,0020) := \"{0}\"\n".format(newScanID))
        ##  http://www.xnat.org/DicomServer has notes regarding the exact formatting of this field
        anonOut.write("(0010,4000) := \"Project: {0}; Subject: {1}; Session: {2}; AA:true\"\n".format(predictProjectName,rpacsSubjectLabel,newScanID))
        anonOut.close()

        ##  # All the directories to anonimize
        dicomDirs = " ".join(dicomDirs)

        remapCommand=dicomRemap+" -d "+anonScript+" -o "+dicomScp+" "+ dicomDirs
        self.logger.debug(remapCommand)
        command_list=[dicomRemap, '-d '+anonScript, '-o '+dicomScp, dicomDirs]

        try:
            tmpOutput = phdUtils.check_output(command_list,stderr=subprocess.STDOUT)
            if re.search('Exception',tmpOutput):
                self.logger.critical("An exception occurred while running the dicom remap command. Output follows.\n"+tmpOutput)
            self.logger.debug(tmpOutput)
        except Exception as e:
            self.logger.critical("An Exception occurred when running the dicom remap command! " + e)
            exit(1)