Changeset 2001


Ignore:
Timestamp:
Oct 12, 2015 1:48:43 PM (6 years ago)
Author:
toby
Message:

add initial Image imports code

Location:
trunk
Files:
8 added
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r1997 r2001  
    242242        self.ImportSmallAngleReaderlist = []
    243243        self._init_Import_routines('sad',self.ImportSmallAngleReaderlist,'SmallAngle_Data')
     244        self.ImportImageReaderlist = []
     245        self._init_Import_routines('img',self.ImportImageReaderlist,'Images')
    244246        self.ImportMenuId = {}
    245247
     
    301303            for i in self.SeqRefine: i.Enable(False)
    302304
    303     def OnImportGeneric(self,reader,readerlist,label,multiple=False,usedRanIdList=[]):
     305    def PreviewFile(self,filename,fp):
     306        'confirm we have the right file'
     307        rdmsg = 'File '+str(filename)+' begins:\n\n'
     308        for i in range(3):
     309            rdmsg += fp.readline()
     310        rdmsg += '\n\nDo you want to read this file?'
     311        if not all([ord(c) < 128 and ord(c) != 0 for c in rdmsg]): # show only if ASCII
     312            rdmsg = 'File '+str(
     313                filename)+' is a binary file. Do you want to read this file?'
     314        # it would be better to use something that
     315        # would resize better, but this will do for now
     316        dlg = wx.MessageDialog(
     317            self, rdmsg,
     318            'Is this the file you want?',
     319            wx.YES_NO | wx.ICON_QUESTION,
     320            )
     321        dlg.SetSize((700,300)) # does not resize on Mac
     322        result = wx.ID_NO
     323        try:
     324            result = dlg.ShowModal()
     325        finally:
     326            dlg.Destroy()
     327        if result == wx.ID_NO: return True
     328        return False
     329   
     330    def OnImportGeneric(self,reader,readerlist,label,multiple=False,
     331                        usedRanIdList=[],Preview=True):
    304332        '''Used to import Phases, powder dataset or single
    305333        crystal datasets (structure factor tables) using reader objects
    306         subclassed from :class:`GSASIIIO.ImportPhase`, :class:`GSASIIIO.ImportStructFactor`
     334        subclassed from :class:`GSASIIIO.ImportPhase`,
     335        :class:`GSASIIIO.ImportStructFactor`
    307336        or :class:`GSASIIIO.ImportPowderData`. If a reader is specified, only
    308337        that will be attempted, but if no reader is specified, every one
     
    330359        :param list usedRanIdList: an optional list of random Ids that
    331360          have been used and should not be reused
     361
     362        :param bool Preview: indicates if a preview of the file should
     363          be shown. Default is True, but set to False for image files
     364          which are all binary.
    332365
    333366        :returns: a list of reader objects (rd_list) that were able
     
    414447            try:
    415448                fp = open(filename,'Ur')
    416                 if len(filelist) == 1:
    417                     # confirm we have the right file
    418                     rdmsg = 'File '+str(filename)+' begins:\n\n'
    419                     for i in range(3):
    420                         rdmsg += fp.readline()
    421                     rdmsg += '\n\nDo you want to read this file?'
    422                     if not all([ord(c) < 128 and ord(c) != 0 for c in rdmsg]): # show only if ASCII
    423                         rdmsg = 'File '+str(
    424                             filename)+' is a binary file. Do you want to read this file?'
    425                     result = wx.ID_NO
    426                     # it would be better to use something that
    427                     # would resize better, but this will do for now
    428                     dlg = wx.MessageDialog(
    429                         self, rdmsg,
    430                         'Is this the file you want?',
    431                         wx.YES_NO | wx.ICON_QUESTION,
    432                         )
    433                     dlg.SetSize((700,300)) # does not resize on Mac
    434                     try:
    435                         result = dlg.ShowModal()
    436                     finally:
    437                         dlg.Destroy()
    438                     if result == wx.ID_NO: return []
    439                            
     449                if len(filelist) == 1 and Preview:
     450                    if self.PreviewFile(filename,fp): return []
    440451                self.lastimport = filename # this is probably not what I want to do -- it saves only the
    441452                # last name in a series. See rd.readfilename for a better name.
     
    554565        finally:
    555566            dlg.Destroy()
    556         return filelist
    557            
     567        return filelist           
     568       
    558569    def OnImportPhase(self,event):
    559570        '''Called in response to an Import/Phase/... menu item
     
    719730        return # success
    720731       
     732    def _Add_ImportMenu_Image(self,parent):
     733        '''configure the Import Image menus accord to the readers found in _init_Imports
     734        '''
     735        submenu = wx.Menu()
     736        item = parent.AppendMenu(wx.ID_ANY, 'Image',
     737            submenu, help='Import image file')
     738        for reader in self.ImportImageReaderlist:
     739            item = submenu.Append(wx.ID_ANY,help=reader.longFormatName,
     740                kind=wx.ITEM_NORMAL,text='from '+reader.formatName+' file')
     741            self.ImportMenuId[item.GetId()] = reader
     742            self.Bind(wx.EVT_MENU, self.OnImportImage, id=item.GetId())
     743        item = submenu.Append(wx.ID_ANY,
     744                              help='Import image data, use file to try to determine format',
     745                              kind=wx.ITEM_NORMAL,
     746                              text='guess format from file')
     747        self.Bind(wx.EVT_MENU, self.OnImportImage, id=item.GetId())
     748       
     749    def OnImportImage(self,event):
     750        '''Called in response to an Import/Image/... menu item
     751        to read an image from a file. Like all the other imports,
     752        dict self.ImportMenuId is used to look up the specific
     753        reader item associated with the menu item, which will be
     754        None for the last menu item, which is the "guess" option
     755        where all appropriate formats will be tried.
     756
     757        A reader object is filled each time an image is read.
     758        '''
     759        # look up which format was requested
     760        reqrdr = self.ImportMenuId.get(event.GetId())
     761        rdlist = self.OnImportGeneric(reqrdr,
     762                                  self.ImportImageReaderlist,
     763                                  'image',multiple=True,Preview=False)
     764        first = True
     765        for rd in rdlist:
     766            if first:
     767                first = False
     768                self.CheckNotebook()
     769            G2IO.LoadImage(rd.readfilename,self,rd.Comments,rd.Data,rd.Npix,rd.Image)
     770        self.PatternTree.SelectItem(G2gd.GetPatternTreeItemId(self,self.Image,'Image Controls'))             #show last image to have beeen read
     771        # replace G2IO.GetImageData with something using imports
     772        # look over G2IO.ReadLoadImage
     773                   
    721774    def _Add_ImportMenu_Sfact(self,parent):
    722775        '''configure the Import Structure Factor menus accord to the readers found in _init_Imports
     
    20212074        Import = wx.Menu(title='')       
    20222075        menubar.Append(menu=Import, title='Import')
     2076        if GSASIIpath.GetConfigValue('debug'):
     2077            self._Add_ImportMenu_Image(Import)
    20232078        self._Add_ImportMenu_Phase(Import)
    20242079        self._Add_ImportMenu_powder(Import)
  • trunk/GSASIIIO.py

    r1997 r2001  
    130130
    131131def CheckImageFile(G2frame,imagefile):
    132     '''Get an new image file name if the specified one does not
    133     exist
     132    '''Try to locate an image file if the project and image have been moved
     133    together. If the image file cannot be found, request the location from
     134    the user.
    134135
    135136    :param wx.Frame G2frame: main GSAS-II Frame and data object
    136 
    137137    :param str imagefile: name of image file
    138 
    139138    :returns: imagefile, if it exists, or the name of a file
    140139      that does exist or False if the user presses Cancel
     
    270269    '''Read a GSAS-II image file and load it into the data tree
    271270    '''
    272     # get a list of existing Image entries
    273     ImgNames = []
    274     if G2frame.PatternTree.GetCount():
    275         item, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
    276         while item:
    277             name = G2frame.PatternTree.GetItemText(item)
    278             if name.startswith('IMG'): ImgNames.append(name)       
    279             item, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
    280271    # if a zip file, open and extract
    281272    if os.path.splitext(imagefile)[1].lower() == '.zip':
     
    285276    Comments,Data,Npix,Image = GetImageData(G2frame,imagefile)
    286277    if Comments:
    287         TreeName = G2obj.MakeUniqueLabel('IMG '+os.path.basename(imagefile),ImgNames)
    288         print 'b=','IMG '+os.path.basename(imagefile)
    289         print 'a=',TreeName
    290         Id = G2frame.PatternTree.AppendItem(parent=G2frame.root,text=TreeName)
    291         G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Comments'),Comments)
    292         Imax = np.amax(Image)
    293         Imin = max(0.0,np.amin(Image))          #force positive
    294         if G2frame.imageDefault:
    295             Data = copy.copy(G2frame.imageDefault)
    296             Data['showLines'] = True
    297             Data['ring'] = []
    298             Data['rings'] = []
    299             Data['cutoff'] = 10
    300             Data['pixLimit'] = 20
    301             Data['edgemin'] = 100000000
    302             Data['calibdmin'] = 0.5
    303             Data['calibskip'] = 0
    304             Data['ellipses'] = []
    305             Data['calibrant'] = ''
    306             Data['GonioAngles'] = [0.,0.,0.]
    307             Data['DetDepthRef'] = False
    308         else:
    309             Data['type'] = 'PWDR'
    310             Data['color'] = 'Paired'
    311             Data['tilt'] = 0.0
    312             Data['rotation'] = 0.0
    313             Data['showLines'] = False
    314             Data['ring'] = []
    315             Data['rings'] = []
    316             Data['cutoff'] = 10
    317             Data['pixLimit'] = 20
    318             Data['calibdmin'] = 0.5
    319             Data['calibskip'] = 0
    320             Data['edgemin'] = 100000000
    321             Data['ellipses'] = []
    322             Data['GonioAngles'] = [0.,0.,0.]
    323             Data['DetDepth'] = 0.
    324             Data['DetDepthRef'] = False
    325             Data['calibrant'] = ''
    326             Data['IOtth'] = [2.0,5.0]
    327             Data['LRazimuth'] = [135,225]
    328             Data['azmthOff'] = 0.0
    329             Data['outChannels'] = 2500
    330             Data['outAzimuths'] = 1
    331             Data['centerAzm'] = False
    332             Data['fullIntegrate'] = False
    333             Data['setRings'] = False
    334             Data['background image'] = ['',-1.0]                           
    335             Data['dark image'] = ['',-1.0]
    336             Data['Flat Bkg'] = 0.0
    337         Data['setDefault'] = False
    338         Data['range'] = [(Imin,Imax),[Imin,Imax]]
    339         G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Image Controls'),Data)
    340         Masks = {'Points':[],'Rings':[],'Arcs':[],'Polygons':[],'Frames':[],'Thresholds':[(Imin,Imax),[Imin,Imax]]}
    341         G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Masks'),Masks)
    342         G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Stress/Strain'),
    343             {'Type':'True','d-zero':[],'Sample phi':0.0,'Sample z':0.0,'Sample load':0.0})
    344         G2frame.PatternTree.SetItemPyData(Id,[Npix,imagefile])
    345         G2frame.PickId = Id
    346         G2frame.PickIdText = G2frame.GetTreeItemsList(G2frame.PickId)
    347         G2frame.Image = Id
     278        LoadImage(imagefile,G2frame,Comments,Data,Npix,Image)
     279   
     280def LoadImage(imagefile,G2frame,Comments,Data,Npix,Image):
     281    '''Load an image into the tree
     282    '''
     283   
     284    ImgNames = []
     285    if G2frame.PatternTree.GetCount(): # get a list of existing Image entries
     286        item, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
     287        while item:
     288            name = G2frame.PatternTree.GetItemText(item)
     289            if name.startswith('IMG'): ImgNames.append(name)       
     290            item, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
     291    TreeName = G2obj.MakeUniqueLabel('IMG '+os.path.basename(imagefile),ImgNames)
     292    Id = G2frame.PatternTree.AppendItem(parent=G2frame.root,text=TreeName)
     293    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Comments'),Comments)
     294    Imax = np.amax(Image)
     295    Imin = max(0.0,np.amin(Image))          #force positive
     296    if G2frame.imageDefault:
     297        Data = copy.copy(G2frame.imageDefault)
     298        Data['showLines'] = True
     299        Data['ring'] = []
     300        Data['rings'] = []
     301        Data['cutoff'] = 10
     302        Data['pixLimit'] = 20
     303        Data['edgemin'] = 100000000
     304        Data['calibdmin'] = 0.5
     305        Data['calibskip'] = 0
     306        Data['ellipses'] = []
     307        Data['calibrant'] = ''
     308        Data['GonioAngles'] = [0.,0.,0.]
     309        Data['DetDepthRef'] = False
     310    else:
     311        Data['type'] = 'PWDR'
     312        Data['color'] = 'Paired'
     313        Data['tilt'] = 0.0
     314        Data['rotation'] = 0.0
     315        Data['showLines'] = False
     316        Data['ring'] = []
     317        Data['rings'] = []
     318        Data['cutoff'] = 10
     319        Data['pixLimit'] = 20
     320        Data['calibdmin'] = 0.5
     321        Data['calibskip'] = 0
     322        Data['edgemin'] = 100000000
     323        Data['ellipses'] = []
     324        Data['GonioAngles'] = [0.,0.,0.]
     325        Data['DetDepth'] = 0.
     326        Data['DetDepthRef'] = False
     327        Data['calibrant'] = ''
     328        Data['IOtth'] = [2.0,5.0]
     329        Data['LRazimuth'] = [135,225]
     330        Data['azmthOff'] = 0.0
     331        Data['outChannels'] = 2500
     332        Data['outAzimuths'] = 1
     333        Data['centerAzm'] = False
     334        Data['fullIntegrate'] = False
     335        Data['setRings'] = False
     336        Data['background image'] = ['',-1.0]                           
     337        Data['dark image'] = ['',-1.0]
     338        Data['Flat Bkg'] = 0.0
     339    Data['setDefault'] = False
     340    Data['range'] = [(Imin,Imax),[Imin,Imax]]
     341    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Image Controls'),Data)
     342    Masks = {'Points':[],'Rings':[],'Arcs':[],'Polygons':[],'Frames':[],'Thresholds':[(Imin,Imax),[Imin,Imax]]}
     343    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Masks'),Masks)
     344    G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Stress/Strain'),
     345        {'Type':'True','d-zero':[],'Sample phi':0.0,'Sample z':0.0,'Sample load':0.0})
     346    G2frame.PatternTree.SetItemPyData(Id,[Npix,imagefile])
     347    G2frame.PickId = Id
     348    G2frame.PickIdText = G2frame.GetTreeItemsList(G2frame.PickId)
     349    G2frame.Image = Id
    348350   
    349351def GetImageData(G2frame,imagefile,imageOnly=False):
     
    19521954        self.numbanks = 1
    19531955        self.instdict = {} # place items here that will be transferred to the instrument parameters
     1956
     1957######################################################################
     1958class ImportImage(ImportBaseclass):
     1959    '''Defines a base class for the reading of images
     1960
     1961    Structure factors are read with a call to :meth:`GSASII.GSASII.OnImportImage`
     1962    which in turn calls :meth:`GSASII.GSASII.OnImportGeneric`, which calls
     1963    methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
     1964    :meth:`Reader`.
     1965
     1966    See :ref:`Writing a Import Routine<Import_Routines>`
     1967    for an explanation on how to use import classes in general. The specifics
     1968    for reading an image requires that the ``Reader()`` routine in the import
     1969    class need to do only a few things:...
     1970   
     1971    (should load :attr:`RefDict` item ``'RefList'`` with the reflection list,
     1972    (and set :attr:`Parameters` with the instrument parameters
     1973    (initialized with :meth:`InitParameters` and set with :meth:`UpdateParameters`).
     1974    '''
     1975    def __init__(self,formatName,longFormatName=None,extensionlist=[],
     1976        strictExtension=False,):
     1977        ImportBaseclass.__init__(self,formatName,longFormatName,
     1978            extensionlist,strictExtension)
     1979        self.InitParameters()
     1980       
     1981    def ReInitialize(self):
     1982        'Reinitialize the Reader to initial settings -- not used at present'
     1983        ImportBaseclass.ReInitialize(self)
     1984        self.InitParameters()
     1985       
     1986    def InitParameters(self):
     1987        'initialize the instrument parameters structure'
     1988        self.Comments = ['No comments']
     1989        self.Data = {}
     1990        self.Npix = 0
     1991        self.Image = None
     1992
    19541993######################################################################
    19551994class ExportBaseclass(object):
Note: See TracChangeset for help on using the changeset viewer.