Changeset 2003


Ignore:
Timestamp:
Oct 12, 2015 5:31:16 PM (6 years ago)
Author:
toby
Message:

Make Transpose a config opt; new routine to read images with import routine (G2IO.ReadImageData?) -- used in Debug mode; In debug mode, import exceptions not caught.

Location:
trunk
Files:
8 edited
3 moved

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r2002 r2003  
    330330    def OnImportGeneric(self,reader,readerlist,label,multiple=False,
    331331                        usedRanIdList=[],Preview=True):
    332         '''Used to import Phases, powder dataset or single
    333         crystal datasets (structure factor tables) using reader objects
     332        '''Used to import Phases or datasets using reader objects
    334333        subclassed from :class:`GSASIIIO.ImportPhase`,
    335         :class:`GSASIIIO.ImportStructFactor`
    336         or :class:`GSASIIIO.ImportPowderData`. If a reader is specified, only
    337         that will be attempted, but if no reader is specified, every one
    338         that is potentially compatible (by file extension) will
    339         be tried on the selected file(s).
     334        :class:`GSASIIIO.ImportStructFactor`,
     335        :class:`GSASIIIO.ImportPowderData`,
     336        :class:`GSASIIIO.ImportSmallAngleData` or
     337        :class:`GSASIIIO.ImportImage`.
     338        If a specific reader is specified, only that method will be called,
     339        but if no reader is specified, every one that is potentially
     340        compatible (by file extension) will be tried on the file(s)
     341        selected in the Open File dialog.
    340342
    341343        :param readerobject reader: This will be a reference to
     
    430432                if extractedfile != filename:
    431433                    filename,self.zipfile = extractedfile,filename # now use the file that was created
    432             # set what formats are compatible with this file
     434            # determine which formats are compatible with this file
    433435            primaryReaders = []
    434436            secondaryReaders = []
     
    439441                elif flag:
    440442                    primaryReaders.append(rd)
    441             if len(secondaryReaders) + len(primaryReaders) == 0:
     443            if len(secondaryReaders) + len(primaryReaders) == 0 and reader:
     444                self.ErrorDialog('Not supported','The selected reader cannot read file '+filename)
     445                return []
     446            elif len(secondaryReaders) + len(primaryReaders) == 0:
    442447                self.ErrorDialog('No Format','No matching format for file '+filename)
    443448                return []
     
    445450            fp = None
    446451            msg = ''
    447             try:
    448                 fp = open(filename,'Ur')
    449                 if len(filelist) == 1 and Preview:
    450                     if self.PreviewFile(filename,fp): return []
    451                 self.lastimport = filename # this is probably not what I want to do -- it saves only the
    452                 # last name in a series. See rd.readfilename for a better name.
    453                
    454                 # try the file first with Readers that specify the
    455                 # file's extension and later with ones that merely allow it
    456                 errorReport = ''
    457                 for rd in primaryReaders+secondaryReaders:
    458                     rd.ReInitialize() # purge anything from a previous read
     452            fp = open(filename,'Ur')
     453            if len(filelist) == 1 and Preview:
     454                if self.PreviewFile(filename,fp): return []
     455            self.lastimport = filename # this is probably not what I want to do -- it saves only the
     456            # last name in a series. See rd.readfilename for a better name.
     457
     458            # try the file first with Readers that specify the
     459            # file's extension and later with ones that merely allow it
     460            errorReport = ''
     461            for rd in primaryReaders+secondaryReaders:
     462                rd.ReInitialize() # purge anything from a previous read
     463                fp.seek(0)  # rewind
     464                rd.errors = "" # clear out any old errors
     465                if not rd.ContentsValidator(fp): # rejected on cursory check
     466                    errorReport += "\n  "+rd.formatName + ' validator error'
     467                    if rd.errors:
     468                        errorReport += ': '+rd.errors
     469                    continue
     470                repeat = True
     471                rdbuffer = {} # create temporary storage for file reader
     472                block = 0
     473                while repeat: # loop if the reader asks for another pass on the file
     474                    block += 1
     475                    repeat = False
    459476                    fp.seek(0)  # rewind
    460                     rd.errors = "" # clear out any old errors
    461                     if not rd.ContentsValidator(fp): # rejected on cursory check
    462                         errorReport += "\n  "+rd.formatName + ' validator error'
    463                         if rd.errors:
    464                             errorReport += ': '+rd.errors
    465                         continue
    466                     repeat = True
    467                     rdbuffer = {} # create temporary storage for file reader
    468                     block = 0
    469                     while repeat: # loop if the reader asks for another pass on the file
    470                         block += 1
    471                         repeat = False
    472                         fp.seek(0)  # rewind
    473                         rd.objname = os.path.basename(filename)
    474                         flag = False
     477                    rd.objname = os.path.basename(filename)
     478                    flag = False
     479                    if GSASIIpath.GetConfigValue('debug'):
     480                        flag = rd.Reader(filename,fp,self,
     481                                         buffer=rdbuffer,
     482                                         blocknum=block,
     483                                         usedRanIdList=usedRanIdList,
     484                                         )
     485                    else:
    475486                        try:
    476487                            flag = rd.Reader(filename,fp,self,
     
    485496                            rd.errors += "\n  Unhandled read exception: "+str(detail)
    486497                            rd.errors += "\n  Traceback info:\n"+str(traceback.format_exc())
    487                         if flag: # this read succeeded
    488                             rd.readfilename = filename
    489                             rd_list.append(copy.deepcopy(rd)) # save the result before it is written over
    490                             if rd.repeat:
    491                                 repeat = True
    492                             continue
    493                         errorReport += '\n'+rd.formatName + ' read error'
    494                         if rd.errors:
    495                             errorReport += ': '+rd.errors
    496                     if rd_list: # read succeeded, was there a warning or any errors?
    497                         if rd.warnings:
    498                             self.ErrorDialog('Read Warning','The '+ rd.formatName+
    499                                              ' reader reported a warning message:\n\n'+
    500                                              rd.warnings)
    501                         break # success in reading, try no further
     498                    if flag: # this read succeeded
     499                        rd.readfilename = filename
     500                        rd_list.append(copy.deepcopy(rd)) # save the result before it is written over
     501                        if rd.repeat:
     502                            repeat = True
     503                        continue
     504                    errorReport += '\n'+rd.formatName + ' read error'
     505                    if rd.errors:
     506                        errorReport += ': '+rd.errors
     507                if rd_list: # read succeeded, was there a warning or any errors?
     508                    if rd.warnings:
     509                        self.ErrorDialog('Read Warning','The '+ rd.formatName+
     510                                         ' reader reported a warning message:\n\n'+
     511                                         rd.warnings)
     512                    break # success in reading, try no further
     513            else:
     514                if singlereader:
     515                    self.ErrorDialog('Read Error','The '+ rd.formatName+
     516                                     ' reader was not able to read file '+filename+msg+
     517                                     '\n\nError message(s):\n'+errorReport
     518                                     )
    502519                else:
    503                     if singlereader:
    504                         self.ErrorDialog('Read Error','The '+ rd.formatName+
    505                                          ' reader was not able to read file '+filename+msg+
    506                                          '\n\nError message(s):\n'+errorReport
    507                                          )
    508                     else:
    509                         self.ErrorDialog('Read Error','No reader was able to read file '+filename+msg+
    510                                          '\n\nError messages:\n'+errorReport
    511                                          )
    512             except:
    513                 import traceback
    514                 print traceback.format_exc()
    515                 self.ErrorDialog('Open Error','Unexpected error trying to open or read file '+filename)
     520                    self.ErrorDialog('Read Error','No reader was able to read file '+filename+msg+
     521                                     '\n\nError messages:\n'+errorReport
     522                                     )
    516523            if fp: fp.close()
    517524        return rd_list
     
    20752082        Import = wx.Menu(title='')       
    20762083        menubar.Append(menu=Import, title='Import')
    2077         if GSASIIpath.GetConfigValue('debug'):
    2078             self._Add_ImportMenu_Image(Import)
     2084        self._Add_ImportMenu_Image(Import)
    20792085        self._Add_ImportMenu_Phase(Import)
    20802086        self._Add_ImportMenu_powder(Import)
  • trunk/GSASIIIO.py

    r2001 r2003  
    4646DEBUG = False       #=True for various prints
    4747TRANSP = False      #=true to transpose images for testing
     48if GSASIIpath.GetConfigValue('Transpose'): TRANSP = True
    4849npsind = lambda x: np.sin(x*np.pi/180.)
    4950
     
    349350    G2frame.Image = Id
    350351   
     352def ReadImageData(G2frame,imagefile,imageOnly=False):
     353    '''Read a single image with an image importer. replacement for GetImageData
     354
     355    :param wx.Frame G2frame: main GSAS-II Frame and data object.
     356    :param str imagefile: name of image file
     357    :param bool imageOnly: If True return only the image,
     358      otherwise  (default) return more (see below)
     359
     360    :returns: an image as a numpy array or a list of four items:
     361      Comments, Data, Npix and the Image, as selected by imageOnly
     362
     363    '''
     364    # determine which formats are compatible with this file
     365    print 'Debug: using ReadImageData'
     366    primaryReaders = []
     367    secondaryReaders = []
     368    for rd in G2frame.ImportImageReaderlist:
     369        flag = rd.ExtensionValidator(imagefile)
     370        if flag is None:
     371            secondaryReaders.append(rd)
     372        elif flag:
     373            primaryReaders.append(rd)
     374    if len(secondaryReaders) + len(primaryReaders) == 0:
     375        print('Error: No matching format for file '+filename)
     376        raise Exception('No image read')
     377    fp = None
     378    errorReport = ''
     379    fp = open(imagefile,'Ur')
     380    for rd in primaryReaders+secondaryReaders:
     381        rd.ReInitialize() # purge anything from a previous read
     382        fp.seek(0)  # rewind
     383        rd.errors = "" # clear out any old errors
     384        if not rd.ContentsValidator(fp): # rejected on cursory check
     385            errorReport += "\n  "+rd.formatName + ' validator error'
     386            if rd.errors:
     387                errorReport += ': '+rd.errors
     388                continue
     389        rdbuffer = {} # create temporary storage for file reader
     390        if GSASIIpath.GetConfigValue('debug'):
     391            flag = rd.Reader(imagefile,fp,G2frame)
     392        else:
     393            flag = False
     394            try:
     395                flag = rd.Reader(imagefile,fp,G2frame)
     396            except rd.ImportException as detail:
     397                rd.errors += "\n  Read exception: "+str(detail)
     398            except Exception as detail:
     399                import traceback
     400                rd.errors += "\n  Unhandled read exception: "+str(detail)
     401                rd.errors += "\n  Traceback info:\n"+str(traceback.format_exc())
     402        if flag: # this read succeeded
     403            if rd.Image is None:
     404                raise Exception('No image read. Strange!')
     405            if GSASIIpath.GetConfigValue('Transpose'):
     406                rd.Image = rd.Image.T
     407            #rd.readfilename = imagefile
     408            if imageOnly:
     409                return rd.Image.T
     410            else:
     411                return rd.Comments,rd.Data,rd.Npix,rd.Image
     412    else:
     413        print('Error reading file '+filename)
     414        print('Error messages(s)\n'+errorReport)
     415        raise Exception('No image read')
     416   
    351417def GetImageData(G2frame,imagefile,imageOnly=False):
    352418    '''Read an image with the file reader keyed by the
     
    364430
    365431    '''
     432    if GSASIIpath.GetConfigValue('debug'):  # test out using replacement routine
     433        return ReadImageData(G2frame,imagefile,imageOnly)
     434   
    366435    ext = ospath.splitext(imagefile)[1]
    367436    Comments = []
     
    522591        return head,data,Npix,image
    523592   
    524        
    525593def GetGEsumData(filename,imageOnly=False):
    526594    'Read SUM file as produced at 1-ID from G.E. images'
  • trunk/config_example.py

    r1971 r2003  
    4343'''
    4444
     45Transpose = False
     46'Set to True to cause images to be Transposed when read (for code development)'
     47
    4548Enable_logging = False
    4649'Set to True to enable use of command logging (under development.)'
  • trunk/imports/G2img_1TIF.py

    r2001 r2003  
    5050        '''
    5151       
    52         filepointer.close() # close the file, since it will be reopened below.
    53         filepointer = None
    5452        self.Comments,self.Data,self.Npix,self.Image = G2IO.GetTifData(filename)
    5553        if self.Npix == 0:
  • trunk/imports/G2img_ADSC.py

    r2001 r2003  
    3737        '''Read using Bob's routine
    3838        '''
    39         filepointer.close() # close the file, since it will be reopened below.
    40         filepointer = None
    4139        self.Comments,self.Data,self.Npix,self.Image = G2IO.GetImgData(filename)
    4240        Image[0][0] = 0
  • trunk/imports/G2img_CheMin.py

    r2001 r2003  
    4040        '''
    4141        import scipy.misc
    42         filepointer.close() # close the file, since it will be reopened below.
    43         filepointer = None
    4442        self.Image = scipy.misc.imread(filename,flatten=True)
    4543        self.Npix = self.Image.size
  • trunk/imports/G2img_EDF.py

    r2001 r2003  
    3838        '''Read using Bob's routine
    3939        '''
    40         filepointer.close() # close the file, since it will be reopened below.
    41         filepointer = None
    4240        self.Comments,self.Data,self.Npix,self.Image = G2IO.GetEdfData(filename)
    4341        if self.Npix == 0 or not self.Comments:
  • trunk/imports/G2img_GE.py

    r2001 r2003  
    2323    def __init__(self):
    2424        super(self.__class__,self).__init__( # fancy way to self-reference
    25             extensionlist=('.sum','.cor','.avg','.ge','.ge1','ge2','ge3','.ge4'),
     25            extensionlist=('.sum','.cor','.avg','.ge','.ge1','.ge2','.ge3','.ge4'),
    2626            strictExtension=True,
    2727            formatName = 'GE image',
     
    3737        '''Read using Bob's routine
    3838        '''
    39         filepointer.close() # close the file, since it will be reopened below.
    40         filepointer = None
    41         self.Comments,self.Data,self.Npix,self.Image = G2IO.GetGEsum(filename)
     39        self.Comments,self.Data,self.Npix,self.Image = G2IO.GetGEsumData(filename)
    4240        if self.Npix == 0 or not self.Comments:
    4341            return False
  • trunk/imports/G2img_MAR.py

    r2001 r2003  
    3737        '''Read using Bob's routine
    3838        '''
    39         filepointer.close() # close the file, since it will be reopened below.
    40         filepointer = None
    4139        self.Comments,self.Data,self.Npix,self.Image = G2IO.GetMAR345Data(filename)
    4240        if self.Npix == 0 or not self.Comments:
  • trunk/imports/G2img_Rigaku.py

    r2001 r2003  
    4242        '''Read using Bob's routine
    4343        '''
    44         filepointer.close() # close the file, since it will be reopened below.
    45         filepointer = None
     44
    4645        self.Comments,self.Data,self.Npix,self.Image = G2IO.GetRigaku(filename)
    4746        if self.Npix == 0 or not self.Comments:
  • trunk/imports/G2img_SumG2.py

    r2001 r2003  
    2626            extensionlist=('.G2img',),
    2727            strictExtension=True,
    28             formatName = 'G2 summed image',
     28            formatName = 'Summed GSAS-II image',
    2929            longFormatName = 'Pickled image from GSAS-II "Sum image data" command'
    3030            )
     
    3939        '''
    4040        import scipy.misc
    41         filepointer.close() # close the file, since it will be reopened below.
    42         filepointer = None
    4341        Fp = open(filename,'rb')
    4442        self.Comments,self.Data,self.Npix,self.image = cPickle.load(Fp)
Note: See TracChangeset for help on using the changeset viewer.