Ejemplo n.º 1
0
    def __init__(self, filename):

        self.filename = filename

        try:
            file = open(self.filename, 'r')
            file.close()
        except IOError:
            raise UserInputException('%s does not exist' % self.filename)

        # first read header

        try:
            width,height,self.headerDistance,self.headerPixelLength, \
                    self.headerPixelHeight,self.headerWavelength = \
                    MarCCDWrap.get_header(self.filename)
        except:
            raise UserInputException("Unable to open MarCCD data file %s." %
                                     self.filename)

        # since marCCD data is just tiff data, we can just open the
        # file as though it is a tiff image and get the data and
        # dimensions out of it.
        temp = Tiff(self.filename)
        self.data = temp.data
        self.size = temp.size
Ejemplo n.º 2
0
    def toFile(self,filename,energyOrWavelength):
        if self.centerX['val'] == None or self.centerX['fixed']==None:
            raise UserInputException('Function toFile() cannot run because the x center has not been set yet.')
        if self.centerY['val'] == None or self.centerY['fixed']==None:
            raise UserInputException('Function toFile() cannot run because the y center has not been set yet.')
        if self.distance['val'] == None or self.distance['fixed']==None:
            raise UserInputException('Function toFile() cannot run because the distance has not been set yet.')
        if self.energy['val'] == None or self.energy['fixed']==None:
            return UserInputException('Function toFile() cannot run because neither the wavelength nor the energy have been set yet.')
        if self.alpha['val']== None or self.alpha['fixed']==None:
            raise UserInputException('Function toFile() cannot run because alpha has not been set yet.')
        if self.beta['val'] == None or self.alpha['fixed']==None:
            raise UserInputException('Function toFile() cannot run because beta has not been set yet.')
        if self.rotation['val'] == None or self.rotation['fixed']==None:
            raise UserInputException('Function toFile() cannot run because rotation has not been set yet.')
        if self.pixelLength['val'] == None:
            raise UserInputException('Function toFile() cannot run because the pixel length has not been set yet.')
        if self.pixelHeight['val'] == None:
            raise UserInputException('Function toFile() cannot run because the pixel height has not been set yet.')

        energyOrWavelength = energyOrWavelength.lower()
        if energyOrWavelength != 'energy' and energyOrWavelength != 'wavelength':
            raise UserInputException("Function toFile() cannot run because parameter energyOrWavelength must be set to either 'energy' or 'wavelength'.")

        file = open(filename,'w')
        file.write("# Calibration File\n")

        # write the fixed values to the file
        dict = self.getCenterX()
        file.write('xc\t%f\t%d\n' % (dict['val'],dict['fixed']))

        dict = self.getCenterY()
        file.write('yc\t%f\t%d\n' % (dict['val'],dict['fixed']))

        dict = self.getDistance()
        file.write('D\t%f\t%d\n' % (dict['val'],dict['fixed']))

        if energyOrWavelength == 'energy':
            dict = self.getEnergy()
            file.write('E\t%f\t%d\n' % (dict['val'],dict['fixed']))
        if energyOrWavelength == 'wavelength':
            dict = self.getWavelength()
            file.write('wavelength\t%f\t%d\n' % (dict['val'],dict['fixed']))

        dict = self.getAlpha()
        file.write('alpha\t%f\t%d\n' % (dict['val'],dict['fixed']))

        dict = self.getBeta()
        file.write('beta\t%f\t%d\n' % (dict['val'],dict['fixed']))
        
        dict = self.getRotation()
        file.write('rotation\t%f\t%d\n' % (dict['val'],dict['fixed']))

        dict = self.getPixelLength()
        file.write('pixelLength\t%f\n' % dict['val'])

        dict = self.getPixelHeight()
        file.write('pixelHeight\t%f\n' % dict['val'])
Ejemplo n.º 3
0
    def setCenterY(self,val,fixed=0,lower=None,upper=None):
        if fixed != 0 and fixed != 1:
            raise UserInputException("Cannot set the y center because fixed must be either 0 or 1.")
        if lower != None and lower >= val:
            raise UserInputException("Cannot set the y center because the lower bound must be less then the value.")
        if upper != None and upper <= val:
            raise UserInputException("Cannot set the y center because the upper bound must be greater then the value.")

        self.centerY = {'val':val,'fixed':fixed,'lower':lower,'upper':upper}
Ejemplo n.º 4
0
    def setRotation(self,val,fixed=0,lower=None,upper=None):
        if fixed != 0 and fixed != 1:
            raise UserInputException("Cannot set the rotation angle because fixed must be set to 0 or 1.")
        if lower != None and lower >= val:
            raise UserInputException("Cannot set the rotation angle because the lower bound must be less then the value.")
        if upper != None and upper <= val:
            raise UserInputException("Cannot set the rotation angle because the upper bound must be greater then the value.")
        if val < -360 or val > 360:
            raise UserInputException("Cannot set the rotation angle because it must be between -90 and 90")

        self.rotation = {'val':val,'fixed':fixed,'lower':upper,'upper':lower} 
Ejemplo n.º 5
0
    def setDistance(self,val,fixed=0,lower=None,upper=None):
        if fixed != 0 and fixed != 1:
            raise UserInputException("Cannot set the distance because fixed must be either to 0 or 1.")
        if lower != None and lower >= val:
            raise UserInputException("Cannot set the distance because the lower bound must be less then the value.")
        if upper != None and upper <= val:
            raise UserInputException("Cannot set the distance because the upper bound must be greater then the value.")
        if val <= 0:
            raise UserInputException("Canont set the distance because it must be a positive quantity.")

        self.distance = {'val':val,'fixed':fixed,'lower':lower,'upper':upper}
Ejemplo n.º 6
0
    def setEnergy(self,val,fixed=0,lower=None,upper=None):
        """ The energy input is in units of eV. """
        if fixed != 0 and fixed != 1:
            raise UserInputException("Cannot set the energy because fixed must be either 0 or 1.")
        if lower != None and lower >= val:
            raise UserInputException("Cannot set the energy because the lower bound must be less then the value.")
        if upper != None and upper <= val:
            raise UserInputException("Cannot set the energy because the upper bound must be greater then the value.")
        if val <= 0:
            raise UserInputException("Cannot set the energy because it must be a positive quantity.")

        self.energy = {'val':val,'fixed':fixed,'lower':lower,'upper':upper}
Ejemplo n.º 7
0
    def setWavelength(self,val,fixed=0,lower=None,upper=None):
        if fixed != 0 and fixed != 1:
            raise UserInputException("Cannot set the wavelength because fixed must be set to 0 or 1.")
        if lower != None and lower >= val:
            raise UserInputException("Cannot set the wavelength because the lower bound on wavelength must be less then the value.")
        if upper != None and upper <= val:
            raise UserInputException("Cannot set the wavelength because the upper bound on wavelength must be greater then the value.")
        if val <= 0:
            raise UserInputException("Cannot set the wavelength because it must be a positive quantity.")

        val = Transform.convertWavelengthToEnergy(val)
        if lower != None: lower=hc/upper
        if upper != None: upper=hc/lower
        # note that a low wavelength is the same as a high energy and vice versa!
        self.energy = {'val':val,'fixed':fixed,'lower':upper,'upper':lower} 
Ejemplo n.º 8
0
    def __init__(self, filename):

        try:
            file = open(filename, 'r')
            file.close()
        except IOError:
            raise UserInputException('%s does not exist' % filename)

        img = Image.open(filename)
        self.filename = filename

        self.size = max(img.size[0], img.size[1])

        img = img.convert('I')  #convert to int
        temp = Numeric.fromstring(img.tostring(), Numeric.Int32)

        # I am not exactly sure why PI and Numeric's tostring and
        # fromstring method are transposed relative to eachother,
        # but this code is what works
        temp.shape = img.size[1], img.size[0]

        # pad values if necessary
        self.data = Numeric.zeros((self.size, self.size), Numeric.Int32)
        self.data[0:temp.shape[0], 0:temp.shape[1]] = temp
        self.data = Numeric.transpose(self.data)
Ejemplo n.º 9
0
    def __init__(self, filename):

        try:
            f = EdfFile.EdfFile(filename)
        except:
            raise UserInputException("""Unable to read in the file \
%s because the Object EdfFile that I am using to read in edf data \
raised an error when trying to read in the file. This probably means \
that there is something wrong \
with the file that you are trying to open""" % filename)

        data = f.GetData(0)

        if not alltrue(alltrue(less_equal(data, 2147483647))):
            print """Warning, some of the data stored in the \
file %s has an intensity larger then 2^31-1 which is too big for this \
program to hold. Any of these large values were clipped to have a value 
of 2^31-1.""" % filename

        # clip any data that is too big
        mask1 = data <= 2147483647
        mask2 = data > 2147483647
        masked_data = data * mask1 + (pow(2, 31) - 1) * mask2
        masked_data = masked_data.astype(Numeric.Int32)

        self.size = max(masked_data.shape[0], masked_data.shape[1])

        # pad values if necessary - create an array to put everything in
        self.data = Numeric.zeros((self.size, self.size), Numeric.Int32)

        # copy the data into the padded array
        self.data[0:masked_data.shape[0], 0:masked_data.shape[1]] = masked_data
        self.data = Numeric.transpose(self.data)
Ejemplo n.º 10
0
    def getWavelength(self):
        if self.energy['val'] == None or self.energy['fixed'] == None:
            return UserInputException('Cannot get the wavelength because neither the wavelength nor the energy have been set.')

        val = Transform.convertEnergyToWavelength(self.energy['val'])
        lower,upper=None,None
        if self.energy['lower'] != None: lower = hc/self.energy['upper']
        if self.energy['upper'] != None: upper = hc/self.energy['lower']
        return {'val':val,'fixed':self.energy['fixed'],'lower':lower,'upper':upper}
Ejemplo n.º 11
0
def splitPaths(string):
    """ Takes in a string of file names and folder names that are
        separated by spaces and returns a list of file names. This
        would seem like a stupid function because split() would do
        the job just as well, but this function is special in that
        it can deal with filenames with spaces in them. If some of
        the file names are not real files existing in teh computer, 
        an exception is raised. 

        Note that there is a 'bug' in the algorithm where it will not
        recognize real files with spaces at the end of the file.
        But seriously, I have never seen a file seriously do this.
        
        These doctests are too unix-ish and will fail on a windows machine.
        But they are good enough to convince me the function works for now.

            >>> import tempfile
            >>> dir = tempfile.mkdtemp() 
            >>> os.popen("touch '%s/a file.txt'" % dir).close()
            >>> os.popen("touch '%s/a nother file'" % dir).close()
            >>> os.popen("mkdir '%s/temp folder/'" % dir).close()
            >>> os.popen("touch '%s/temp folder/some final file'" % dir).close()
            >>> string = '   %s  %s/ %s/a file.txt %s/a nother file  %s/temp folder %s/temp folder/ %s/temp folder/some final file' % (dir,dir,dir,dir,dir,dir,dir)
            >>> split = splitPaths(string)
            >>> expected = ['%s' % dir, '%s/' % dir, '%s/a file.txt' % dir, '%s/a nother file' % dir, '%s/temp folder' % dir, '%s/temp folder/' % dir, '%s/temp folder/some final file' % dir]
            >>> split == expected
            True
    """

    # split on newline into chunks separated by spaces
    list = string.strip().split(' ')
    filesOrDirectories = []

    # loop through all the chunks of the string
    while len(list) > 0:
        filename = list.pop(0)

        # if there were several spaces between a filename, some of the 'chunks'
        # will be blank characters, so we should just ignore them and move
        # along
        if filename == '':
            continue
        # If the current chunk is not a valid path name, append the next chunk
        while not os.path.exists(filename):
            if len(list) < 1:
                raise UserInputException(
                    "'%s' cannot be split into a bunch of file names becaues the name '%s' (or possibly some earlier chunks of it) does not exist."
                    % (filename, filename))
            # add the next item, remembering that the split removed
            # the space so we have to explicitly add it back in.
            filename = filename + ' ' + list.pop(0)

        # add the valid path we found
        filesOrDirectories.append(filename)

    return filesOrDirectories
Ejemplo n.º 12
0
    def addQPair(self, Q, dQ=0):
        """ Input a pair of Q and delta Q values into the list of Q values. 
            If no delta Q value is given, delta Q's default value is 0.
            Q ranges can not overlap, so if an overlapping Q range is given,
            then an error is raised and the value is not added. """
        if Q < 0:
            raise UserInputException(
                "Error, cannot complete function addQPair because Q<0.")

        # test if Q ranges overlap
        for QLoop, dQLoop in self.getAllQPairs():
            if (QLoop + dQLoop > Q - dQ and QLoop - dQLoop < Q + dQ):
                raise UserInputException(
                    "Error, cannot complete fucntion addQPair because the input pair (%f,%f) overlaps the pair (%f,%f)"
                    % (Q, dQ, QLoop, dQLoop))

        self.QList.append([Q, dQ])
        self.QList.sort()  # sort list so greater Q values are lower in list.
        self.current = 0
Ejemplo n.º 13
0
 def isInQRange(self, Q):
     """ This function looks to see if a given Q value is in the
         range of any of Q ranges inside the object. If it is, 1 
         is returned. Otherwise, 0 is returned. """
     if Q < 0:
         raise UserInputException(
             "Error, cannot complete function addQPair because Q<0.")
     for loop in self.QList:
         if Q < loop[0] + loop[1] and Q > loop[0] - loop[1]:
             return 1
     return 0
Ejemplo n.º 14
0
    def next(self):
        """ This function can be used for iterating through all 
        the Q,dQ pairs. """
        if self.current == '':
            raise UserInputException('Function next() cannot be \
called because no Q values have been entered into the array')

        if self.current >= len(self.QList):
            self.current = 0
            return ''

        val = self.QList[self.current]
        self.current += 1
        return val
    def savePolygonsToFile(self, filename):
        if self.numPolygons() < 1:
            raise UserInputException("Cannot save polygons to a \
file until there are polygons to save.")
        file = open(filename, 'w')
        file.write("# Polygon(s) drawn on " + time.asctime() + "\n")
        for i in range(self.polygonBeginningsIndex.shape[0]):
            index = self.polygonBeginningsIndex[i]
            size = self.polygonNumberOfItems[i]

            for j in range(size):
                file.write(
                    str(self.polygonsX[index + j]) + '\t' +
                    str(self.polygonsY[index + j]) + '\n')
            file.write('\n')
Ejemplo n.º 16
0
    def fromFile(self, filename):
        self.QList = []
        self.current = ''

        file = open(filename, 'rU')

        originalLine = file.readline()
        line = originalLine.split('#')[0].lower()

        # any blank lines should be ignored
        while line == '':
            originalLine = file.readline()
            line = originalLine.split('#')[0].lower()

        words = line.split()
        # remove possible comments

        # Q delta Q, it will be split into ["Q","delta","Q"], so
        # we want to restructure it so that it looks like
        # ["Q","delta Q"] for easy parsing later.
        if len(words) == 3 and words[1] == "delta":
            words = [words[0], words[1] + ' ' + words[2]]

        if len(words) != 2:
            raise UserInputException('%s is not a proper QData file. \
The first line of the file is "%s" but it should be of the form \
"Q dQ" or "D dD".' % (filename, originalLine))

        if words[0] == "q":
            if words[1] != "dq" and words[1] != "delta q":
                raise UserInputException('%s is not a proper QData file. \
The first line of the file is "%s" but it should be of the form \
"Q    dQ" or "D   dD".' % (filename, originalLine))

            line = file.readline()
            while line:
                line = line.split('#')[0]
                if line == '':  # if it was a comment line, go on
                    line = file.readline()
                    continue

                words = line.split()
                if len(words) != 2:
                    raise UserInputException('%s is not a proper QData file. \
One of the lines of data does not have exactly 2 numbers (one for the value, \
and one for the uncertainty).' % filename)

                self.addQPair(float(words[0]), float(words[1]))

                line = file.readline()

            # parse in data

        elif words[0] == "d":
            if words[1] != "dd" and words[1] != "delta d":
                raise UserInputException('%s is not a proper QData file. The \
first line of the file is "%s" but it should be of the form "Q    dQ" or \
"D   dD".' % (filename, line))

            line = file.readline()
            while line:
                # parse
                line = line.split('#')[0]
                if line == '':  # if it was a comment line, go on
                    line = file.readline()
                    continue

                words = line.split()
                if len(words) != 2:
                    raise UserInputException('%s is not a proper QData file. \
One of the lines of data does not have exactly 2 numbers (one for the value, \
and one for the uncertainty).' % filename)

                self.addDPair(float(words[0]), float(words[1]))
                line = file.readline()

        else:
            raise UserInputException(
                '%s is not a proper QData file. The first \
line of the file is "%s" but it should be of the form "Q    dQ" or \
"D   dD".' % (filename, line))
Ejemplo n.º 17
0
 def getEnergy(self):
     if self.energy['val']==None or self.energy['fixed']== None:
         return UserInputException('Cannot get the energy because neither the wavelength nor the energy have been set yet.')
     
     return copy.copy(self.energy)
Ejemplo n.º 18
0
 def getAlpha(self):
     if self.alpha['val']==None or self.alpha['fixed']== None:
         raise UserInputException('cannot get alpha because it has not been set.')
     
     return copy.copy(self.alpha)
    def loadPolygonsFromFile(self, filename):
        """ This function reads in one or more polygons
            from a file and stores them in the object
            along with any other polygons already
            stored in the object. """

        print 'file = ', filename

        file = open(filename, 'r')

        currentPolygon = []

        line = file.readline()
        while line:
            # remove comments from the line
            line = line.split('#')[0]
            line = line.strip()

            # Any blank or comment lines signify a new polygon
            if line == '':
                # add in the previous polygon (if possible)
                # and start a new one.

                if currentPolygon != []:
                    # if a polygon was stored from before
                    # then add the polygon to the file

                    if len(currentPolygon) <= 4:
                        # if we found less then 3 polygon
                        # coordinates before a break,
                        # raise an error because all polygons
                        # need 3 coordinates
                        raise UserInputExcpetion('"%s" is not \
a valid polygon file because one of the polygon has fewer then \
3 coordinates.' % (filename))

                    self.addPolygon(currentPolygon)

                    currentPolygon = []  # reset polygon

            else:
                # otherwise, read the next pair of coordinates in
                pair = line.split()
                if len(pair) != 2:
                    raise UserInputException('"%s" is not a \
valid line in the polygon file %s. Polygon lines should only \
have the x coordinate followed by the y coordinate with only \
spaces between them.' % (line, filename))

                try:
                    currentPolygon += (float(pair[0]), float(pair[1]))
                except:
                    raise UserInputException('"%s" is not a \
valid line in the polygon file %s. Polygon lines need to have \
valid numbers for the x and y coordinate.' % (line, filename))

            line = file.readline()

        # there could be one final polygon to store in the file

        if currentPolygon != []:

            if len(currentPolygon) <= 4:
                # if we found less then 3 polygon coordinates
                # before a break, raise an error because all
                # polygons need 3 coordinates
                raise UserInputExcpetion('"%s" is not a valid \
polygon file because one of the polygon has fewer then 3 \
coordinates.' % (filename))

            self.addPolygon(currentPolygon)

            currentPolygon = []  # reset polygon
Ejemplo n.º 20
0
 def getBeta(self):
     if self.beta['val']==None or self.beta['fixed']== None:
         raise UserInputException('Cannot get beta because it has not been set.')
    
     return copy.copy(self.beta)
Ejemplo n.º 21
0
 def setPixelHeight(self,val):
     if val<=0:
         raise UserInputException("Cannot set the pixel height because it must be greater then 0.")
     self.pixelHeight= {'val':val}
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
    def saveCakeImage(self,
                      filename,
                      calibrationData,
                      qLower,
                      qUpper,
                      numQ,
                      chiLower,
                      chiUpper,
                      numChi,
                      doPolarizationCorrection,
                      P,
                      maskedPixelInfo,
                      colorMaps,
                      colorMapName,
                      lowerBound,
                      upperBound,
                      logScale=None,
                      invert=None,
                      drawQLines=None,
                      drawdQLines=None,
                      QData=None,
                      drawPeaks=None,
                      peakList=None,
                      qLinesColor=None,
                      dQLinesColor=None,
                      peakLinesColor=None):

        image = self.getCakeImage(
            calibrationData=calibrationData,
            qLower=qLower,
            qUpper=qUpper,
            numQ=numQ,
            chiLower=chiLower,
            chiUpper=chiUpper,
            numChi=numChi,
            doPolarizationCorrection=doPolarizationCorrection,
            P=P,
            maskedPixelInfo=maskedPixelInfo,
            width=None,
            height=None,
            colorMaps=colorMaps,
            colorMapName=colorMapName,
            lowerBound=lowerBound,
            upperBound=upperBound,
            logScale=logScale,
            invert=invert)

        if drawQLines or drawdQLines:
            if QData == None:
                raise Exception(
                    "Cannot save the cake data until a q list 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():
                    Cake.addConstantQLineCakeImage(image, Q, qLower, qUpper,
                                                   numQ, chiLower, chiUpper,
                                                   numChi, 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():
                    Cake.addConstantQLineCakeImage(image, Q - dQ, qLower,
                                                   qUpper, numQ, chiLower,
                                                   chiUpper, numChi,
                                                   dQLinesColor)
                    Cake.addConstantQLineCakeImage(image, Q + dQ, qLower,
                                                   qUpper, numQ, chiLower,
                                                   chiUpper, numChi,
                                                   dQLinesColor)

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

            smallest = self.getSmallestRange(calibrationData)

            Cake.addPeaksCakeImage(image,
                                   qLower,
                                   qUpper,
                                   numQ,
                                   chiLower,
                                   chiUpper,
                                   numChi,
                                   peakList,
                                   calibrationData,
                                   peakLinesColor,
                                   smallestRangeQLower=smallest['qLower'],
                                   smallestRangeQUpper=smallest['qUpper'],
                                   smallestRangeChiLower=smallest['chiLower'],
                                   smallestRangeChiUpper=smallest['chiUpper'])
        try:
            image.save(filename)
        except Exception, e:
            raise UserInputException(
                "Cannot save the cake: %s has an unknown file extension" %
                filename)
Ejemplo n.º 24
0
    def __init__(self, filenames, extension=None):
        """ Does everything to initialize the object. 
            Either you can pass in the type of file that you are using
            by explicitly giving its extension, or the program can try
            to figure this out for you. filenames must be a list of all of the
            files that will be opened and added together. If the list 
            only has one file in it, then only that one will be loaeded. """

        if len(filenames) < 1:
            raise Exception(
                "Cannot initialize a DiffractionData object without being given at least one file to load in."
            )

        if len(filenames) > 1:
            # Many files to load

            if extension == None:

                extensions = []
                for file in filenames:
                    split = os.path.basename(file).split('.')
                    if len(split) > 0:
                        extension = split[-1]
                    extensions.append(extension.lower())

                for extension in extensions:
                    if extension != extensions[0]:
                        raise UnknownFiletypeException(
                            "Cannot read in multiple files because they do not have the same extension"
                        )

                extension = extensions[0]  # Only one extension to store

            allData = []
            for file in filenames:
                if extension in ["mar2300", "mar3450"]:
                    allData.append(MarXXXX.MarXXXX(file))
                elif extension == "mccd":
                    allData.append(MarCCD.MarCCD(file))
                elif extension == "edf":
                    allData.append(ESRF.ESRF(file))
                elif extension in ["tiff", "tif"]:
                    allData.append(Tiff.Tiff(file))
                else:
                    raise UnknownFiletypeException(
                        "%s is an unknown filetype" % file)

            for data in allData:
                if data.size != allData[0].size:
                    raise UserInputException(
                        "Cannot add files because they are of different size.")

            filename = ""
            # store all filenames in one string
            for index in range(len(allData)):
                filename += allData[index].filename.strip() + " "

            self.theDiffractionData = allData.pop()  # store all iamges in one

            # add all the data together
            for data in allData:
                self.theDiffractionData.data += data.data

            # store the merged filename for later
            self.theDiffractionData.filename = filename

        else:
            # Only one file to load

            filename = filenames[0]  # get out the only file

            if extension == None:
                split = os.path.basename(filename).split('.')
                if len(split) > 0:
                    extension = split[-1]

            extension = extension.lower()

            if extension in ["mar2300", "mar3450"]:
                self.theDiffractionData = MarXXXX.MarXXXX(filename)
            elif extension == "mccd":
                self.theDiffractionData = MarCCD.MarCCD(filename)
            elif extension == "edf":
                self.theDiffractionData = ESRF.ESRF(filename)
            elif extension in ["tiff", "tif"]:
                self.theDiffractionData = Tiff.Tiff(filename)
            else:
                raise UnknownFiletypeException("%s is an unknown filetype" %
                                               filename)
Ejemplo n.º 25
0
 def getRotation(self):
     if self.rotation['val']==None or self.rotation['fixed']== None:
         raise UserInputException('Cannot get the rotation angle because it has not been set.')
    
     return copy.copy(self.rotation)
Ejemplo n.º 26
0
 def setPixelLength(self,val):
     if val<=0:
         raise UserInputException("Cannot set the pixel length because it must be greater then 0.")
     self.pixelLength = {'val':val}
Ejemplo n.º 27
0
    def getDistance(self):
        if self.distance['val']==None or self.distance['fixed']==None:
            raise UserInputException('Cannot get the distance because it has not been set.')

        return copy.copy(self.distance)
Ejemplo n.º 28
0
    def __init__(self, filename):

        # Whether or not to look for the overload pixels
        doOverflow = 1

        try:
            file = open(filename, 'rb')
            file.close()
        except IOError:
            raise UserInputException('%s does not exist' % filename)

        self.filename = filename
        file = open(filename, 'rb')

        header = {}

        for n in range(96):
            a = file.read(8)
            b = file.read(72)
            header[a] = b

        try:
            npixelb = int(header['NPIXELB:'].split()[0])
        except:
            raise Exception("Cannot read in the Bruker data file \
%s because the header field NPIXELB can not be parsed." % filename)

        if npixelb != 1 and npixelb != 2 and npixelb != 4:
            raise Exception("Cannot read in the Bruker data file \
%s because the The header field NPIXELB must equal 1, 2 or \
4." % npixelb)

        try:
            ncol = int(header['NCOLS  :'].split()[0])
        except:
            raise Exception("Cannot read in the Bruker data file \
%s because the header field NCOLS can not be parsed." % filename)

        try:
            nrow = int(header['NROWS  :'].split()[0])
        except:
            raise Exception("Cannot read in the Bruker data file \
%s because the header field NROWS can not be parsed." % filename)

        try:
            self.headerDistance = General.splitAverage(header['DISTANC:'])
        except:
            print "Cannot read the DISTANC header field from \
%s" % filename

        # sometimes, there are multiple wavelengths in this field
        # I am not sure what they are for, but we will just average
        # them and hope for the best.
        try:
            self.headerWavelength = General.splitAverage(header['WAVELEN:'])
        except:
            print "Cannot read the WAVELEN header field from \
%s" % filename

        try:
            self.headerCenterX = float(header['CENTER :'].split()[0])
            self.headerCenterY = float(header['CENTER :'].split()[1])
        except:
            print "Cannot read the center header fields from \
%s" % filename

        self.size = max(ncol, nrow)

        try:
            noverfl = int(header['NOVERFL:'].split()[0])
        except:
            raise Exception("Cannot read in the Bruker data file \
%s because the header field NOVERFL can not be parsed." % filename)

        datastring = file.read(ncol * nrow * npixelb)

        if npixelb == 1:
            temp = Numeric.fromstring(datastring, Numeric.UInt8)
            temp.shape = nrow, ncol

            if (noverfl != General.num_equals(temp, 255)):
                print "Warning, cannot read in the overflow \
pixels in Bruker file %s because the header field NOVERFL \
(%s) does not match the number of pixels in the data with value \
equal to exactly 255 (%s). All overloaded pixels must be set in \
the data to 255)." % (filename, noverfl, General.num_equals(temp, 255))

                doOverflow = 0

        elif npixelb == 2:
            temp = Numeric.fromstring(datastring, Numeric.UInt16)
            temp.shape = nrow, ncol

            if (noverfl != General.num_equals(temp, 65535)):
                print "Warning, cannot read in the overflow \
pixels in Bruker file %s because the header field NOVERFL \
(%s) does not match the number of pixels in the data with value \
equal to exactly 65535 (%s). All overloaded pixels must be set in \
the data to 65535)." % (filename, noverfl, General.num_equals(temp, 65535))

                doOverflow = 0

        elif npixelb == 4:
            data = Numeric.fromstring(datastring, Numeric.UInt32)
            data.shape = nrow, ncol

            # clip any data that is too big to fit into a signed int.
            mask1 = data <= 2147483647
            mask2 = data > 2147483647
            temp = data * mask1 + (pow(2, 31) - 1) * mask2

            # don't look for overflow pixels since they would be too
            # big to fit the data.
            if nooverfl != 0:
                print "No overflow pixels will be looked for in the \
Bruker file %s because the values would be too big to store in the \
data." % filename

            doOverflow = 0

        # convert to integers
        temp = temp.astype(Numeric.Int32)

        if noverfl != 0 and doOverflow:
            # loop over all overflow pixels
            for loop in range(noverfl):

                try:
                    intensity = int(file.read(9))
                    pixelOffset = int(file.read(7))

                except Exception, e:
                    raise Exception("Cannot read in all the \
overloaded pixels in the Bruker file %s because the overload \
pixels are not stored as ASCII at the bottom of the file as \
they should be." % filename)

                # make sure to use integer division
                row = int(pixelOffset) / int(ncol)
                column = pixelOffset % ncol

                if row >= nrow:
                    raise Exception("Cannot read in all the \
overload pixels in the Bruker file %s because one of the pixel \
offset numbers for an overloaded pixel would lead to putting the \
overloaded pixel outside of the data array." % filename)

                if npixelb == 1:
                    if temp[row][column] != 255:
                        raise Exception("Cannot read in all the \
overload pixels in the Bruker file %s because one of the pixel \
offset numbers for an overloaded pixel would lead to replacing \
a pixel whose intensity is not equal to 255 (as the replace \
pixels' intensity must be)." % filename)

                    temp[row][column] = intensity

                elif npixelb == 2:
                    if temp[row][column] != 65535:
                        raise Exception("Cannot read in all the \
overload pixels in the Bruker file %s because one of the pixel \
offset numbers for an overloaded pixel would lead to replacing \
a pixel whose intensity is not equal to 65535 (as the replace \
pixels' intensity must be)." % filename)

                    temp[row][column] = intensity
Ejemplo n.º 29
0
 def getPixelHeight(self):
     if self.pixelHeight['val']==None: 
         raise UserInputException('Cannot get the pixel height because it has not been set.')
     return copy.copy(self.pixelHeight)
Ejemplo n.º 30
0
 def getPixelLength(self):
     if self.pixelLength['val']==None: 
         raise UserInputException('Cannot get the pixel length because it has not been set.')
     return copy.copy(self.pixelLength)