Пример #1
0
 def process(self, _edObject=None):
     EDPluginExec.postProcess(self)
     EDVerbose.DEBUG("*** EDPluginChiToEDFv1_0.process")
     # Read the Chi file
     pyStrPathToChiFile = self.getDataInput().getChiFile().getPath(
     ).getValue()
     pyNumpyArray = numpy.loadtxt(pyStrPathToChiFile, skiprows=4)
     # Prepare the header dictionary
     self.m_edDictionaryHeader = {}
     for xsDataKeyValuePair in self.getDataInput().getHeader(
     ).getKeyValuePair():
         key = xsDataKeyValuePair.getKey().getValue()
         value = xsDataKeyValuePair.getValue().getValue()
         self.m_edDictionaryHeader[str(key)] = str(value)
     # Save it as an EDF file
     if self.getDataInput().getOutputPathEDF() is not None:
         strOutputPath = self.getDataInput().getOutputPathEDF().getPath(
         ).getValue()
     else:
         strOutputPath = self.getWorkingDirectory()
     if strOutputPath is None:
         strOutputPath = os.getcwd()
     if os.path.exists(strOutputPath):
         if os.path.isfile(strOutputPath):
             self._strEDFFile = strOutputPath
         else:  #it is a directory, I guess
             self._strEDFFile = os.path.join(
                 strOutputPath,
                 os.path.splitext(
                     os.path.basename(self.getDataInput().getChiFile().
                                      getPath().getValue()))[0] + ".edf")
     else:  #strOutputPath does not exist
         if strOutputPath.endswith("/"):
             try:
                 os.makedirs(strOutputPath, int("777", 8))
             except IOError:
                 raise IOError, "Unable to create directory named %s, please chech the rights or the input parameters." % strOutputPath
             self._strEDFFile = os.path.join(
                 strOutputPath,
                 os.path.splitext(
                     os.path.basename(self.getDataInput().getChiFile().
                                      getPath().getValue()))[0] + ".edf")
         else:  #it will be a file, the create the upper directory if needed
             upperDir = os.path.dirname(strOutputPath)
             if not os.path.isdir(upperDir):
                 try:
                     os.makedirs(upperDir, int("777", 8))
                 except IOError:
                     raise IOError, "Unable to create directory named %s, please chech the rights or the input parameters." % upperDir
             self._strEDFFile = strOutputPath
     print self._strEDFFile
     edfFile = EdfFile(self._strEDFFile)
     edfFile.WriteImage(self.m_edDictionaryHeader, pyNumpyArray)
Пример #2
0
    def writeData(self):

        if self.fileName.endswith('.edf'):
            fileEdf = EdfFile(self.fileName, access='wb')
            fileEdf.WriteImage({}, self.data)

        if self.fileName.endswith('.mat'):
            NameFile = self.fileName.split('/')[-1]
            NameFile = NameFile.split('.')[0]
            sio.savemat(self.fileName, {NameFile: self.data})

        if self.fileName.endswith('.tiff'):
            tifImage = TiffIO.TiffIO(self.fileName, 'wb+')
            tifImage.writeImage(self.data)

        if self.fileName.endswith('.png'):
            scipy.misc.imsave(self.fileName, self.data)

        if self.fileName.endswith('.dcm'):
            write_dicom(self.data, self.fileName)

        if self.fileName.endswith('.npy'):
            np.save(self.fileName, self.data)
Пример #3
0
    def process(self, _edObject=None):
        EDPluginControl.process(self)
        EDVerbose.DEBUG("EDPluginBioSaxsMetadatav1_0.process")
        if not os.path.isfile(self.strInputImage):
            EDVerbose.WARNING("The given input file does not exist !!!")
            header = {}
        else:
            header = EdfFile(self.strInputImage).GetHeader(0)
            for key in EDUtilsBioSaxs.TRANSLATION:
                if key in dir(self) and self.__getattribute__(key) is None:
                    if EDUtilsBioSaxs.TRANSLATION[key] in header:
                        if key in EDUtilsBioSaxs.FLOAT_KEYS:
                            setattr(
                                self, key,
                                float(header[EDUtilsBioSaxs.TRANSLATION[key]]))
                        else:
                            setattr(self, key,
                                    header[EDUtilsBioSaxs.TRANSLATION[key]])
        if self.strOutputImage is not None:
            if os.path.abspath(self.strOutputImage) != os.path.abspath(
                    self.strInputImage):
                shutil.copy(self.strInputImage, self.strOutputImage)
            keyToUpgrade = []
            for key in EDUtilsBioSaxs.TRANSLATION:
                if key in dir(self) and self.__getattribute__(key) is None:
                    if EDUtilsBioSaxs.TRANSLATION[key] not in header:
                        keyToUpgrade.append(key)
                    else:

                        if key in EDUtilsBioSaxs.FLOAT_KEYS:
                            oneHeader = float(
                                header[EDUtilsBioSaxs.TRANSLATION[key]])
                        else:
                            oneHeader = header[EDUtilsBioSaxs.TRANSLATION[key]]
                        oneValue = eval("self.%s" % key)
                        EDVerbose.DEBUG(
                            "key: %s value_header=%s(%s) value_extra=%s(%s)" %
                            (key, oneHeader, oneHeader.__class__,
                             eval("self.%s" % key), eval(
                                 "self.%s" % key).__class__))
                        if oneHeader != oneValue:
                            keyToUpgrade.append(key)
            for key in keyToUpgrade:
                if not self.__bSaxsMetadataFailed:
                    xsdi = XSDataInputSaxsAddMetadatav1_0()
                    xsdi.setInputImage(self.xsdInputData.getOutputImage())
                    xsdi.setKey(XSDataString(EDUtilsBioSaxs.TRANSLATION[key]))
                    xsdi.setValue(XSDataString("%s" % eval("self.%s" % key)))
                    edPlugin = self.loadPlugin(
                        self.__strControlledPluginMetadata)
                    edPlugin.setDataInput(xsdi)
                    edPlugin.connectSUCCESS(self.doSuccessMetadata)
                    edPlugin.connectFAILURE(self.doFailureMetadata)
                    edPlugin.executeSynchronous()

            if self.__bSaxsMetadataFailed:
                EDVerbose.screen(
                    "EDPluginBioSaxsMetadatav1_0.process: writeMetadata using EdfFile "
                )
                edf = EdfFile(self.strOutputImage)
                headers = [
                    edf.GetHeader(i) for i in xrange(edf.GetNumImages())
                ]
                data = [edf.GetData(i) for i in xrange(edf.GetNumImages())]
                del edf
                for key in EDUtilsBioSaxs.TRANSLATION:
                    if key in dir(self) and self.__getattribute__(key) is None:
                        header[EDUtilsBioSaxs.TRANSLATION[key]] = eval(
                            "self.%s" % key)

                edf = EdfFile(self.strOutputImage)
                if len(data) == 1:
                    edf.WriteImage(header, data[0], Append=0)
                elif len(data) > 1:
                    edf.WriteImage(header, data[0], Append=0)
                    for datum in data[1:]:
                        edf.WriteImage({}, datum, Append=1)
                else:
                    EDVerbose.WARNING("There are not data in %s !!!" %
                                      self.strInputImage)
Пример #4
0
    Comm.start()
    if DoConfigure:
        Comm.Configure()
        if not Comm.isAlive():
            raise SystemExit
        

    Comm.startAcquisition()
    if not Comm.isAlive():
        raise SystemExit

    while Comm.getCurrentCommand() != Comm.COM_NONE:        
        time.sleep(0.2)

    for i in range(Comm.getNbFramesReady()):
        if not Comm.isAlive():
            raise SystemExit       
        arr = Comm.getBuffer(i)
        arr.resize(240,566)
        f = EDF("%s_%.4d%s" % (filename,i,".edf"))
        f.WriteImage({},arr[:,5:565])
        del f

    Comm.quit()        
    del Comm

if __name__ == "__main__":
    main()

Пример #5
0
]:
    if os.path.isfile(pystSinogramFilename):
        edf = EdfFile(pystSinogramFilename)
        npSinogramArray = edf.GetData(0)
    else:
        npSinogramArray = roi.getEmptySinogramArray()
        edf = EdfFile(pystSinogramFilename)

    if pystSinogramFilename == "sinogramPhotonFlux.edf":
        npSinogramArray[pyintXpos, pyintYpos] = roi.pyfPhotonFlux
    elif pystSinogramFilename == "sinogramIntegratedRaw.edf":
        npSinogramArray[pyintXpos, pyintYpos] = roi.integrate()
    elif pystSinogramFilename == "sinogramIntegratedCor.edf":
        npSinogramArray[pyintXpos,
                        pyintYpos] = roi.integrate() / roi.pyfPhotonFlux
    edf.WriteImage(pydMetaDataEDF, npSinogramArray, Append=0)

pylRegionsOfInterest = []

if cif.exists("_pd_sum_2theta_range_min"):
    pylRegionsOfInterest.append([
        float(cif["_pd_sum_2theta_range_min"]),
        float(cif["_pd_sum_2theta_range_max"])
    ])
else:
    for oneloop in cif["loop_"]:
        if "_pd_sum_2theta_range_min" in oneloop[0]:
            for i in oneloop[1]:
                pylRegionsOfInterest.append([
                    float(i["_pd_sum_2theta_range_min"]),
                    float(i["_pd_sum_2theta_range_max"])
Пример #6
0
    def saveDiffractionImage(self,
                             filename,
                             colorMaps,
                             colorMapName,
                             maskedPixelInfo,
                             pixel1X=None,
                             pixel1Y=None,
                             pixel2X=None,
                             pixel2Y=None,
                             lowerBound=0,
                             upperBound=1,
                             logScale=None,
                             invert=None,
                             drawQLines=None,
                             drawdQLines=None,
                             QData=None,
                             calibrationData=None,
                             drawPeaks=None,
                             peakList=None,
                             qLinesColor=None,
                             dQLinesColor=None,
                             peakLinesColor=None):

        # save EDF data specially
        if getextension(filename) == ".edf":
            edf = EdfFile(filename)
            #You can write any relevant information in the dictionnary.
            edf.WriteImage(
                {
                    'Title':
                    "Edf file converted by the Area Diffraction Machine"
                },
                Numeric.transpose(self.theDiffractionData.data),
                DataType="SignedInteger",
                Append=0)
            del edf  # to force file close
            return

        # otherwise, try to save it using the PIL

        image = self.getDiffractionImage(colorMaps, colorMapName,
                                         maskedPixelInfo, None, None, None,
                                         None, None, None, lowerBound,
                                         upperBound, logScale, invert)

        if drawQLines or drawdQLines:
            if QData == None:
                raise Exception(
                    "Cannot save the diffraction data until a q list is given."
                )
            if calibrationData == None:
                raise Exception(
                    "Cannot save the diffraction data until the calibration Data is given."
                )

            if drawQLines:
                if qLinesColor == None:
                    raise Exception(
                        'Cannot add q lines to the saved image until the q line color is set.'
                    )
                for Q, dQ in QData.getAllQPairs():
                    MakeDiffractionImage.addConstantQLineDiffractionImage(
                        image, Q, calibrationData, qLinesColor)

            if drawdQLines:
                if dQLinesColor == None:
                    raise Exception(
                        'Cannot add delta q lines to the saved image until the delta q line color is set.'
                    )
                for Q, dQ in QData.getAllQPairs():
                    MakeDiffractionImage.addConstantQLineDiffractionImage(
                        image, Q - dQ, calibrationData, dQLinesColor)
                    MakeDiffractionImage.addConstantQLineDiffractionImage(
                        image, Q + dQ, calibrationData, dQLinesColor)

        if drawPeaks and peakList != None:
            if peakLinesColor == None:
                raise Exception(
                    "Cannot  add peaks to the saved iamge until the peak color is set."
                )

            MakeDiffractionImage.addPeaksDiffractionImage(
                image, peakList, peakLinesColor)

        # by default, return entire image
        if pixel1X != None and pixel1Y != None and pixel2X != None and pixel2Y != None:
            image = image.crop(
                (min(int(pixel1X),
                     int(pixel2X)), min(int(pixel1Y), int(pixel2Y)),
                 max(int(pixel1X),
                     int(pixel2X)), max(int(pixel1Y), int(pixel2Y))))
        try:
            image.save(filename)
        except Exception, e:
            raise UserInputException(
                "Cannot save image: %s has an unknown file extension" %
                filename)