Changeset 580


Ignore:
Timestamp:
Apr 30, 2012 10:57:52 AM (11 years ago)
Author:
toby
Message:

finish import structure factor; refactor import classes

Location:
trunk
Files:
2 added
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/G2importphase_CIF.py

    r547 r580  
    2424            )
    2525    def ContentsValidator(self, filepointer):
    26         filepointer.seek(0) # rewind the file pointer
    2726        for i,line in enumerate(filepointer):
    2827            if i >= 1000: break
     
    7473            ciffile = 'file:'+urllib.pathname2url(filename)
    7574            cf = cif.ReadCif(ciffile)
     75            self.DoneBusy()
    7676            #print cf
    7777            # scan blocks for structural info
     
    9494                    choice[-1] += blknm + ': '
    9595                    for i in phasenamefields: # get a name for the phase
    96                         name = cf[blknm].get(i).strip()
     96                        name = cf[blknm].get(i)
    9797                        if name is None or name == '?' or name == '.':
    9898                            continue
     
    208208            print traceback.format_exc()
    209209            returnstat = False
    210         finally:
    211             self.DoneBusy()
    212210        return returnstat
  • trunk/G2importphase_GPX.py

    r574 r580  
    2020            )
    2121    def ContentsValidator(self, filepointer):
    22         filepointer.seek(0) # rewind the file pointer
    2322        # if the 1st section can't be read as a cPickle file, it can't be!
    2423        try:
     
    4746            self.Phase = G2str.GetAllPhaseData(filename,phasenames[selblk])
    4847            return True
    49         except:
    50             return False
    51 
     48        except Exception as detail:
     49            print self.formatName+' error:',detail # for testing
     50            print sys.exc_info()[0] # for testing
     51            import traceback
     52            print traceback.format_exc()
  • trunk/GSASII.py

    r577 r580  
    313313            # files extension and later with ones that allow it
    314314            for rd in primaryReaders+secondaryReaders:
     315                fp.seek(0)  # rewind
    315316                if not rd.ContentsValidator(fp):
    316317                    continue # rejected on cursory check
    317                 #flag = rd.Reader(file,fp,self)
    318318                try:
     319                    fp.seek(0)  # rewind
    319320                    flag = rd.Reader(file,fp,self)
    320321                except:
     
    330331                    'Edit phase name', rd.Phase['General']['Name'],
    331332                    style=wx.OK)
    332                 #dlg.SetValue("Python is the best!")
    333333                dlg.CenterOnParent()
    334334                if dlg.ShowModal() == wx.ID_OK:
     
    336336                dlg.Destroy()
    337337                PhaseName = rd.Phase['General']['Name']
     338                print 'Read phase '+str(PhaseName)+' from file '+str(file)
     339                self.CheckNotebook()
    338340                if not G2gd.GetPatternTreeItemId(self,self.root,'Phases'):
    339341                    sub = self.PatternTree.AppendItem(parent=self.root,text='Phases')
     
    366368        filelist = []
    367369        for path in pathlist:
     370            #print path
    368371            for filename in glob.iglob(os.path.join(path, "G2importsfact*.py")):
    369372                filelist.append(filename)   
     
    476479            # files extension and later with ones that allow it
    477480            for rd in primaryReaders+secondaryReaders:
     481                fp.seek(0)  # rewind
    478482                if not rd.ContentsValidator(fp):
    479483                    continue # rejected on cursory check
    480                 #flag = rd.Reader(file,fp,self)
    481484                try:
     485                    fp.seek(0)  # rewind
    482486                    flag = rd.Reader(file,fp,self)
    483487                except:
     
    489493                    continue
    490494                if not flag: continue
    491 #                dlg = wx.TextEntryDialog( # allow editing of Structure Factor name
    492 #                    self, 'Enter the name for the new Structure Factor',
    493 #                    'Edit Structure Factor name', rd.Phase['General']['Name'],
    494  #                   style=wx.OK)
     495                HistName = ospath.basename(file)
     496                dlg = wx.TextEntryDialog( # allow editing of Structure Factor name
     497                    self, 'Enter the name for the new Structure Factor',
     498                    'Edit Structure Factor name', HistName,
     499                    style=wx.OK)
    495500                dlg.CenterOnParent()
    496 #                if dlg.ShowModal() == wx.ID_OK:
    497 #                    rd.Phase['General']['Name'] = dlg.GetValue()
    498 #                dlg.Destroy()
    499 #                PhaseName = rd.Phase['General']['Name']
    500 #                if not G2gd.GetPatternTreeItemId(self,self.root,'Phases'):
    501 #                    sub = self.PatternTree.AppendItem(parent=self.root,text='Phases')
    502 #                else:
    503 #                    sub = G2gd.GetPatternTreeItemId(self,self.root,'Phases')
    504 #                psub = self.PatternTree.AppendItem(parent=sub,text=PhaseName)
    505 #                self.PatternTree.SetItemPyData(psub,rd.Phase)
    506 #                self.PatternTree.Expand(self.root) # make sure phases are seen
    507 #                self.PatternTree.Expand(sub)
    508 #                self.PatternTree.Expand(psub)
     501                if dlg.ShowModal() == wx.ID_OK:
     502                    HistName = dlg.GetValue()
     503                dlg.Destroy()
     504                print 'Read structure factor table '+str(HistName)+' from file '+str(file)
     505                self.CheckNotebook()
     506                Id = self.PatternTree.AppendItem(parent=self.root,
     507                                                 text='HKLF '+HistName)
     508                self.PatternTree.SetItemPyData(Id,rd.RefList)
     509                Sub = self.PatternTree.AppendItem(Id,text='Instrument Parameters')
     510                self.PatternTree.SetItemPyData(Sub,rd.Parameters)
     511                self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(
     512                    Id,text='HKL Plot Controls'),
     513                                               rd.Controls)
     514                self.PatternTree.SelectItem(Id)
     515                self.PatternTree.Expand(Id)
     516                self.Sngl = Id
    509517                return # success
    510518        except:
  • trunk/GSASIIIO.py

    r577 r580  
    12651265######################################################################
    12661266E,SGData = G2spc.SpcGroup('P 1') # data structure for default space group
    1267 class ImportPhase(object):
    1268     '''Defines a base class for the reading of files with coordinates
     1267class ImportBaseclass(object):
     1268    '''Defines a base class for the importing of data files (diffraction
     1269    data, coordinates,...
    12691270    '''
    12701271    def __init__(self,
     
    12871288        # the extension matches one in the extensionlist
    12881289        self.strictExtension = strictExtension
    1289         # define a default Phase structure
    1290         self.Phase = SetNewPhase(Name='new phase',SGData=SGData)
    12911290        self.warnings = ''
    12921291        self.errors = ''
    12931292        #print 'created',self.__class__
    12941293
    1295     def PhaseSelector(self, ChoiceList, ParentFrame=None,
    1296                       title='Select a phase', size=None):
    1297         ''' Provide a wx dialog to select a phase if the file contains more
    1298         than one
     1294    def BlockSelector(self, ChoiceList, ParentFrame=None,
     1295                      title='Select a block',
     1296                      size=None, header='Block Selector'):
     1297        ''' Provide a wx dialog to select a block if the file contains more
     1298        than one set of data and one must be selected
    12991299        '''
    13001300        dlg = wx.SingleChoiceDialog(
    13011301            ParentFrame,
    1302             title,
    1303             'Phase Selection',
     1302            title, header,
    13041303            ChoiceList,
    13051304            )
     
    13511350        return True
    13521351
     1352class ImportPhase(ImportBaseclass):
     1353    '''Defines a base class for the reading of files with coordinates
     1354    '''
     1355    def __init__(self,
     1356                 formatName,
     1357                 longFormatName=None,
     1358                 extensionlist=[],
     1359                 strictExtension=False,
     1360                 ):
     1361        # call parent __init__
     1362        ImportBaseclass.__init__(self,formatName,
     1363                                            longFormatName,
     1364                                            extensionlist,
     1365                                            strictExtension)
     1366        # define a default Phase structure
     1367        self.Phase = SetNewPhase(Name='new phase',SGData=SGData)
     1368
     1369    def PhaseSelector(self, ChoiceList, ParentFrame=None,
     1370                      title='Select a phase', size=None,
     1371                      header='Phase Selector'):
     1372        ''' Provide a wx dialog to select a phase if the file contains more
     1373        than one phase
     1374        '''
     1375        self.BlockSelector(ChoiceList, ParentFrame, title, size, header)
     1376
    13531377######################################################################
    1354 class ImportStructFactor(object):
     1378class ImportStructFactor(ImportBaseclass):
    13551379    '''Defines a base class for the reading of files with tables
    13561380    of structure factors
     
    13621386                 strictExtension=False,
    13631387                 ):
    1364         self.formatName = formatName # short string naming file type
    1365         if longFormatName: # longer string naming file type
    1366             self.longFormatName = longFormatName
    1367         else:
    1368             self.longFormatName = formatName
    1369         # define extensions that are allowed for the file type
    1370         # for windows, remove any extensions that are duplicate, as case is ignored
    1371         if sys.platform == 'windows' and extensionlist:
    1372             extensionlist = list(set([s.lower() for s in extensionlist]))
    1373         self.extensionlist = extensionlist
    1374         # If strictExtension is True, the file will not be read, unless
    1375         # the extension matches one in the extensionlist
    1376         self.strictExtension = strictExtension
     1388        ImportBaseclass.__init__(self,formatName,
     1389                                            longFormatName,
     1390                                            extensionlist,
     1391                                            strictExtension)
     1392
    13771393        # define contents of Structure Factor entry
    13781394        self.Controls = { # dictionary with plotting controls
    13791395            'Type' : 'Fosq',
    1380             'ifFc' : None,
     1396            'ifFc' : False,    #
    13811397            'HKLmax' : [None,None,None],
    13821398            'HKLmin' : [None,None,None],
    1383             'FoMax' : None,   # maximum observed structure factor
     1399            'FoMax' : None,   # maximum observed structure factor as Fo
    13841400            'Zone' : '001',
    13851401            'Layer' : 0,
    13861402            'Scale' : 1.0,
    13871403            'log-lin' : 'lin',
    1388             }           
     1404            }
    13891405        self.Parameters = [ # list with data collection parameters
    13901406            ('SXC',1.5428),
     
    13931409            ]
    13941410        self.RefList = []
    1395         self.warnings = ''
    1396         self.errors = ''
    1397 
    1398     def PhaseSelector(self, ChoiceList, ParentFrame=None,
    1399                       title='Select a structure factor', size=None):
    1400         ''' Provide a wx dialog to select a dataset if the file contains more
    1401         than one
     1411
     1412    def UpdateParameters(self,Type=None,Wave=None):
     1413        HistType = self.Parameters[0][0]
     1414        HistWave = self.Parameters[0][1]
     1415        if Type is not None:
     1416            HistType = Type
     1417        if Wave is not None:
     1418            HistWave = Wave
     1419        self.Parameters = [ # overwrite entire list
     1420            (HistType,HistWave),
     1421            [HistType,HistWave],
     1422            ['Type','Lam']
     1423            ]
     1424           
     1425    def UpdateControls(self,Type='Fosq',FcalcPresent=False):
     1426        '''Scan through the reflections to update the Controls dictionary
    14021427        '''
    1403         dlg = wx.SingleChoiceDialog(
    1404             ParentFrame,
    1405             title,
    1406             'Structure Factor Selection',
    1407             ChoiceList,
    1408             )
    1409         if size: dlg.SetSize(size)
    1410         if dlg.ShowModal() == wx.ID_OK:
    1411             sel = dlg.GetSelection()
    1412             dlg.Destroy()
    1413             return sel
     1428        self.Controls['Type'] = Type
     1429        self.Controls['iffc'] = FcalcPresent
     1430        HKLmax = [None,None,None]
     1431        HKLmin = [None,None,None]
     1432        Fo2max = None
     1433        for HKL,Fo2,SFo2,Fc,Fcp,Fcpp,phase in self.RefList:
     1434            if Fo2max is None:
     1435                Fo2max = Fo2
     1436            else:
     1437                Fo2max = max(Fo2max,Fo2)
     1438            for i,hkl in enumerate(HKL):
     1439                if HKLmax[i] is None:
     1440                    HKLmax[i] = hkl
     1441                    HKLmin[i] = hkl
     1442                else:
     1443                    HKLmax[i] = max(HKLmax[i],hkl)
     1444                    HKLmin[i] = min(HKLmin[i],hkl)
     1445        self.Controls['HKLmax'] = HKLmax
     1446        self.Controls['HKLmin'] = HKLmin
     1447        if Type ==  'Fosq':
     1448            self.Controls['FoMax'] = np.sqrt(Fo2max)
     1449        elif Type ==  'Fo':
     1450            self.Controls['FoMax'] = Fo2max
    14141451        else:
    1415             dlg.Destroy()
    1416             return None
    1417 
    1418     def ShowBusy(self):
    1419         wx.BeginBusyCursor()
    1420 
    1421     def DoneBusy(self):
    1422         wx.EndBusyCursor()
    1423        
    1424 #    def Reader(self, filename, filepointer, ParentFrame=None):
    1425 #        '''This method must be supplied in the child class
    1426 #        it will read the file
    1427 #        '''
    1428 #        return True # if read OK
    1429 #        return False # if an error occurs
    1430 
    1431     def ExtensionValidator(self, filename):
    1432         '''This methods checks if the file has the correct extension
    1433         Return False if this filename will not be supported by this reader
    1434         Return True if the extension matches the list supplied by the reader
    1435         Return None if the reader allows un-registered extensions
    1436         '''
    1437         if filename:
    1438             ext = os.path.splitext(filename)[1]
    1439             if sys.platform == 'windows': ext = ext.lower()
    1440             if ext in self.extensionlist: return True
    1441             if self.strictExtension: return False
    1442         return None
    1443 
    1444     def ContentsValidator(self, filepointer):
    1445         '''This routine will attempt to determine if the file can be read
    1446         with the current format.
    1447         This will typically be overridden with a method that
    1448         takes a quick scan of [some of]
    1449         the file contents to do a "sanity" check if the file
    1450         appears to match the selected format.
    1451         Expected to be called via self.Validator()
    1452         '''
    1453         #filepointer.seek(0) # rewind the file pointer
    1454         return True
     1452            print "Unsupported Stract Fact type in ImportStructFactor.UpdateControls"
     1453            raise Exception,"Unsupported Stract Fact type in ImportStructFactor.UpdateControls"
Note: See TracChangeset for help on using the changeset viewer.