Changeset 2817


Ignore:
Timestamp:
May 2, 2017 10:03:41 AM (6 years ago)
Author:
vondreele
Message:

major revision - move all importers to GSASIIobj & make them independent of wx so they can be used in a scripting environment.
Still to move are PhaseSelector?, and 3 BlockSelector? dialogs

Location:
trunk
Files:
34 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r2800 r2817  
    380380        :meth:`GSASII.OnImportSmallAngle` and :meth:'GSASII.OnImportReflectometry`
    381381
    382         Uses reader_objects subclassed from :class:`GSASIIIO.ImportPhase`,
    383         :class:`GSASIIIO.ImportStructFactor`,
    384         :class:`GSASIIIO.ImportPowderData`,
    385         :class:`GSASIIIO.ImportSmallAngleData`
    386         :class:`GSASIIIO.ImportReflectometryData` or
    387         :class:`GSASIIIO.ImportImage`.
     382        Uses reader_objects subclassed from :class:`GSASIIobj.ImportPhase`,
     383        :class:`GSASIIobj.ImportStructFactor`,
     384        :class:`GSASIIobj.ImportPowderData`,
     385        :class:`GSASIIobj.ImportSmallAngleData`
     386        :class:`GSASIIobj.ImportReflectometryData` or
     387        :class:`GSASIIobj.ImportImage`.
    388388        If a specific reader is specified, only that method will be called,
    389389        but if no reader is specified, every one that is potentially
     
    552552                            rd.errors += "\n  Traceback info:\n"+str(traceback.format_exc())
    553553                    if flag: # this read succeeded
     554                        if rd.SciPy:        #was default read by scipy; needs 1 time fixes
     555                            G2IO.EditImageParms(self,rd.Data,rd.Comments,rd.Image,filename)
     556                            rd.SciPy = False
    554557                        rd.readfilename = filename
    555558                        if load2Tree:   #images only
     
    11221125            for i in range(1,1+ibanks):
    11231126                choices.append('Bank '+str(i))
    1124             bank = 1 + rd.BlockSelector(
     1127            bank = 1 + G2IO.BlockSelector(
    11251128                choices, self,
    11261129                title='Select an instrument parameter bank for '+
     
    13291332                for l in dI.defaultIparm_lbl:
    13301333                    choices.append('Defaults for '+l)
    1331                 res = rd.BlockSelector(choices,ParentFrame=self,title=head,
     1334                res = G2IO.BlockSelector(choices,ParentFrame=self,title=head,
    13321335                    header='Select default inst parms',useCancel=True)
    13331336                if res is None: return None
     
    17091712                item, cookie = self.PatternTree.GetNextChild(self.root, cookie)
    17101713        # Initialize a base class reader
    1711         rd = G2IO.ImportPowderData(
     1714        rd = G2obj.ImportPowderData(
    17121715            extensionlist=tuple(),
    17131716            strictExtension=False,
     
    31013104                    Id = self.PatternTree.AppendItem(parent=self.root,text=outname)
    31023105                    if Id:
    3103                         Sample = G2pdG.SetDefaultSample()
     3106                        Sample = G2obj.SetDefaultSample()
    31043107                        Ymin = np.min(Ysum)
    31053108                        Ymax = np.max(Ysum)
  • trunk/GSASIIIO.py

    r2777 r2817  
    223223    mainsizer = wx.BoxSizer(wx.VERTICAL)
    224224    h,w = Image.shape[:2]
    225     mainsizer.Add(wx.StaticText(dlg,wx.ID_ANY,
    226                                 'File '+str(filename)+'\nImage size: '+str(h)+' x '+str(w)),
    227                   0,wx.ALIGN_LEFT|wx.ALL, 2)
     225    mainsizer.Add(wx.StaticText(dlg,wx.ID_ANY,'File '+str(filename)+'\nImage size: '+str(h)+' x '+str(w)),
     226        0,wx.ALIGN_LEFT|wx.ALL, 2)
    228227   
    229228    vsizer = wx.BoxSizer(wx.HORIZONTAL)
    230229    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Wavelength (\xC5) '),
    231                0,wx.ALIGN_LEFT|wx.ALL, 2)
     230        0,wx.ALIGN_LEFT|wx.ALL, 2)
    232231    wdgt = G2G.ValidatedTxtCtrl(dlg,Data,'wavelength')
    233232    vsizer.Add(wdgt)
     
    236235    vsizer = wx.BoxSizer(wx.HORIZONTAL)
    237236    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Pixel size (\xb5m). Width '),
    238                0,wx.ALIGN_LEFT|wx.ALL, 2)
     237        0,wx.ALIGN_LEFT|wx.ALL, 2)
    239238    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['pixelSize'],0,
    240239                                 size=(50,-1))
    241240    vsizer.Add(wdgt)
    242     vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'  Height '),
    243                wx.ALIGN_LEFT|wx.ALL, 2)
    244     wdgt = G2G.ValidatedTxtCtrl(dlg,Data['pixelSize'],1,
    245                                  size=(50,-1))
     241    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'  Height '),wx.ALIGN_LEFT|wx.ALL, 2)
     242    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['pixelSize'],1,size=(50,-1))
    246243    vsizer.Add(wdgt)
    247244    mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
     
    249246    vsizer = wx.BoxSizer(wx.HORIZONTAL)
    250247    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Sample to detector (mm) '),
    251                0,wx.ALIGN_LEFT|wx.ALL, 2)
     248        0,wx.ALIGN_LEFT|wx.ALL, 2)
    252249    wdgt = G2G.ValidatedTxtCtrl(dlg,Data,'distance')
    253250    vsizer.Add(wdgt)
     
    256253    vsizer = wx.BoxSizer(wx.HORIZONTAL)
    257254    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Beam center (pixels). X = '),
    258                0,wx.ALIGN_LEFT|wx.ALL, 2)
    259     wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],0,
    260                                  size=(75,-1))
     255        0,wx.ALIGN_LEFT|wx.ALL, 2)
     256    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],0,size=(75,-1))
    261257    vsizer.Add(wdgt)
    262     vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'  Y = '),
    263                wx.ALIGN_LEFT|wx.ALL, 2)
    264     wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],1,
    265                                  size=(75,-1))
     258    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'  Y = '),wx.ALIGN_LEFT|wx.ALL, 2)
     259    wdgt = G2G.ValidatedTxtCtrl(dlg,Data['center'],1,size=(75,-1))
    266260    vsizer.Add(wdgt)
    267261    mainsizer.Add(vsizer,0,wx.ALIGN_LEFT|wx.ALL, 2)
     
    269263    vsizer = wx.BoxSizer(wx.HORIZONTAL)
    270264    vsizer.Add(wx.StaticText(dlg,wx.ID_ANY,u'Comments '),
    271                0,wx.ALIGN_LEFT|wx.ALL, 2)
     265        0,wx.ALIGN_LEFT|wx.ALL, 2)
    272266    wdgt = G2G.ValidatedTxtCtrl(dlg,Comments,0,size=(250,-1))
    273267    vsizer.Add(wdgt)
     
    549543    return
    550544   
    551 # should get moved to importer when ready to test
    552 def GetEdfData(filename,imageOnly=False):   
    553     'Read European detector data edf file'
    554     if not imageOnly:
    555         print 'Read European detector data edf file: ',filename
    556     File = open(filename,'rb')
    557     fileSize = os.stat(filename).st_size
    558     head = File.read(3072)
    559     lines = head.split('\n')
    560     sizexy = [0,0]
    561     pixSize = [154,154]     #Pixium4700?
    562     cent = [0,0]
    563     wave = 1.54187  #default <CuKa>
    564     dist = 1000.
    565     head = ['European detector data',]
    566     for line in lines:
    567         line = line.replace(';',' ').strip()
    568         fields = line.split()
    569         if 'Dim_1' in line:
    570             sizexy[0] = int(fields[2])
    571         elif 'Dim_2' in line:
    572             sizexy[1] = int(fields[2])
    573         elif 'DataType' in line:
    574             dType = fields[2]
    575         elif 'wavelength' in line:
    576             wave = float(fields[2])
    577         elif 'Size' in line:
    578             imSize = int(fields[2])
    579 #        elif 'DataType' in lines:
    580 #            dType = fields[2]
    581         elif 'pixel_size_x' in line:
    582             pixSize[0] = float(fields[2])
    583         elif 'pixel_size_y' in line:
    584             pixSize[1] = float(fields[2])
    585         elif 'beam_center_x' in line:
    586             cent[0] = float(fields[2])
    587         elif 'beam_center_y' in line:
    588             cent[1] = float(fields[2])
    589         elif 'refined_distance' in line:
    590             dist = float(fields[2])
    591         if line:
    592             head.append(line)
    593         else:   #blank line at end of header
    594             break 
    595     File.seek(fileSize-imSize)
    596     if dType == 'UnsignedShort':       
    597         image = np.array(np.frombuffer(File.read(imSize),dtype=np.int16),dtype=np.int32)
    598     else:
    599         image = np.array(np.frombuffer(File.read(imSize),dtype=np.int32),dtype=np.int32)
    600     image = np.reshape(image,(sizexy[1],sizexy[0]))
    601     data = {'pixelSize':pixSize,'wavelength':wave,'distance':dist,'center':cent,'size':sizexy}
    602     Npix = sizexy[0]*sizexy[1]
    603     File.close()   
    604     if imageOnly:
    605         return image
    606     else:
    607         return head,data,Npix,image
    608        
    609 # should get moved to importer when ready to test
    610 def GetRigaku(filename,imageOnly=False):
    611     'Read Rigaku R-Axis IV image file'
    612     import array as ar
    613     if not imageOnly:
    614         print 'Read Rigaku R-Axis IV file: ',filename   
    615     File = open(filename,'rb')
    616     fileSize = os.stat(filename).st_size
    617     Npix = (fileSize-6000)/2
    618     File.read(6000)
    619     head = ['Rigaku R-Axis IV detector data',]
    620     image = np.array(ar.array('H',File.read(fileSize-6000)),dtype=np.int32)
    621     print fileSize,image.shape
    622     print head
    623     if Npix == 9000000:
    624         sizexy = [3000,3000]
    625         pixSize = [100.,100.]       
    626     elif Npix == 2250000:
    627         sizexy = [1500,1500]
    628         pixSize = [200.,200.]
    629     else:
    630         sizexy = [6000,6000]
    631         pixSize = [50.,50.]
    632     image = np.reshape(image,(sizexy[1],sizexy[0]))       
    633     data = {'pixelSize':pixSize,'wavelength':1.5428,'distance':250.0,'center':[150.,150.],'size':sizexy} 
    634     File.close()   
    635     if imageOnly:
    636         return image
    637     else:
    638         return head,data,Npix,image
    639    
    640 # should get moved to importer when ready to test       
    641 def GetImgData(filename,imageOnly=False):
    642     'Read an ADSC image file'
    643     import array as ar
    644     if not imageOnly:
    645         print 'Read ADSC img file: ',filename
    646     File = open(filename,'rb')
    647     head = File.read(511)
    648     lines = head.split('\n')
    649     head = []
    650     center = [0,0]
    651     for line in lines[1:-2]:
    652         line = line.strip()[:-1]
    653         if line:
    654             if 'SIZE1' in line:
    655                 size = int(line.split('=')[1])
    656                 Npix = size*size
    657             elif 'WAVELENGTH' in line:
    658                 wave = float(line.split('=')[1])
    659             elif 'BIN' in line:
    660                 if line.split('=')[1] == '2x2':
    661                     pixel=(102,102)
    662                 else:
    663                     pixel = (51,51)
    664             elif 'DISTANCE' in line:
    665                 distance = float(line.split('=')[1])
    666             elif 'CENTER_X' in line:
    667                 center[0] = float(line.split('=')[1])
    668             elif 'CENTER_Y' in line:
    669                 center[1] = float(line.split('=')[1])
    670             head.append(line)
    671     data = {'pixelSize':pixel,'wavelength':wave,'distance':distance,'center':center,'size':[size,size]}
    672     image = []
    673     pos = 512
    674     File.seek(pos)
    675     image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
    676     image = np.reshape(image,(size,size))
    677 #    image = np.zeros(shape=(size,size),dtype=np.int32)   
    678 #    while row < size:
    679 #        File.seek(pos)
    680 #        line = ar.array('H',File.read(2*size))
    681 #        image[row] = np.asarray(line)
    682 #        row += 1
    683 #        pos += 2*size
    684     File.close()
    685     if imageOnly:
    686         return image
    687     else:
    688         return lines[1:-2],data,Npix,image
    689        
    690 # should get moved to importer when ready to test
    691 def GetMAR345Data(filename,imageOnly=False):
    692     'Read a MAR-345 image plate image'
    693     try:
    694         import pack_f as pf
    695     except:
    696         msg = wx.MessageDialog(None, message="Unable to load the GSAS MAR image decompression, pack_f",
    697                                caption="Import Error",
    698                                style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
    699         msg.ShowModal()
    700         return None,None,None,None
    701 
    702     if not imageOnly:
    703         print 'Read Mar345 file: ',filename
    704     File = open(filename,'rb')
    705     head = File.read(4095)
    706     lines = head[128:].split('\n')
    707     head = []
    708     for line in lines:
    709         line = line.strip()
    710         if 'PIXEL' in line:
    711             values = line.split()
    712             pixel = (int(values[2]),int(values[4]))     #in microns
    713         elif 'WAVELENGTH' in line:
    714             wave = float(line.split()[1])
    715         elif 'DISTANCE' in line:
    716             distance = float(line.split()[1])           #in mm
    717             if not distance:
    718                 distance = 500.
    719         elif 'CENTER' in line:
    720             values = line.split()
    721             center = [float(values[2])/10.,float(values[4])/10.]    #make in mm from pixels
    722         if line:
    723             head.append(line)
    724     data = {'pixelSize':pixel,'wavelength':wave,'distance':distance,'center':center}
    725     for line in head:
    726         if 'FORMAT' in line[0:6]:
    727             items = line.split()
    728             sizex = int(items[1])
    729             Npix = int(items[3])
    730             sizey = int(Npix/sizex)
    731     pos = 4096
    732     data['size'] = [sizex,sizey]
    733     File.seek(pos)
    734     line = File.read(8)
    735     while 'CCP4' not in line:       #get past overflow list for now
    736         line = File.read(8)
    737         pos += 8
    738     pos += 37
    739     File.seek(pos)
    740     raw = File.read()
    741     File.close()
    742     image = np.zeros(shape=(sizex,sizey),dtype=np.int32)
    743    
    744     image = np.flipud(pf.pack_f(len(raw),raw,sizex,sizey,image).T)  #transpose to get it right way around & flip
    745     if imageOnly:
    746         return image
    747     else:
    748         return head,data,Npix,image
    749        
    750545def ProjFileOpen(G2frame,showProvenance=True):
    751546    'Read a GSAS-II project file and load into the G2 data tree'
     
    913708            if nOcc:
    914709                Aname += '(%d)'%(nOcc)
    915         Sample = G2pdG.SetDefaultSample()       #set as Debye-Scherrer
     710        Sample = G2obj.SetDefaultSample()       #set as Debye-Scherrer
    916711        Sample['Gonio. radius'] = data['distance']
    917712        Sample['Omega'] = data['GonioAngles'][0]
     
    1116911            grfile.close()
    1117912            print ' G(R) saved to: ',grfilename
    1118            
    1119            
    1120            
    1121913   
    1122914def PeakListSave(G2frame,file,peaks):
     
    1155947    print 'index peak list saved'
    1156948   
    1157 def SetNewPhase(Name='New Phase',SGData=None,cell=None,Super=None):
    1158     '''Create a new phase dict with default values for various parameters
    1159 
    1160     :param str Name: Name for new Phase
    1161 
    1162     :param dict SGData: space group data from :func:`GSASIIspc:SpcGroup`;
    1163       defaults to data for P 1
    1164 
    1165     :param list cell: unit cell parameter list; defaults to
    1166       [1.0,1.0,1.0,90.,90,90.,1.]
    1167 
    1168     '''
    1169     if SGData is None: SGData = G2spc.SpcGroup('P 1')[1]
    1170     if cell is None: cell=[1.0,1.0,1.0,90.,90,90.,1.]
    1171     phaseData = {
    1172         'ranId':ran.randint(0,sys.maxint),
    1173         'General':{
    1174             'Name':Name,
    1175             'Type':'nuclear',
    1176             'Modulated':False,
    1177             'AtomPtrs':[3,1,7,9],
    1178             'SGData':SGData,
    1179             'Cell':[False,]+cell,
    1180             'Pawley dmin':1.0,
    1181             'Data plot type':'None',
    1182             'SH Texture':{
    1183                 'Order':0,
    1184                 'Model':'cylindrical',
    1185                 'Sample omega':[False,0.0],
    1186                 'Sample chi':[False,0.0],
    1187                 'Sample phi':[False,0.0],
    1188                 'SH Coeff':[False,{}],
    1189                 'SHShow':False,
    1190                 'PFhkl':[0,0,1],
    1191                 'PFxyz':[0,0,1],
    1192                 'PlotType':'Pole figure',
    1193                 'Penalty':[['',],0.1,False,1.0]}},
    1194         'Atoms':[],
    1195         'Drawing':{},
    1196         'Histograms':{},
    1197         'Pawley ref':[],
    1198         'RBModels':{},
    1199         }
    1200     if Super and Super.get('Use',False):
    1201         phaseData['General'].update({'Modulated':True,'Super':True,'SuperSg':Super['ssSymb']})
    1202         phaseData['General']['SSGData'] = G2spc.SSpcGroup(SGData,Super['ssSymb'])
    1203         phaseData['General']['SuperVec'] = [Super['ModVec'],False,Super['maxH']]
    1204 
    1205     return phaseData
    1206        
    1207949class MultipleChoicesDialog(wx.Dialog):
    1208950    '''A dialog that offers a series of choices, each with a
     
    13951137#   not used directly, only by subclassing
    13961138######################################################################
    1397 try:
    1398     E,SGData = G2spc.SpcGroup('P 1') # data structure for default space group
    1399 except: # errors on doc build
    1400     SGData = None
    1401 P1SGData = SGData
    1402 ######################################################################
    1403 class ImportBaseclass(object):
    1404     '''Defines a base class for the reading of input files (diffraction
    1405     data, coordinates,...). See :ref:`Writing a Import Routine<Import_routines>`
    1406     for an explanation on how to use a subclass of this class.
     1139def BlockSelector(ChoiceList, ParentFrame=None,title='Select a block',
     1140    size=None, header='Block Selector',useCancel=True):
     1141    ''' Provide a wx dialog to select a block if the file contains more
     1142    than one set of data and one must be selected
    14071143    '''
    1408     class ImportException(Exception):
    1409         '''Defines an Exception that is used when an import routine hits an expected error,
    1410         usually in .Reader.
    1411 
    1412         Good practice is that the Reader should define a value in self.errors that
    1413         tells the user some information about what is wrong with their file.         
    1414         '''
    1415         pass
     1144    if useCancel:
     1145        dlg = wx.SingleChoiceDialog(
     1146            ParentFrame,title, header,ChoiceList)
     1147    else:
     1148        dlg = wx.SingleChoiceDialog(
     1149            ParentFrame,title, header,ChoiceList,
     1150            style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CENTRE)
     1151    if size: dlg.SetSize(size)
     1152    dlg.CenterOnParent()
     1153    if dlg.ShowModal() == wx.ID_OK:
     1154        sel = dlg.GetSelection()
     1155        return sel
     1156    else:
     1157        return None
     1158    dlg.Destroy()
     1159
     1160def MultipleBlockSelector(ChoiceList, ParentFrame=None,
     1161    title='Select a block',size=None, header='Block Selector'):
     1162    '''Provide a wx dialog to select a block of data if the
     1163    file contains more than one set of data and one must be
     1164    selected.
     1165
     1166    :returns: a list of the selected blocks
     1167    '''
     1168    dlg = wx.MultiChoiceDialog(ParentFrame,title, header,ChoiceList+['Select all'],
     1169        wx.CHOICEDLG_STYLE)
     1170    dlg.CenterOnScreen()
     1171    if size: dlg.SetSize(size)
     1172    if dlg.ShowModal() == wx.ID_OK:
     1173        sel = dlg.GetSelections()
     1174    else:
     1175        return []
     1176    dlg.Destroy()
     1177    selected = []
     1178    if len(ChoiceList) in sel:
     1179        return range(len(ChoiceList))
     1180    else:
     1181        return sel
     1182    return selected
     1183
     1184def MultipleChoicesSelector(choicelist, headinglist, ParentFrame=None, **kwargs):
     1185    '''A modal dialog that offers a series of choices, each with a title and a wx.Choice
     1186    widget. Typical input:
    14161187   
    1417     UseReader = True  # in __init__ set value of self.UseReader to False to skip use of current importer
    1418     def __init__(self,formatName,longFormatName=None,
    1419                  extensionlist=[],strictExtension=False,):
    1420         self.formatName = formatName # short string naming file type
    1421         if longFormatName: # longer string naming file type
    1422             self.longFormatName = longFormatName
    1423         else:
    1424             self.longFormatName = formatName
    1425         # define extensions that are allowed for the file type
    1426         # for windows, remove any extensions that are duplicate, as case is ignored
    1427         if sys.platform == 'windows' and extensionlist:
    1428             extensionlist = list(set([s.lower() for s in extensionlist]))
    1429         self.extensionlist = extensionlist
    1430         # If strictExtension is True, the file will not be read, unless
    1431         # the extension matches one in the extensionlist
    1432         self.strictExtension = strictExtension
    1433         self.errors = ''
    1434         self.warnings = ''
    1435         # used for readers that will use multiple passes to read
    1436         # more than one data block
    1437         self.repeat = False
    1438         self.selections = []
    1439         self.repeatcount = 0
    1440         self.readfilename = '?'
    1441         #print 'created',self.__class__
    1442 
    1443     def ReInitialize(self):
    1444         'Reinitialize the Reader to initial settings'
    1445         self.errors = ''
    1446         self.warnings = ''
    1447         self.repeat = False
    1448         self.repeatcount = 0
    1449         self.readfilename = '?'
    1450 
    1451     def BlockSelector(self, ChoiceList, ParentFrame=None,title='Select a block',
    1452         size=None, header='Block Selector',useCancel=True):
    1453         ''' Provide a wx dialog to select a block if the file contains more
    1454         than one set of data and one must be selected
    1455         '''
    1456         if useCancel:
    1457             dlg = wx.SingleChoiceDialog(
    1458                 ParentFrame,title, header,ChoiceList)
    1459         else:
    1460             dlg = wx.SingleChoiceDialog(
    1461                 ParentFrame,title, header,ChoiceList,
    1462                 style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CENTRE)
    1463         if size: dlg.SetSize(size)
    1464         dlg.CenterOnParent()
    1465         if dlg.ShowModal() == wx.ID_OK:
    1466             sel = dlg.GetSelection()
    1467             return sel
    1468         else:
    1469             return None
    1470         dlg.Destroy()
    1471 
    1472     def MultipleBlockSelector(self, ChoiceList, ParentFrame=None,
    1473         title='Select a block',size=None, header='Block Selector'):
    1474         '''Provide a wx dialog to select a block of data if the
    1475         file contains more than one set of data and one must be
    1476         selected.
    1477 
    1478         :returns: a list of the selected blocks
    1479         '''
    1480         dlg = wx.MultiChoiceDialog(ParentFrame,title, header,ChoiceList+['Select all'],
    1481             wx.CHOICEDLG_STYLE)
    1482         dlg.CenterOnScreen()
    1483         if size: dlg.SetSize(size)
    1484         if dlg.ShowModal() == wx.ID_OK:
    1485             sel = dlg.GetSelections()
    1486         else:
    1487             return []
    1488         dlg.Destroy()
    1489         selected = []
    1490         if len(ChoiceList) in sel:
    1491             return range(len(ChoiceList))
    1492         else:
    1493             return sel
    1494         return selected
    1495 
    1496     def MultipleChoicesDialog(self, choicelist, headinglist, ParentFrame=None, **kwargs):
    1497         '''A modal dialog that offers a series of choices, each with a title and a wx.Choice
    1498         widget. Typical input:
    1499        
    1500            * choicelist=[ ('a','b','c'), ('test1','test2'),('no choice',)]
    1501            
    1502            * headinglist = [ 'select a, b or c', 'select 1 of 2', 'No option here']
    1503            
    1504         optional keyword parameters are: head (window title) and title
    1505         returns a list of selected indicies for each choice (or None)
    1506         '''
    1507         result = None
    1508         dlg = MultipleChoicesDialog(choicelist,headinglist,
    1509             parent=ParentFrame, **kwargs)         
    1510         dlg.CenterOnParent()
    1511         if dlg.ShowModal() == wx.ID_OK:
    1512             result = dlg.chosen
    1513         dlg.Destroy()
    1514         return result
    1515 
    1516     def ShowBusy(self):
    1517         wx.BeginBusyCursor()
     1188       * choicelist=[ ('a','b','c'), ('test1','test2'),('no choice',)]
     1189       
     1190       * headinglist = [ 'select a, b or c', 'select 1 of 2', 'No option here']
     1191       
     1192    optional keyword parameters are: head (window title) and title
     1193    returns a list of selected indicies for each choice (or None)
     1194    '''
     1195    result = None
     1196    dlg = MultipleChoicesDialog(choicelist,headinglist,
     1197        parent=ParentFrame, **kwargs)         
     1198    dlg.CenterOnParent()
     1199    if dlg.ShowModal() == wx.ID_OK:
     1200        result = dlg.chosen
     1201    dlg.Destroy()
     1202    return result
     1203
     1204def PhaseSelector(self, ChoiceList, ParentFrame=None,
     1205    title='Select a phase', size=None,header='Phase Selector'):
     1206    ''' Provide a wx dialog to select a phase if the file contains more
     1207    than one phase
     1208    '''
     1209    return BlockSelector(ChoiceList,ParentFrame,title,
     1210        size,header)
     1211
     1212def ShowBusy():
     1213    wx.BeginBusyCursor()
    15181214#        wx.Yield() # make it happen now!
    15191215
    1520     def DoneBusy(self):
    1521         wx.EndBusyCursor()
    1522         wx.Yield() # make it happen now!
    1523        
    1524 #    def Reader(self, filename, filepointer, ParentFrame=None, **unused):
    1525 #        '''This method must be supplied in the child class to read the file.
    1526 #        if the read fails either return False or raise an Exception
    1527 #        preferably of type ImportException.
    1528 #        '''
    1529 #        #start reading
    1530 #        raise ImportException("Error occurred while...")
    1531 #        self.errors += "Hint for user on why the error occur
    1532 #        return False # if an error occurs
    1533 #        return True # if read OK
    1534 
    1535     def ExtensionValidator(self, filename):
    1536         '''This methods checks if the file has the correct extension
    1537         Return False if this filename will not be supported by this reader
    1538         Return True if the extension matches the list supplied by the reader
    1539         Return None if the reader allows un-registered extensions
    1540         '''
    1541         if filename:
    1542             ext = os.path.splitext(filename)[1]
    1543             if sys.platform == 'windows': ext = ext.lower()
    1544             if ext in self.extensionlist: return True
    1545             if self.strictExtension: return False
    1546         return None
    1547 
    1548     def ContentsValidator(self, filepointer):
    1549         '''This routine will attempt to determine if the file can be read
    1550         with the current format.
    1551         This will typically be overridden with a method that
    1552         takes a quick scan of [some of]
    1553         the file contents to do a "sanity" check if the file
    1554         appears to match the selected format.
    1555         Expected to be called via self.Validator()
    1556         '''
    1557         #filepointer.seek(0) # rewind the file pointer
    1558         return True
    1559 
    1560     def CIFValidator(self, filepointer):
    1561         '''A :meth:`ContentsValidator` for use to validate CIF files.
    1562         '''
    1563         for i,l in enumerate(filepointer):
    1564             if i >= 1000: return True
    1565             '''Encountered only blank lines or comments in first 1000
    1566             lines. This is unlikely, but assume it is CIF anyway, since we are
    1567             even less likely to find a file with nothing but hashes and
    1568             blank lines'''
    1569             line = l.strip()
    1570             if len(line) == 0: # ignore blank lines
    1571                 continue
    1572             elif line.startswith('#'): # ignore comments
    1573                 continue
    1574             elif line.startswith('data_'): # on the right track, accept this file
    1575                 return True
    1576             else: # found something invalid
    1577                 self.errors = 'line '+str(i+1)+' contains unexpected data:\n'
    1578                 if all([ord(c) < 128 and ord(c) != 0 for c in str(l)]): # show only if ASCII
    1579                     self.errors += '  '+str(l)
    1580                 else:
    1581                     self.errors += '  (binary)'
    1582                 self.errors += '\n  Note: a CIF should only have blank lines or comments before'
    1583                 self.errors += '\n        a data_ statement begins a block.'
    1584                 return False
    1585 
    1586 ######################################################################
    1587 class ImportPhase(ImportBaseclass):
    1588     '''Defines a base class for the reading of files with coordinates
    1589 
    1590     Objects constructed that subclass this (in import/G2phase_*.py etc.) will be used
    1591     in :meth:`GSASII.GSASII.OnImportPhase`.
    1592     See :ref:`Writing a Import Routine<Import_Routines>`
    1593     for an explanation on how to use this class.
    1594 
    1595     '''
    1596     def __init__(self,formatName,longFormatName=None,extensionlist=[],
    1597         strictExtension=False,):
    1598         # call parent __init__
    1599         ImportBaseclass.__init__(self,formatName,longFormatName,
    1600             extensionlist,strictExtension)
    1601         self.Phase = None # a phase must be created with G2IO.SetNewPhase in the Reader
    1602         self.Constraints = None
    1603 
    1604     def PhaseSelector(self, ChoiceList, ParentFrame=None,
    1605         title='Select a phase', size=None,header='Phase Selector'):
    1606         ''' Provide a wx dialog to select a phase if the file contains more
    1607         than one phase
    1608         '''
    1609         return self.BlockSelector(ChoiceList,ParentFrame,title,
    1610             size,header)
    1611 
    1612 ######################################################################
    1613 class ImportStructFactor(ImportBaseclass):
    1614     '''Defines a base class for the reading of files with tables
    1615     of structure factors.
    1616 
    1617     Structure factors are read with a call to :meth:`GSASII.GSASII.OnImportSfact`
    1618     which in turn calls :meth:`GSASII.GSASII.OnImportGeneric`, which calls
    1619     methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
    1620     :meth:`Reader`.
    1621 
    1622     See :ref:`Writing a Import Routine<Import_Routines>`
    1623     for an explanation on how to use import classes in general. The specifics
    1624     for reading a structure factor histogram require that
    1625     the ``Reader()`` routine in the import
    1626     class need to do only a few things: It
    1627     should load :attr:`RefDict` item ``'RefList'`` with the reflection list,
    1628     and set :attr:`Parameters` with the instrument parameters
    1629     (initialized with :meth:`InitParameters` and set with :meth:`UpdateParameters`).
    1630     '''
    1631     def __init__(self,formatName,longFormatName=None,extensionlist=[],
    1632         strictExtension=False,):
    1633         ImportBaseclass.__init__(self,formatName,longFormatName,
    1634             extensionlist,strictExtension)
    1635 
    1636         # define contents of Structure Factor entry
    1637         self.Parameters = []
    1638         'self.Parameters is a list with two dicts for data parameter settings'
    1639         self.InitParameters()
    1640         self.RefDict = {'RefList':[],'FF':{},'Super':0}
    1641         self.Banks = []             #for multi bank data (usually TOF)
    1642         '''self.RefDict is a dict containing the reflection information, as read from the file.
    1643         Item 'RefList' contains the reflection information. See the
    1644         :ref:`Single Crystal Reflection Data Structure<XtalRefl_table>`
    1645         for the contents of each row. Dict element 'FF'
    1646         contains the form factor values for each element type; if this entry
    1647         is left as initialized (an empty list) it will be initialized as needed later.
    1648         '''
    1649     def ReInitialize(self):
    1650         'Reinitialize the Reader to initial settings'
    1651         ImportBaseclass.ReInitialize(self)
    1652         self.InitParameters()
    1653         self.Banks = []             #for multi bank data (usually TOF)
    1654         self.RefDict = {'RefList':[],'FF':{},'Super':0}
    1655        
    1656     def InitParameters(self):
    1657         'initialize the instrument parameters structure'
    1658         Lambda = 0.70926
    1659         HistType = 'SXC'
    1660         self.Parameters = [{'Type':[HistType,HistType], # create the structure
    1661                             'Lam':[Lambda,Lambda]
    1662                             }, {}]
    1663         'Parameters is a list with two dicts for data parameter settings'
    1664 
    1665     def UpdateParameters(self,Type=None,Wave=None):
    1666         'Revise the instrument parameters'
    1667         if Type is not None:
    1668             self.Parameters[0]['Type'] = [Type,Type]
    1669         if Wave is not None:
    1670             self.Parameters[0]['Lam'] = [Wave,Wave]           
    1671                        
    1672 ######################################################################
    1673 class ImportPowderData(ImportBaseclass):
    1674     '''Defines a base class for the reading of files with powder data.
    1675 
    1676     Objects constructed that subclass this (in import/G2pwd_*.py etc.) will be used
    1677     in :meth:`GSASII.GSASII.OnImportPowder`.
    1678     See :ref:`Writing a Import Routine<Import_Routines>`
    1679     for an explanation on how to use this class.
    1680     '''
    1681     def __init__(self,formatName,longFormatName=None,
    1682         extensionlist=[],strictExtension=False,):
    1683         ImportBaseclass.__init__(self,formatName,longFormatName,
    1684             extensionlist,strictExtension)
    1685         self.clockWd = None  # used in TOF
    1686         self.ReInitialize()
    1687        
    1688     def ReInitialize(self):
    1689         'Reinitialize the Reader to initial settings'
    1690         ImportBaseclass.ReInitialize(self)
    1691         self.powderentry = ['',None,None] #  (filename,Pos,Bank)
    1692         self.powderdata = [] # Powder dataset
    1693         '''A powder data set is a list with items [x,y,w,yc,yb,yd]:
    1694                 np.array(x), # x-axis values
    1695                 np.array(y), # powder pattern intensities
    1696                 np.array(w), # 1/sig(intensity)^2 values (weights)
    1697                 np.array(yc), # calc. intensities (zero)
    1698                 np.array(yb), # calc. background (zero)
    1699                 np.array(yd), # obs-calc profiles
    1700         '''                           
    1701         self.comments = []
    1702         self.idstring = ''
    1703         self.Sample = G2pdG.SetDefaultSample() # default sample parameters
    1704         self.Controls = {}  # items to be placed in top-level Controls
    1705         self.GSAS = None     # used in TOF
    1706         self.repeat_instparm = True # Should a parm file be
    1707         #                             used for multiple histograms?
    1708         self.instparm = None # name hint from file of instparm to use
    1709         self.instfile = '' # full path name to instrument parameter file
    1710         self.instbank = '' # inst parm bank number
    1711         self.instmsg = ''  # a label that gets printed to show
    1712                            # where instrument parameters are from
    1713         self.numbanks = 1
    1714         self.instdict = {} # place items here that will be transferred to the instrument parameters
    1715         self.pwdparms = {} # place parameters that are transferred directly to the tree
    1716                            # here (typically from an existing GPX file)
    1717 ######################################################################
    1718 class ImportSmallAngleData(ImportBaseclass):
    1719     '''Defines a base class for the reading of files with small angle data.
    1720     See :ref:`Writing a Import Routine<Import_Routines>`
    1721     for an explanation on how to use this class.
    1722     '''
    1723     def __init__(self,formatName,longFormatName=None,extensionlist=[],
    1724         strictExtension=False,):
    1725            
    1726         ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
    1727             strictExtension)
    1728         self.ReInitialize()
    1729        
    1730     def ReInitialize(self):
    1731         'Reinitialize the Reader to initial settings'
    1732         ImportBaseclass.ReInitialize(self)
    1733         self.smallangleentry = ['',None,None] #  (filename,Pos,Bank)
    1734         self.smallangledata = [] # SASD dataset
    1735         '''A small angle data set is a list with items [x,y,w,yc,yd]:
    1736                 np.array(x), # x-axis values
    1737                 np.array(y), # powder pattern intensities
    1738                 np.array(w), # 1/sig(intensity)^2 values (weights)
    1739                 np.array(yc), # calc. intensities (zero)
    1740                 np.array(yd), # obs-calc profiles
    1741                 np.array(yb), # preset bkg
    1742         '''                           
    1743         self.comments = []
    1744         self.idstring = ''
    1745         self.Sample = G2pdG.SetDefaultSample()
    1746         self.GSAS = None     # used in TOF
    1747         self.clockWd = None  # used in TOF
    1748         self.numbanks = 1
    1749         self.instdict = {} # place items here that will be transferred to the instrument parameters
    1750 
    1751 ######################################################################
    1752 class ImportReflectometryData(ImportBaseclass):
    1753     '''Defines a base class for the reading of files with reflectometry data.
    1754     See :ref:`Writing a Import Routine<Import_Routines>`
    1755     for an explanation on how to use this class.
    1756     '''
    1757     def __init__(self,formatName,longFormatName=None,extensionlist=[],
    1758         strictExtension=False,):
    1759            
    1760         ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
    1761             strictExtension)
    1762         self.ReInitialize()
    1763        
    1764     def ReInitialize(self):
    1765         'Reinitialize the Reader to initial settings'
    1766         ImportBaseclass.ReInitialize(self)
    1767         self.reflectometryentry = ['',None,None] #  (filename,Pos,Bank)
    1768         self.reflectometrydata = [] # SASD dataset
    1769         '''A small angle data set is a list with items [x,y,w,yc,yd]:
    1770                 np.array(x), # x-axis values
    1771                 np.array(y), # powder pattern intensities
    1772                 np.array(w), # 1/sig(intensity)^2 values (weights)
    1773                 np.array(yc), # calc. intensities (zero)
    1774                 np.array(yd), # obs-calc profiles
    1775                 np.array(yb), # preset bkg
    1776         '''                           
    1777         self.comments = []
    1778         self.idstring = ''
    1779         self.Sample = G2pdG.SetDefaultSample()
    1780         self.GSAS = None     # used in TOF
    1781         self.clockWd = None  # used in TOF
    1782         self.numbanks = 1
    1783         self.instdict = {} # place items here that will be transferred to the instrument parameters
    1784 
    1785 ######################################################################
    1786 class ImportPDFData(ImportBaseclass):
    1787     '''Defines a base class for the reading of files with PDF G(R) data.
    1788     See :ref:`Writing a Import Routine<Import_Routines>`
    1789     for an explanation on how to use this class.
    1790     '''
    1791     def __init__(self,formatName,longFormatName=None,extensionlist=[],
    1792         strictExtension=False,):
    1793            
    1794         ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
    1795             strictExtension)
    1796         self.ReInitialize()
    1797        
    1798     def ReInitialize(self):
    1799         'Reinitialize the Reader to initial settings'
    1800         ImportBaseclass.ReInitialize(self)
    1801         self.pdfentry = ['',None,None] #  (filename,Pos,Bank)
    1802         self.pdfdata = [] # PDF G(R) dataset
    1803         '''A pdf g(r) data set is a list with items [x,y]:
    1804                 np.array(x), # r-axis values
    1805                 np.array(y), # pdf g(r)
    1806         '''                           
    1807         self.comments = []
    1808         self.idstring = ''
    1809         self.numbanks = 1
    1810 
    1811 ######################################################################
    1812 class ImportImage(ImportBaseclass):
    1813     '''Defines a base class for the reading of images
    1814 
    1815     Images are read in only these places:
    1816    
    1817       * Initial reading is typically done from a menu item
    1818         with a call to :meth:`GSASII.GSASII.OnImportImage`
    1819         which in turn calls :meth:`GSASII.GSASII.OnImportGeneric`. That calls
    1820         methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
    1821         :meth:`Reader`. This returns a list of reader objects for each read image.
    1822 
    1823       * Images are read alternatively in :func:`GSASIIIO.ReadImages`, which puts image info
    1824         directly into the data tree.
    1825 
    1826       * Images are reloaded with :func:`GSASIIIO.GetImageData`.
    1827 
    1828     .. _Image_import_routines:
    1829 
    1830     When reading an image, the ``Reader()`` routine in the ImportImage class
    1831     should set:
    1832    
    1833       * :attr:`Comments`: a list of strings (str),
    1834       * :attr:`Npix`: the number of pixels in the image (int),
    1835       * :attr:`Image`: the actual image as a numpy array (np.array)
    1836       * :attr:`Data`: a dict defining image parameters (dict). Within this dict the following
    1837         data items are needed:
    1838        
    1839          * 'pixelSize': size of each pixel in microns (such as ``[200,200]``.
    1840          * 'wavelength': wavelength in Angstoms.
    1841          * 'distance': distance of detector from sample in cm.
    1842          * 'center': uncalibrated center of beam on detector (such as ``[204.8,204.8]``.
    1843          * 'size': size of image (such as ``[2048,2048]``).
    1844          * 'ImageTag': image number or other keyword used to retrieve image from
    1845            a multi-image data file (defaults to ``1`` if not specified).
    1846          * 'sumfile': holds sum image file name if a sum was produced from a multi image file
    1847 
    1848     optional data items:
    1849    
    1850       * :attr:`repeat`: set to True if there are additional images to
    1851         read in the file, False otherwise
    1852       * :attr:`repeatcount`: set to the number of the image.
    1853      
    1854     Note that the above is initialized with :meth:`InitParameters`.
    1855     (Also see :ref:`Writing a Import Routine<Import_Routines>`
    1856     for an explanation on how to use import classes in general.)
    1857     '''
    1858     def __init__(self,formatName,longFormatName=None,extensionlist=[],
    1859         strictExtension=False,):
    1860         ImportBaseclass.__init__(self,formatName,longFormatName,
    1861             extensionlist,strictExtension)
    1862         self.InitParameters()
    1863        
    1864     def ReInitialize(self):
    1865         'Reinitialize the Reader to initial settings -- not used at present'
    1866         ImportBaseclass.ReInitialize(self)
    1867         self.InitParameters()
    1868        
    1869     def InitParameters(self):
    1870         'initialize the instrument parameters structure'
    1871         self.Comments = ['No comments']
    1872         self.Data = {}
    1873         self.Npix = 0
    1874         self.Image = None
    1875         self.repeat = False
    1876         self.repeatcount = 1
    1877         self.sumfile = ''
    1878 
    1879     def LoadImage(self,ParentFrame,imagefile,imagetag=None):
    1880         '''Optionally, call this after reading in an image to load it into the tree.
    1881         This saves time by preventing a reread of the same information.
    1882         '''
    1883         if ParentFrame:
    1884             ParentFrame.ImageZ = self.Image   # store the image for plotting
    1885             ParentFrame.oldImagefile = imagefile # save the name of the last image file read
    1886             ParentFrame.oldImageTag = imagetag   # save the tag of the last image file read           
    1887 
     1216def DoneBusy():
     1217    wx.EndBusyCursor()
     1218    wx.Yield() # make it happen now!
    18881219######################################################################
    18891220def striphist(var,insChar=''):
     
    27872118    return Layer
    27882119
    2789 def ReadCIF(URLorFile):
    2790     '''Open a CIF, which may be specified as a file name or as a URL using PyCifRW
    2791     (from James Hester).
    2792     The open routine gets confused with DOS names that begin with a letter and colon
    2793     "C:\dir\" so this routine will try to open the passed name as a file and if that
    2794     fails, try it as a URL
    2795 
    2796     :param str URLorFile: string containing a URL or a file name. Code will try first
    2797       to open it as a file and then as a URL.
    2798 
    2799     :returns: a PyCifRW CIF object.
    2800     '''
    2801     import CifFile as cif # PyCifRW from James Hester
    2802 
    2803     # alternate approach:
    2804     #import urllib
    2805     #ciffile = 'file:'+urllib.pathname2url(filename)
    2806    
    2807     try:
    2808         fp = open(URLorFile,'r')
    2809         cf = cif.ReadCif(fp)
    2810         fp.close()
    2811         return cf
    2812     except IOError:
    2813         return cif.ReadCif(URLorFile)
    2814 
    28152120if __name__ == '__main__':
    28162121    import GSASII
  • trunk/GSASIIobj.py

    r2765 r2817  
    863863import random as ran
    864864import sys
     865import os.path as ospath
    865866import GSASIIpath
    866867import GSASIImath as G2mth
     868import GSASIIspc as G2spc
    867869import numpy as np
    868870
     
    977979regular expressions. Initialized in :func:`CompileVarDesc`.
    978980'''
     981P1SGData = G2spc.SpcGroup('P 1')[1] # data structure for default space group
     982
     983def SetNewPhase(Name='New Phase',SGData=None,cell=None,Super=None):
     984    '''Create a new phase dict with default values for various parameters
     985
     986    :param str Name: Name for new Phase
     987
     988    :param dict SGData: space group data from :func:`GSASIIspc:SpcGroup`;
     989      defaults to data for P 1
     990
     991    :param list cell: unit cell parameter list; defaults to
     992      [1.0,1.0,1.0,90.,90,90.,1.]
     993
     994    '''
     995    if SGData is None: SGData = P1SGData
     996    if cell is None: cell=[1.0,1.0,1.0,90.,90,90.,1.]
     997    phaseData = {
     998        'ranId':ran.randint(0,sys.maxint),
     999        'General':{
     1000            'Name':Name,
     1001            'Type':'nuclear',
     1002            'Modulated':False,
     1003            'AtomPtrs':[3,1,7,9],
     1004            'SGData':SGData,
     1005            'Cell':[False,]+cell,
     1006            'Pawley dmin':1.0,
     1007            'Data plot type':'None',
     1008            'SH Texture':{
     1009                'Order':0,
     1010                'Model':'cylindrical',
     1011                'Sample omega':[False,0.0],
     1012                'Sample chi':[False,0.0],
     1013                'Sample phi':[False,0.0],
     1014                'SH Coeff':[False,{}],
     1015                'SHShow':False,
     1016                'PFhkl':[0,0,1],
     1017                'PFxyz':[0,0,1],
     1018                'PlotType':'Pole figure',
     1019                'Penalty':[['',],0.1,False,1.0]}},
     1020        'Atoms':[],
     1021        'Drawing':{},
     1022        'Histograms':{},
     1023        'Pawley ref':[],
     1024        'RBModels':{},
     1025        }
     1026    if Super and Super.get('Use',False):
     1027        phaseData['General'].update({'Modulated':True,'Super':True,'SuperSg':Super['ssSymb']})
     1028        phaseData['General']['SSGData'] = G2spc.SSpcGroup(SGData,Super['ssSymb'])
     1029        phaseData['General']['SuperVec'] = [Super['ModVec'],False,Super['maxH']]
     1030
     1031    return phaseData
     1032               
     1033def ReadCIF(URLorFile):
     1034    '''Open a CIF, which may be specified as a file name or as a URL using PyCifRW
     1035    (from James Hester).
     1036    The open routine gets confused with DOS names that begin with a letter and colon
     1037    "C:\dir\" so this routine will try to open the passed name as a file and if that
     1038    fails, try it as a URL
     1039
     1040    :param str URLorFile: string containing a URL or a file name. Code will try first
     1041      to open it as a file and then as a URL.
     1042
     1043    :returns: a PyCifRW CIF object.
     1044    '''
     1045    import CifFile as cif # PyCifRW from James Hester
     1046
     1047    # alternate approach:
     1048    #import urllib
     1049    #ciffile = 'file:'+urllib.pathname2url(filename)
     1050   
     1051    try:
     1052        fp = open(URLorFile,'r')
     1053        cf = cif.ReadCif(fp)
     1054        fp.close()
     1055        return cf
     1056    except IOError:
     1057        return cif.ReadCif(URLorFile)
    9791058
    9801059def IndexAllIds(Histograms,Phases):
     
    16471726
    16481727#==========================================================================
     1728def SetDefaultSample():
     1729    'Fills in default items for the Sample dictionary for Debye-Scherrer & SASD'
     1730    return {
     1731        'InstrName':'',
     1732        'ranId':ran.randint(0,sys.maxint),
     1733        'Scale':[1.0,True],'Type':'Debye-Scherrer','Absorption':[0.0,False],
     1734        'DisplaceX':[0.0,False],'DisplaceY':[0.0,False],'Diffuse':[],
     1735        'Temperature':300.,'Pressure':0.1,'Time':0.0,
     1736        'FreePrm1':0.,'FreePrm2':0.,'FreePrm3':0.,
     1737        'Gonio. radius':200.0,
     1738        'Omega':0.0,'Chi':0.0,'Phi':0.0,'Azimuth':0.0,
     1739#SASD items
     1740        'Materials':[{'Name':'vacuum','VolFrac':1.0,},{'Name':'vacuum','VolFrac':0.0,}],
     1741        'Thick':1.0,'Contrast':[0.0,0.0],       #contrast & anomalous contrast
     1742        'Trans':1.0,                            #measured transmission
     1743        'SlitLen':0.0,                          #Slit length - in Q(A-1)
     1744        }
     1745######################################################################
     1746class ImportBaseclass(object):
     1747    '''Defines a base class for the reading of input files (diffraction
     1748    data, coordinates,...). See :ref:`Writing a Import Routine<Import_routines>`
     1749    for an explanation on how to use a subclass of this class.
     1750    '''
     1751    class ImportException(Exception):
     1752        '''Defines an Exception that is used when an import routine hits an expected error,
     1753        usually in .Reader.
     1754
     1755        Good practice is that the Reader should define a value in self.errors that
     1756        tells the user some information about what is wrong with their file.         
     1757        '''
     1758        pass
     1759   
     1760    UseReader = True  # in __init__ set value of self.UseReader to False to skip use of current importer
     1761    def __init__(self,formatName,longFormatName=None,
     1762                 extensionlist=[],strictExtension=False,):
     1763        self.formatName = formatName # short string naming file type
     1764        if longFormatName: # longer string naming file type
     1765            self.longFormatName = longFormatName
     1766        else:
     1767            self.longFormatName = formatName
     1768        # define extensions that are allowed for the file type
     1769        # for windows, remove any extensions that are duplicate, as case is ignored
     1770        if sys.platform == 'windows' and extensionlist:
     1771            extensionlist = list(set([s.lower() for s in extensionlist]))
     1772        self.extensionlist = extensionlist
     1773        # If strictExtension is True, the file will not be read, unless
     1774        # the extension matches one in the extensionlist
     1775        self.strictExtension = strictExtension
     1776        self.errors = ''
     1777        self.warnings = ''
     1778        self.SciPy = False          #image reader needed scipy
     1779        # used for readers that will use multiple passes to read
     1780        # more than one data block
     1781        self.repeat = False
     1782        self.selections = []
     1783        self.repeatcount = 0
     1784        self.readfilename = '?'
     1785        #print 'created',self.__class__
     1786
     1787    def ReInitialize(self):
     1788        'Reinitialize the Reader to initial settings'
     1789        self.errors = ''
     1790        self.warnings = ''
     1791        self.SciPy = False          #image reader needed scipy
     1792        self.repeat = False
     1793        self.repeat = False
     1794        self.repeatcount = 0
     1795        self.readfilename = '?'
     1796
     1797       
     1798#    def Reader(self, filename, filepointer, ParentFrame=None, **unused):
     1799#        '''This method must be supplied in the child class to read the file.
     1800#        if the read fails either return False or raise an Exception
     1801#        preferably of type ImportException.
     1802#        '''
     1803#        #start reading
     1804#        raise ImportException("Error occurred while...")
     1805#        self.errors += "Hint for user on why the error occur
     1806#        return False # if an error occurs
     1807#        return True # if read OK
     1808
     1809    def ExtensionValidator(self, filename):
     1810        '''This methods checks if the file has the correct extension
     1811        Return False if this filename will not be supported by this reader
     1812        Return True if the extension matches the list supplied by the reader
     1813        Return None if the reader allows un-registered extensions
     1814        '''
     1815        if filename:
     1816            ext = ospath.splitext(filename)[1]
     1817            if sys.platform == 'windows': ext = ext.lower()
     1818            if ext in self.extensionlist: return True
     1819            if self.strictExtension: return False
     1820        return None
     1821
     1822    def ContentsValidator(self, filepointer):
     1823        '''This routine will attempt to determine if the file can be read
     1824        with the current format.
     1825        This will typically be overridden with a method that
     1826        takes a quick scan of [some of]
     1827        the file contents to do a "sanity" check if the file
     1828        appears to match the selected format.
     1829        Expected to be called via self.Validator()
     1830        '''
     1831        #filepointer.seek(0) # rewind the file pointer
     1832        return True
     1833
     1834    def CIFValidator(self, filepointer):
     1835        '''A :meth:`ContentsValidator` for use to validate CIF files.
     1836        '''
     1837        for i,l in enumerate(filepointer):
     1838            if i >= 1000: return True
     1839            '''Encountered only blank lines or comments in first 1000
     1840            lines. This is unlikely, but assume it is CIF anyway, since we are
     1841            even less likely to find a file with nothing but hashes and
     1842            blank lines'''
     1843            line = l.strip()
     1844            if len(line) == 0: # ignore blank lines
     1845                continue
     1846            elif line.startswith('#'): # ignore comments
     1847                continue
     1848            elif line.startswith('data_'): # on the right track, accept this file
     1849                return True
     1850            else: # found something invalid
     1851                self.errors = 'line '+str(i+1)+' contains unexpected data:\n'
     1852                if all([ord(c) < 128 and ord(c) != 0 for c in str(l)]): # show only if ASCII
     1853                    self.errors += '  '+str(l)
     1854                else:
     1855                    self.errors += '  (binary)'
     1856                self.errors += '\n  Note: a CIF should only have blank lines or comments before'
     1857                self.errors += '\n        a data_ statement begins a block.'
     1858                return False
     1859
     1860######################################################################
     1861class ImportPhase(ImportBaseclass):
     1862    '''Defines a base class for the reading of files with coordinates
     1863
     1864    Objects constructed that subclass this (in import/G2phase_*.py etc.) will be used
     1865    in :meth:`GSASII.GSASII.OnImportPhase`.
     1866    See :ref:`Writing a Import Routine<Import_Routines>`
     1867    for an explanation on how to use this class.
     1868
     1869    '''
     1870    def __init__(self,formatName,longFormatName=None,extensionlist=[],
     1871        strictExtension=False,):
     1872        # call parent __init__
     1873        ImportBaseclass.__init__(self,formatName,longFormatName,
     1874            extensionlist,strictExtension)
     1875        self.Phase = None # a phase must be created with G2IO.SetNewPhase in the Reader
     1876        self.Constraints = None
     1877
     1878######################################################################
     1879class ImportStructFactor(ImportBaseclass):
     1880    '''Defines a base class for the reading of files with tables
     1881    of structure factors.
     1882
     1883    Structure factors are read with a call to :meth:`GSASII.GSASII.OnImportSfact`
     1884    which in turn calls :meth:`GSASII.GSASII.OnImportGeneric`, which calls
     1885    methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
     1886    :meth:`Reader`.
     1887
     1888    See :ref:`Writing a Import Routine<Import_Routines>`
     1889    for an explanation on how to use import classes in general. The specifics
     1890    for reading a structure factor histogram require that
     1891    the ``Reader()`` routine in the import
     1892    class need to do only a few things: It
     1893    should load :attr:`RefDict` item ``'RefList'`` with the reflection list,
     1894    and set :attr:`Parameters` with the instrument parameters
     1895    (initialized with :meth:`InitParameters` and set with :meth:`UpdateParameters`).
     1896    '''
     1897    def __init__(self,formatName,longFormatName=None,extensionlist=[],
     1898        strictExtension=False,):
     1899        ImportBaseclass.__init__(self,formatName,longFormatName,
     1900            extensionlist,strictExtension)
     1901
     1902        # define contents of Structure Factor entry
     1903        self.Parameters = []
     1904        'self.Parameters is a list with two dicts for data parameter settings'
     1905        self.InitParameters()
     1906        self.RefDict = {'RefList':[],'FF':{},'Super':0}
     1907        self.Banks = []             #for multi bank data (usually TOF)
     1908        '''self.RefDict is a dict containing the reflection information, as read from the file.
     1909        Item 'RefList' contains the reflection information. See the
     1910        :ref:`Single Crystal Reflection Data Structure<XtalRefl_table>`
     1911        for the contents of each row. Dict element 'FF'
     1912        contains the form factor values for each element type; if this entry
     1913        is left as initialized (an empty list) it will be initialized as needed later.
     1914        '''
     1915    def ReInitialize(self):
     1916        'Reinitialize the Reader to initial settings'
     1917        ImportBaseclass.ReInitialize(self)
     1918        self.InitParameters()
     1919        self.Banks = []             #for multi bank data (usually TOF)
     1920        self.RefDict = {'RefList':[],'FF':{},'Super':0}
     1921       
     1922    def InitParameters(self):
     1923        'initialize the instrument parameters structure'
     1924        Lambda = 0.70926
     1925        HistType = 'SXC'
     1926        self.Parameters = [{'Type':[HistType,HistType], # create the structure
     1927                            'Lam':[Lambda,Lambda]
     1928                            }, {}]
     1929        'Parameters is a list with two dicts for data parameter settings'
     1930
     1931    def UpdateParameters(self,Type=None,Wave=None):
     1932        'Revise the instrument parameters'
     1933        if Type is not None:
     1934            self.Parameters[0]['Type'] = [Type,Type]
     1935        if Wave is not None:
     1936            self.Parameters[0]['Lam'] = [Wave,Wave]           
     1937                       
     1938######################################################################
     1939class ImportPowderData(ImportBaseclass):
     1940    '''Defines a base class for the reading of files with powder data.
     1941
     1942    Objects constructed that subclass this (in import/G2pwd_*.py etc.) will be used
     1943    in :meth:`GSASII.GSASII.OnImportPowder`.
     1944    See :ref:`Writing a Import Routine<Import_Routines>`
     1945    for an explanation on how to use this class.
     1946    '''
     1947    def __init__(self,formatName,longFormatName=None,
     1948        extensionlist=[],strictExtension=False,):
     1949        ImportBaseclass.__init__(self,formatName,longFormatName,
     1950            extensionlist,strictExtension)
     1951        self.clockWd = None  # used in TOF
     1952        self.ReInitialize()
     1953       
     1954    def ReInitialize(self):
     1955        'Reinitialize the Reader to initial settings'
     1956        ImportBaseclass.ReInitialize(self)
     1957        self.powderentry = ['',None,None] #  (filename,Pos,Bank)
     1958        self.powderdata = [] # Powder dataset
     1959        '''A powder data set is a list with items [x,y,w,yc,yb,yd]:
     1960                np.array(x), # x-axis values
     1961                np.array(y), # powder pattern intensities
     1962                np.array(w), # 1/sig(intensity)^2 values (weights)
     1963                np.array(yc), # calc. intensities (zero)
     1964                np.array(yb), # calc. background (zero)
     1965                np.array(yd), # obs-calc profiles
     1966        '''                           
     1967        self.comments = []
     1968        self.idstring = ''
     1969        self.Sample = SetDefaultSample() # default sample parameters
     1970        self.Controls = {}  # items to be placed in top-level Controls
     1971        self.GSAS = None     # used in TOF
     1972        self.repeat_instparm = True # Should a parm file be
     1973        #                             used for multiple histograms?
     1974        self.instparm = None # name hint from file of instparm to use
     1975        self.instfile = '' # full path name to instrument parameter file
     1976        self.instbank = '' # inst parm bank number
     1977        self.instmsg = ''  # a label that gets printed to show
     1978                           # where instrument parameters are from
     1979        self.numbanks = 1
     1980        self.instdict = {} # place items here that will be transferred to the instrument parameters
     1981        self.pwdparms = {} # place parameters that are transferred directly to the tree
     1982                           # here (typically from an existing GPX file)
     1983######################################################################
     1984class ImportSmallAngleData(ImportBaseclass):
     1985    '''Defines a base class for the reading of files with small angle data.
     1986    See :ref:`Writing a Import Routine<Import_Routines>`
     1987    for an explanation on how to use this class.
     1988    '''
     1989    def __init__(self,formatName,longFormatName=None,extensionlist=[],
     1990        strictExtension=False,):
     1991           
     1992        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
     1993            strictExtension)
     1994        self.ReInitialize()
     1995       
     1996    def ReInitialize(self):
     1997        'Reinitialize the Reader to initial settings'
     1998        ImportBaseclass.ReInitialize(self)
     1999        self.smallangleentry = ['',None,None] #  (filename,Pos,Bank)
     2000        self.smallangledata = [] # SASD dataset
     2001        '''A small angle data set is a list with items [x,y,w,yc,yd]:
     2002                np.array(x), # x-axis values
     2003                np.array(y), # powder pattern intensities
     2004                np.array(w), # 1/sig(intensity)^2 values (weights)
     2005                np.array(yc), # calc. intensities (zero)
     2006                np.array(yd), # obs-calc profiles
     2007                np.array(yb), # preset bkg
     2008        '''                           
     2009        self.comments = []
     2010        self.idstring = ''
     2011        self.Sample = SetDefaultSample()
     2012        self.GSAS = None     # used in TOF
     2013        self.clockWd = None  # used in TOF
     2014        self.numbanks = 1
     2015        self.instdict = {} # place items here that will be transferred to the instrument parameters
     2016
     2017######################################################################
     2018class ImportReflectometryData(ImportBaseclass):
     2019    '''Defines a base class for the reading of files with reflectometry data.
     2020    See :ref:`Writing a Import Routine<Import_Routines>`
     2021    for an explanation on how to use this class.
     2022    '''
     2023    def __init__(self,formatName,longFormatName=None,extensionlist=[],
     2024        strictExtension=False,):
     2025           
     2026        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
     2027            strictExtension)
     2028        self.ReInitialize()
     2029       
     2030    def ReInitialize(self):
     2031        'Reinitialize the Reader to initial settings'
     2032        ImportBaseclass.ReInitialize(self)
     2033        self.reflectometryentry = ['',None,None] #  (filename,Pos,Bank)
     2034        self.reflectometrydata = [] # SASD dataset
     2035        '''A small angle data set is a list with items [x,y,w,yc,yd]:
     2036                np.array(x), # x-axis values
     2037                np.array(y), # powder pattern intensities
     2038                np.array(w), # 1/sig(intensity)^2 values (weights)
     2039                np.array(yc), # calc. intensities (zero)
     2040                np.array(yd), # obs-calc profiles
     2041                np.array(yb), # preset bkg
     2042        '''                           
     2043        self.comments = []
     2044        self.idstring = ''
     2045        self.Sample = SetDefaultSample()
     2046        self.GSAS = None     # used in TOF
     2047        self.clockWd = None  # used in TOF
     2048        self.numbanks = 1
     2049        self.instdict = {} # place items here that will be transferred to the instrument parameters
     2050
     2051######################################################################
     2052class ImportPDFData(ImportBaseclass):
     2053    '''Defines a base class for the reading of files with PDF G(R) data.
     2054    See :ref:`Writing a Import Routine<Import_Routines>`
     2055    for an explanation on how to use this class.
     2056    '''
     2057    def __init__(self,formatName,longFormatName=None,extensionlist=[],
     2058        strictExtension=False,):
     2059           
     2060        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
     2061            strictExtension)
     2062        self.ReInitialize()
     2063       
     2064    def ReInitialize(self):
     2065        'Reinitialize the Reader to initial settings'
     2066        ImportBaseclass.ReInitialize(self)
     2067        self.pdfentry = ['',None,None] #  (filename,Pos,Bank)
     2068        self.pdfdata = [] # PDF G(R) dataset
     2069        '''A pdf g(r) data set is a list with items [x,y]:
     2070                np.array(x), # r-axis values
     2071                np.array(y), # pdf g(r)
     2072        '''                           
     2073        self.comments = []
     2074        self.idstring = ''
     2075        self.numbanks = 1
     2076
     2077######################################################################
     2078class ImportImage(ImportBaseclass):
     2079    '''Defines a base class for the reading of images
     2080
     2081    Images are read in only these places:
     2082   
     2083      * Initial reading is typically done from a menu item
     2084        with a call to :meth:`GSASII.GSASII.OnImportImage`
     2085        which in turn calls :meth:`GSASII.GSASII.OnImportGeneric`. That calls
     2086        methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
     2087        :meth:`Reader`. This returns a list of reader objects for each read image.
     2088
     2089      * Images are read alternatively in :func:`GSASIIIO.ReadImages`, which puts image info
     2090        directly into the data tree.
     2091
     2092      * Images are reloaded with :func:`GSASIIIO.GetImageData`.
     2093
     2094    .. _Image_import_routines:
     2095
     2096    When reading an image, the ``Reader()`` routine in the ImportImage class
     2097    should set:
     2098   
     2099      * :attr:`Comments`: a list of strings (str),
     2100      * :attr:`Npix`: the number of pixels in the image (int),
     2101      * :attr:`Image`: the actual image as a numpy array (np.array)
     2102      * :attr:`Data`: a dict defining image parameters (dict). Within this dict the following
     2103        data items are needed:
     2104       
     2105         * 'pixelSize': size of each pixel in microns (such as ``[200,200]``.
     2106         * 'wavelength': wavelength in Angstoms.
     2107         * 'distance': distance of detector from sample in cm.
     2108         * 'center': uncalibrated center of beam on detector (such as ``[204.8,204.8]``.
     2109         * 'size': size of image (such as ``[2048,2048]``).
     2110         * 'ImageTag': image number or other keyword used to retrieve image from
     2111           a multi-image data file (defaults to ``1`` if not specified).
     2112         * 'sumfile': holds sum image file name if a sum was produced from a multi image file
     2113
     2114    optional data items:
     2115   
     2116      * :attr:`repeat`: set to True if there are additional images to
     2117        read in the file, False otherwise
     2118      * :attr:`repeatcount`: set to the number of the image.
     2119     
     2120    Note that the above is initialized with :meth:`InitParameters`.
     2121    (Also see :ref:`Writing a Import Routine<Import_Routines>`
     2122    for an explanation on how to use import classes in general.)
     2123    '''
     2124    def __init__(self,formatName,longFormatName=None,extensionlist=[],
     2125        strictExtension=False,):
     2126        ImportBaseclass.__init__(self,formatName,longFormatName,
     2127            extensionlist,strictExtension)
     2128        self.InitParameters()
     2129       
     2130    def ReInitialize(self):
     2131        'Reinitialize the Reader to initial settings -- not used at present'
     2132        ImportBaseclass.ReInitialize(self)
     2133        self.InitParameters()
     2134       
     2135    def InitParameters(self):
     2136        'initialize the instrument parameters structure'
     2137        self.Comments = ['No comments']
     2138        self.Data = {}
     2139        self.Npix = 0
     2140        self.Image = None
     2141        self.repeat = False
     2142        self.repeatcount = 1
     2143        self.sumfile = ''
     2144
     2145    def LoadImage(self,ParentFrame,imagefile,imagetag=None):
     2146        '''Optionally, call this after reading in an image to load it into the tree.
     2147        This saves time by preventing a reread of the same information.
     2148        '''
     2149        if ParentFrame:
     2150            ParentFrame.ImageZ = self.Image   # store the image for plotting
     2151            ParentFrame.oldImagefile = imagefile # save the name of the last image file read
     2152            ParentFrame.oldImageTag = imagetag   # save the tag of the last image file read           
     2153
     2154#################################################################################################
    16492155# shortcut routines
    16502156exp = np.exp
  • trunk/GSASIIpwdGUI.py

    r2808 r2817  
    149149        return False
    150150
    151 def SetDefaultSample():
    152     'Fills in default items for the Sample dictionary for Debye-Scherrer & SASD'
    153     return {
    154         'InstrName':'',
    155         'ranId':ran.randint(0,sys.maxint),
    156         'Scale':[1.0,True],'Type':'Debye-Scherrer','Absorption':[0.0,False],
    157         'DisplaceX':[0.0,False],'DisplaceY':[0.0,False],'Diffuse':[],
    158         'Temperature':300.,'Pressure':0.1,'Time':0.0,
    159         'FreePrm1':0.,'FreePrm2':0.,'FreePrm3':0.,
    160         'Gonio. radius':200.0,
    161         'Omega':0.0,'Chi':0.0,'Phi':0.0,'Azimuth':0.0,
    162 #SASD items
    163         'Materials':[{'Name':'vacuum','VolFrac':1.0,},{'Name':'vacuum','VolFrac':0.0,}],
    164         'Thick':1.0,'Contrast':[0.0,0.0],       #contrast & anomalous contrast
    165         'Trans':1.0,                            #measured transmission
    166         'SlitLen':0.0,                          #Slit length - in Q(A-1)
    167         }
    168151def SetupSampleLabels(histName,dataType,histType):
    169152    '''Setup a list of labels and number formatting for use in
  • trunk/GSASIIscriptable.py

    r2816 r2817  
    1313import sys
    1414import cPickle
     15import GSASIIpath
     16import GSASIIobj as G2obj
     17
    1518def LoadDictFromProjFile(ProjFile):
    1619    ''''Read a GSAS-II project file and load items to dictionary
     
    9295    file.close()
    9396    print('project save successful')
     97   
     98def ImportPowder(filename,reader):
     99    print 'importer'
     100   
    94101
    95102def main():
  • trunk/docs/source/imports.rst

    r2802 r2817  
    33
    44Imports are implemented by deriving a class from
    5 :class:`GSASIIIO.ImportPhase`, :class:`GSASIIIO.ImportStructFactor`,
    6 :class:`GSASIIIO.ImportPowderData`
     5:class:`GSASIIobj.ImportPhase`, :class:`GSASIIobj.ImportStructFactor`,
     6:class:`GSASIIobj.ImportPowderData`
    77or :class:`GSASIIIO.ImportPowderData` (which are in turn
    8 derived from :class:`GSASIIIO.ImportBaseclass`)
     8derived from :class:`GSASIIobj.ImportBaseclass`)
    99to implement import of
    1010a phase, a single crystal or a powder dataset, respectively.
     
    147147_________________________
    148148
    149 Note that the base class (:class:`GSASIIIO.ImportBaseclass`) supplies two routines,
    150 :meth:`~GSASIIIO.ImportBaseclass.BlockSelector` and
    151 :meth:`~GSASIIIO.ImportBaseclass.MultipleBlockSelector` that are useful for
    152 selecting amongst one or more datasets (and perhaps phases) for
     149Note that GSASIIIO supplies three routines,
     150:meth:`~GSASIIIO.BlockSelector`
     151:meth:`~GSASIIIO.MultipleBlockSelector` and
     152:meth:`~GSASIIIO.MultipleChoiceSelector` that are useful for
     153selecting amongst one or more datasets (and perhaps phases) or data items for
    153154``Reader()`` routines that may encounter more than one set of information
    154155in a file.
    155156Likewise, when an operation will take some time to complete,
    156 use :meth:`~GSASIIIO.ImportBaseclass.ShowBusy` and
    157 :meth:`~GSASIIIO.ImportBaseclass.DoneBusy` to show the user
    158 that something is happening.
    159 
     157use :meth:`~GSASIIIO.ShowBusy` and
     158:meth:`~GSASIIIO.DoneBusy` to show the user that something is happening.
    160159
    161160ContentsValidator()
     
    205204----------------------------------------
    206205Phase import routines are classes derived from
    207 :class:`GSASIIIO.ImportPhase`. 
     206:class:`GSASIIobj.ImportPhase`. 
    208207They must be found in files named `G2phase*.py` that are in the Python path
    209208and the class must override the ``__init__`` method and add a ``Reader`` method.
     
    231230---------------------------------------------
    232231Powder data import routines are classes derived from
    233 :class:`GSASIIIO.ImportPowderData`.
     232:class:`GSASIIobj.ImportPowderData`.
    234233They must be found in files named `G2pwd*.py` that are in the Python path
    235234and the class must override the ``__init__`` method and add a
     
    275274-----------------------------------------------------
    276275Single crystal data import routines are classes derived from
    277 , :class:`GSASIIIO.ImportStructFactor`.
     276, :class:`GSASIIobj.ImportStructFactor`.
    278277They must be found in files named `G2sfact*.py` that are in the Python path
    279278and the class must override the ``__init__`` method and add a ``Reader`` method.
     
    292291-----------------------------------------------------
    293292Small angle scattering data import routines are classes derived from
    294 , :class:`GSASIIIO.ImportSmallAngle`.
     293, :class:`GSASIIobj.ImportSmallAngle`.
    295294They must be found in files named `G2sad*.py` that are in the Python path
    296295and the class must override the ``__init__`` method and add a ``Reader`` method.
     
    348347-----------------------------------------------------
    349348PDF import routines are classes derived from
    350 :class:`GSASIIIO.ImportPDFData`.
     349:class:`GSASIIobj.ImportPDFData`.
    351350See :ref:`Writing a Import Routine<Import_Routines>` for general information on importers.
    352351
     
    359358-----------------------------------------------------
    360359Reflectometry import routines are classes derived from
    361 :class:`GSASIIIO.ImportReflectometryData`.
     360:class:`GSASIIobj.ImportReflectometryData`.
    362361See :ref:`Writing a Import Routine<Import_Routines>` for general information on importers.
    363362
  • trunk/imports/G2img_1TIF.py

    r2774 r2817  
    2020
    2121import struct as st
    22 import GSASIIIO as G2IO
     22import GSASIIobj as G2obj
    2323import GSASIIpath
    2424import numpy as np
     
    2626DEBUG = False
    2727GSASIIpath.SetVersionNumber("$Revision$")
    28 class TIF_ReaderClass(G2IO.ImportImage):
     28class TIF_ReaderClass(G2obj.ImportImage):
    2929    '''Reads TIF files using a routine (:func:`GetTifData`) that looks
    3030    for files that can be identified from known instruments and will
     
    5858        edit the likely wrong default image parameters.
    5959        '''
    60        
    6160        self.Comments,self.Data,self.Npix,self.Image = GetTifData(filename)
    6261        if self.Npix == 0:
     
    6665            self.Npix = self.Image.size
    6766            if ParentFrame:
     67                self.SciPy = True
    6868                self.Comments = ['no metadata']
    6969                self.Data = {'wavelength': 0.1, 'pixelSize': [200, 200], 'distance': 100.0}
    7070                self.Data['size'] = list(self.Image.shape)
    7171                self.Data['center'] = [int(i/2) for i in self.Image.shape]
    72                 G2IO.EditImageParms(ParentFrame,self.Data,self.Comments,self.Image,filename)
    7372        if self.Npix == 0:
    7473            return False
  • trunk/imports/G2img_ADSC.py

    r2539 r2817  
    1313'''
    1414
    15 import GSASIIIO as G2IO
     15import GSASIIobj as G2obj
    1616import GSASIIpath
     17import numpy as np
    1718GSASIIpath.SetVersionNumber("$Revision$")
    18 class ADSC_ReaderClass(G2IO.ImportImage):
     19class ADSC_ReaderClass(G2obj.ImportImage):
    1920    '''Reads an ADSC .img file
    2021    '''
     
    3334       
    3435    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    35         '''Read using Bob's routine :func:`GSASIIIO.GetImgData`
    36         (to be moved to this file, eventually)
    37         '''
    38         self.Comments,self.Data,self.Npix,self.Image = G2IO.GetImgData(filename)
     36        self.Comments,self.Data,self.Npix,self.Image = GetImgData(filename)
    3937        if self.Npix == 0 or not self.Comments:
    4038            return False
    4139        self.LoadImage(ParentFrame,filename)
    4240        return True
     41
     42def GetImgData(filename,imageOnly=False):
     43    'Read an ADSC image file'
     44    import array as ar
     45    if not imageOnly:
     46        print 'Read ADSC img file: ',filename
     47    File = open(filename,'rb')
     48    head = File.read(511)
     49    lines = head.split('\n')
     50    head = []
     51    center = [0,0]
     52    for line in lines[1:-2]:
     53        line = line.strip()[:-1]
     54        if line:
     55            if 'SIZE1' in line:
     56                size = int(line.split('=')[1])
     57                Npix = size*size
     58            elif 'WAVELENGTH' in line:
     59                wave = float(line.split('=')[1])
     60            elif 'BIN' in line:
     61                if line.split('=')[1] == '2x2':
     62                    pixel=(102,102)
     63                else:
     64                    pixel = (51,51)
     65            elif 'DISTANCE' in line:
     66                distance = float(line.split('=')[1])
     67            elif 'CENTER_X' in line:
     68                center[0] = float(line.split('=')[1])
     69            elif 'CENTER_Y' in line:
     70                center[1] = float(line.split('=')[1])
     71            head.append(line)
     72    data = {'pixelSize':pixel,'wavelength':wave,'distance':distance,'center':center,'size':[size,size]}
     73    image = []
     74    pos = 512
     75    File.seek(pos)
     76    image = np.array(ar.array('H',File.read(2*Npix)),dtype=np.int32)
     77    image = np.reshape(image,(size,size))
     78    File.close()
     79    if imageOnly:
     80        return image
     81    else:
     82        return lines[1:-2],data,Npix,image
     83       
  • trunk/imports/G2img_CBF.py

    r2802 r2817  
    1414
    1515import time
    16 import GSASIIIO as G2IO
     16import GSASIIobj as G2obj
    1717import GSASIIpath
    1818import unpack_cbf as cbf
    1919GSASIIpath.SetVersionNumber("$Revision: 2133 $")
    20 class CBF_ReaderClass(G2IO.ImportImage):
     20class CBF_ReaderClass(G2obj.ImportImage):
    2121    '''Routine to read a Read cif image data .cbf file.
    2222    This is used by Pilatus.
  • trunk/imports/G2img_CheMin.py

    r2133 r2817  
    1717'''
    1818
    19 import sys
    20 import os
    21 import GSASIIIO as G2IO
     19import GSASIIobj as G2obj
    2220import GSASIIpath
    2321GSASIIpath.SetVersionNumber("$Revision$")
    24 class png_ReaderClass(G2IO.ImportImage):
     22class png_ReaderClass(G2obj.ImportImage):
    2523    '''Reads standard PNG images; parameters are set to those of the
    2624    Mars Rover (CheMin) diffractometer.
     
    4341        '''
    4442        import scipy.misc
    45         self.Image = scipy.misc.imread(filename,flatten=True)
     43        self.Image = scipy.misc.imread(filename,flatten=True).T
    4644        self.Npix = self.Image.size
    4745        if self.Npix == 0:
    4846            return False
    4947        if ParentFrame:
     48            self.SciPy = True
    5049            self.Comments = ['no metadata']
    5150            pixy = list(self.Image.shape)
    5251            sizexy = [40,40]
    5352            self.Data = {'wavelength': 1.78892, 'pixelSize': sizexy, 'distance': 18.0,'size':pixy}
    54             self.Data['center'] = [pixy[0]*sizexy[0]/1000,pixy[1]*sizexy[1]/2000]
    55             G2IO.EditImageParms(ParentFrame,self.Data,self.Comments,self.Image,filename)
     53            self.Data['center'] = [pixy[0]*sizexy[0]/1000.,pixy[1]*sizexy[1]/2000.]
    5654        self.LoadImage(ParentFrame,filename)
    5755        return True
  • trunk/imports/G2img_EDF.py

    r2133 r2817  
    1313'''
    1414
    15 import sys
    1615import os
    17 import GSASIIIO as G2IO
     16import numpy as np
     17import GSASIIobj as G2obj
    1818import GSASIIpath
    1919GSASIIpath.SetVersionNumber("$Revision$")
    20 class EDF_ReaderClass(G2IO.ImportImage):
     20class EDF_ReaderClass(G2obj.ImportImage):
    2121    '''Routine to read a Read European detector data .edf file.
    2222    This is a particularly nice standard.
     
    3636       
    3737    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    38         '''Read using Bob's routine :func:`GSASIIIO.GetEdfData`
    39         (to be moved to this file, eventually)
    40         '''
    41         self.Comments,self.Data,self.Npix,self.Image = G2IO.GetEdfData(filename)
     38        self.Comments,self.Data,self.Npix,self.Image = GetEdfData(filename)
    4239        if self.Npix == 0 or not self.Comments:
    4340            return False
    4441        self.LoadImage(ParentFrame,filename)
    4542        return True
     43
     44def GetEdfData(filename,imageOnly=False):   
     45    'Read European detector data edf file'
     46    if not imageOnly:
     47        print 'Read European detector data edf file: ',filename
     48    File = open(filename,'rb')
     49    fileSize = os.stat(filename).st_size
     50    head = File.read(3072)
     51    lines = head.split('\n')
     52    sizexy = [0,0]
     53    pixSize = [154,154]     #Pixium4700?
     54    cent = [0,0]
     55    wave = 1.54187  #default <CuKa>
     56    dist = 1000.
     57    head = ['European detector data',]
     58    for line in lines:
     59        line = line.replace(';',' ').strip()
     60        fields = line.split()
     61        if 'Dim_1' in line:
     62            sizexy[0] = int(fields[2])
     63        elif 'Dim_2' in line:
     64            sizexy[1] = int(fields[2])
     65        elif 'DataType' in line:
     66            dType = fields[2]
     67        elif 'wavelength' in line:
     68            wave = float(fields[2])
     69        elif 'Size' in line:
     70            imSize = int(fields[2])
     71#        elif 'DataType' in lines:
     72#            dType = fields[2]
     73        elif 'pixel_size_x' in line:
     74            pixSize[0] = float(fields[2])
     75        elif 'pixel_size_y' in line:
     76            pixSize[1] = float(fields[2])
     77        elif 'beam_center_x' in line:
     78            cent[0] = float(fields[2])
     79        elif 'beam_center_y' in line:
     80            cent[1] = float(fields[2])
     81        elif 'refined_distance' in line:
     82            dist = float(fields[2])
     83        if line:
     84            head.append(line)
     85        else:   #blank line at end of header
     86            break 
     87    File.seek(fileSize-imSize)
     88    if dType == 'UnsignedShort':       
     89        image = np.array(np.frombuffer(File.read(imSize),dtype=np.int16),dtype=np.int32)
     90    else:
     91        image = np.array(np.frombuffer(File.read(imSize),dtype=np.int32),dtype=np.int32)
     92    image = np.reshape(image,(sizexy[1],sizexy[0]))
     93    data = {'pixelSize':pixSize,'wavelength':wave,'distance':dist,'center':cent,'size':sizexy}
     94    Npix = sizexy[0]*sizexy[1]
     95    File.close()   
     96    if imageOnly:
     97        return image
     98    else:
     99        return head,data,Npix,image
     100       
  • trunk/imports/G2img_GE.py

    r2773 r2817  
    1818import os
    1919import numpy as np
    20 import GSASIIIO as G2IO
     20import GSASIIobj as G2obj
    2121import GSASIIpath
    2222GSASIIpath.SetVersionNumber("$Revision$")
    23 class GE_ReaderClass(G2IO.ImportImage):
     23class GE_ReaderClass(G2obj.ImportImage):
    2424    '''Routine to read a GE image, typically from APS Sector 1.
    2525       
     
    6767        return True
    6868
    69 class GEsum_ReaderClass(G2IO.ImportImage):
     69class GEsum_ReaderClass(G2obj.ImportImage):
    7070    '''Routine to read multiple GE images & sum them, typically from APS Sector 1.
    7171       
  • trunk/imports/G2img_HDF5.py

    r2802 r2817  
    1919except ImportError:
    2020    h5py = None
    21 import GSASIIIO as G2IO
     21import GSASIIobj as G2obj
    2222import GSASIIpath
    2323GSASIIpath.SetVersionNumber("$Revision$")
    2424
    25 class HDF5_Reader(G2IO.ImportImage):
     25class HDF5_Reader(G2obj.ImportImage):
    2626    '''Routine to read a HD5 image, typically from APS Sector 6.
    2727    B. Frosik/SDM.
  • trunk/imports/G2img_MAR.py

    r2133 r2817  
    1010*Module G2img_MAR: MAR image files*
    1111--------------------------------------
    12 
    1312'''
    1413
    15 import sys
    16 import os
    17 import GSASIIIO as G2IO
     14import GSASIIobj as G2obj
    1815import GSASIIpath
     16import numpy as np
    1917GSASIIpath.SetVersionNumber("$Revision$")
    20 class MAR_ReaderClass(G2IO.ImportImage):
     18class MAR_ReaderClass(G2obj.ImportImage):
    2119    '''Routine to read several MAR formats, .mar3450,.mar2300,.mar2560
    2220    '''
     
    3533       
    3634    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    37         '''Read using Bob's routine :func:`GSASIIIO.GetMAR345Data`
    38         (to be moved to this file, eventually)
    39         '''
    40         self.Comments,self.Data,self.Npix,self.Image = G2IO.GetMAR345Data(filename)
     35        self.Comments,self.Data,self.Npix,self.Image = GetMAR345Data(filename)
    4136        if self.Npix == 0 or not self.Comments:
    4237            return False
    4338        self.LoadImage(ParentFrame,filename)
    4439        return True
     40
     41def GetMAR345Data(filename,imageOnly=False):
     42    'Read a MAR-345 image plate image'
     43    try:
     44        import pack_f as pf
     45    except:
     46        print '**** ERROR - Unable to load the GSAS MAR image decompression, pack_f'
     47        return None,None,None,None
     48
     49    if not imageOnly:
     50        print 'Read Mar345 file: ',filename
     51    File = open(filename,'rb')
     52    head = File.read(4095)
     53    lines = head[128:].split('\n')
     54    head = []
     55    for line in lines:
     56        line = line.strip()
     57        if 'PIXEL' in line:
     58            values = line.split()
     59            pixel = (int(values[2]),int(values[4]))     #in microns
     60        elif 'WAVELENGTH' in line:
     61            wave = float(line.split()[1])
     62        elif 'DISTANCE' in line:
     63            distance = float(line.split()[1])           #in mm
     64            if not distance:
     65                distance = 500.
     66        elif 'CENTER' in line:
     67            values = line.split()
     68            center = [float(values[2])/10.,float(values[4])/10.]    #make in mm from pixels
     69        if line:
     70            head.append(line)
     71    data = {'pixelSize':pixel,'wavelength':wave,'distance':distance,'center':center}
     72    for line in head:
     73        if 'FORMAT' in line[0:6]:
     74            items = line.split()
     75            sizex = int(items[1])
     76            Npix = int(items[3])
     77            sizey = int(Npix/sizex)
     78    pos = 4096
     79    data['size'] = [sizex,sizey]
     80    File.seek(pos)
     81    line = File.read(8)
     82    while 'CCP4' not in line:       #get past overflow list for now
     83        line = File.read(8)
     84        pos += 8
     85    pos += 37
     86    File.seek(pos)
     87    raw = File.read()
     88    File.close()
     89    image = np.zeros(shape=(sizex,sizey),dtype=np.int32)
     90   
     91    image = np.flipud(pf.pack_f(len(raw),raw,sizex,sizey,image).T)  #transpose to get it right way around & flip
     92    if imageOnly:
     93        return image
     94    else:
     95        return head,data,Npix,image
     96       
  • trunk/imports/G2img_Rigaku.py

    r2133 r2817  
    1313'''
    1414
    15 import sys
    1615import os
    17 import GSASIIIO as G2IO
     16import GSASIIobj as G2obj
    1817import GSASIIpath
     18import numpy as np
    1919GSASIIpath.SetVersionNumber("$Revision$")
    20 class Rigaku_ReaderClass(G2IO.ImportImage):
     20class Rigaku_ReaderClass(G2obj.ImportImage):
    2121    '''Routine to read a Rigaku R-Axis IV image file.
    2222    '''
     
    3939       
    4040    def Reader(self,filename,filepointer, ParentFrame=None, **unused):
    41         '''Read using Bob's routine :func:`GSASIIIO.GetRigaku`
    42         (to be moved to this file, eventually)
    43         '''
    44 
    45         self.Comments,self.Data,self.Npix,self.Image = G2IO.GetRigaku(filename)
     41        self.Comments,self.Data,self.Npix,self.Image = GetRigaku(filename)
    4642        if self.Npix == 0 or not self.Comments:
    4743            return False
    4844        self.LoadImage(ParentFrame,filename)
    4945        return True
     46
     47def GetRigaku(filename,imageOnly=False):
     48    'Read Rigaku R-Axis IV image file'
     49    import array as ar
     50    if not imageOnly:
     51        print 'Read Rigaku R-Axis IV file: ',filename   
     52    File = open(filename,'rb')
     53    fileSize = os.stat(filename).st_size
     54    Npix = (fileSize-6000)/2
     55    File.read(6000)
     56    head = ['Rigaku R-Axis IV detector data',]
     57    image = np.array(ar.array('H',File.read(fileSize-6000)),dtype=np.int32)
     58    print fileSize,image.shape
     59    print head
     60    if Npix == 9000000:
     61        sizexy = [3000,3000]
     62        pixSize = [100.,100.]       
     63    elif Npix == 2250000:
     64        sizexy = [1500,1500]
     65        pixSize = [200.,200.]
     66    else:
     67        sizexy = [6000,6000]
     68        pixSize = [50.,50.]
     69    image = np.reshape(image,(sizexy[1],sizexy[0]))       
     70    data = {'pixelSize':pixSize,'wavelength':1.5428,'distance':250.0,'center':[150.,150.],'size':sizexy} 
     71    File.close()   
     72    if imageOnly:
     73        return image
     74    else:
     75        return head,data,Npix,image
     76   
  • trunk/imports/G2img_SumG2.py

    r2309 r2817  
    1313'''
    1414
    15 import sys
    16 import os
    1715import cPickle
    18 import GSASIIIO as G2IO
     16import GSASIIobj as G2obj
    1917import GSASIIpath
    2018GSASIIpath.SetVersionNumber("$Revision$")
    21 class G2_ReaderClass(G2IO.ImportImage):
     19class G2_ReaderClass(G2obj.ImportImage):
    2220    '''Routine to read an image that has been pickled in Python. Images
    2321    in this format are created by the "Sum image data" command. At least for
     
    4442        '''Read using cPickle
    4543        '''
    46         import scipy.misc
    4744        Fp = open(filename,'rb')
    4845        self.Comments,self.Data,self.Npix,self.Image = cPickle.load(Fp)
  • trunk/imports/G2pdf_gr.py

    r2781 r2817  
    1818import os.path as ospath
    1919import numpy as np
    20 import GSASIIIO as G2IO
     20import GSASIIobj as G2obj
    2121import GSASIIpath
    2222GSASIIpath.SetVersionNumber("$Revision: 2738 $")
    2323
    24 class txt_PDFReaderClass(G2IO.ImportPDFData):
     24class txt_PDFReaderClass(G2obj.ImportPDFData):
    2525    'Routines to import PDF G(R) data from a .gr file'
    2626    def __init__(self):
  • trunk/imports/G2phase.py

    r2738 r2817  
    2121import math
    2222import random as ran
    23 import traceback
    2423import numpy as np
    2524import wx
    26 import GSASIIIO as G2IO
     25import GSASIIobj as G2obj
    2726import GSASIIspc as G2spc
    2827import GSASIIlattice as G2lat
     
    3130R2pisq = 1./(2.*np.pi**2)
    3231
    33 class PDB_ReaderClass(G2IO.ImportPhase):
     32class PDB_ReaderClass(G2obj.ImportPhase):
    3433    'Routine to import Phase information from a PDB file'
    3534    def __init__(self):
     
    106105                        E,SGData = G2spc.SpcGroup(SpGrp)
    107106                    else:
    108                         SGData = G2IO.SGData # P 1
     107                        SGData = G2obj.P1SGData # P 1
    109108                        self.warnings += '\nThe space group was not interpreted and has been set to "P 1".'
    110109                        self.warnings += "Change this in phase's General tab."           
     
    119118                    self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". '
    120119                    self.warnings += "Change this in phase's General tab."
    121                     SGData = G2IO.SGData # P 1
     120                    SGData = G2obj.P1SGData # P 1
    122121                XYZ = [float(S[31:39]),float(S[39:47]),float(S[47:55])]
    123122                XYZ = np.inner(AB,XYZ)
     
    155154        if not cell:
    156155            raise self.ImportException("No cell (CRYST entry) found")
    157         Phase = G2IO.SetNewPhase(Name=PhaseName,SGData=SGData,cell=cell+[Volume,])
     156        Phase = G2obj.SetNewPhase(Name=PhaseName,SGData=SGData,cell=cell+[Volume,])
    158157        Phase['General']['Type'] = 'macromolecular'
    159158        Phase['General']['AtomPtrs'] = [6,4,10,12]
     
    161160        return Phase
    162161
    163 class EXP_ReaderClass(G2IO.ImportPhase):
     162class EXP_ReaderClass(G2obj.ImportPhase):
    164163    'Routine to import Phase information from GSAS .EXP files'
    165164    def __init__(self):
     
    246245                E,SGData = G2spc.SpcGroup(SpGrp)
    247246                if E:
    248                     SGData = G2IO.SGData # P 1 -- unlikely to need this!
     247                    SGData = G2obj.P1SGData # P 1 -- unlikely to need this!
    249248                    self.warnings += '\nThe GSAS space group was not interpreted(!) and has been set to "P 1".'
    250249                    self.warnings += "Change this in phase's General tab."                       
     
    330329        if not Atoms:
    331330            raise self.ImportException("No atoms found in phase")
    332         Phase = G2IO.SetNewPhase(Name=PhaseName,SGData=SGData,cell=abc+angles+[Volume,])
     331        Phase = G2obj.SetNewPhase(Name=PhaseName,SGData=SGData,cell=abc+angles+[Volume,])
    333332        general = Phase['General']
    334333        general['Type'] = Ptype
     
    345344        return Phase
    346345
    347 class JANA_ReaderClass(G2IO.ImportPhase):
     346class JANA_ReaderClass(G2obj.ImportPhase):
    348347    'Routine to import Phase information from a JANA2006 file'
    349348    def __init__(self):
     
    430429                        E,SGData = G2spc.SpcGroup(SpGrp)
    431430                    else:
    432                         SGData = G2IO.SGData # P 1
     431                        SGData = G2obj.P1SGData # P 1
    433432                        self.warnings += '\nThe space group was not interpreted and has been set to "P 1".'
    434433                        self.warnings += "Change this in phase's General tab."           
     
    450449            self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". '
    451450            self.warnings += "Change this in phase's General tab."
    452             SGData = G2IO.SGData # P 1
     451            SGData = G2obj.P1SGData # P 1
    453452        waveTypes = ['Fourier','Sawtooth','ZigZag',]
    454453        filename2 = os.path.splitext(filename)[0]+'.m40'
     
    544543        if not cell:
    545544            raise self.ImportException("No cell found")
    546         Phase = G2IO.SetNewPhase(Name=Title,SGData=SGData,cell=cell+[Volume,])
     545        Phase = G2obj.SetNewPhase(Name=Title,SGData=SGData,cell=cell+[Volume,])
    547546        Phase['General']['Type'] = Type
    548547        Phase['General']['Modulated'] = True
  • trunk/imports/G2phase_CIF.py

    r2738 r2817  
    3333import CifFile as cif # PyCifRW from James Hester
    3434
    35 class CIFPhaseReader(G2IO.ImportPhase):
     35class CIFPhaseReader(G2obj.ImportPhase):
    3636    'Implements a phase importer from a possibly multi-block CIF file'
    3737    def __init__(self):
     
    4848    def Reader(self,filename,filepointer, ParentFrame=None, usedRanIdList=[], **unused):
    4949        self.isodistort_warnings = ''
    50         self.Phase = G2IO.SetNewPhase(Name='new phase',SGData=G2IO.P1SGData) # create a new empty phase dict
     50        self.Phase = G2obj.SetNewPhase(Name='new phase') # create a new empty phase dict
    5151        # make sure the ranId is really unique!
    5252        while self.Phase['ranId'] in usedRanIdList:
     
    6969            '_chemical_formula_sum'
    7070            )
    71         self.ShowBusy() # this can take a while
    72         cf = G2IO.ReadCIF(filename)
    73         self.DoneBusy()
     71        cf = G2obj.ReadCIF(filename)
    7472        # scan blocks for structural info
    7573        self.errors = 'Error during scan of blocks for datasets'
     
    113111                if not sg: sg = cf[blknm].get("_space_group_name_H-M_alt",'')
    114112                if sg: choice[-1] += ', (' + sg.strip() + ')'
    115             selblk = self.PhaseSelector(
     113            selblk = G2IO.PhaseSelector(
    116114                choice,
    117115                ParentFrame=ParentFrame,
     
    154152                    self.warnings += '\nAre there spaces separating axial fields?\n\nError msg: '
    155153                    self.warnings += G2spc.SGErrors(E)
    156                 SGData = G2IO.SGData # P 1
     154                SGData = G2obj.P1SGData # P 1
    157155            self.Phase['General']['SGData'] = SGData
    158156            # cell parameters
  • trunk/imports/G2phase_GPX.py

    r2738 r2817  
    1818import cPickle
    1919import random as ran
     20import GSASIIobj as G2obj
    2021import GSASIIIO as G2IO
    2122import GSASIIstrIO as G2stIO
     
    2324GSASIIpath.SetVersionNumber("$Revision$")
    2425
    25 class PhaseReaderClass(G2IO.ImportPhase):
     26class PhaseReaderClass(G2obj.ImportPhase):
    2627    'Opens a .GPX file and pulls out a selected phase'
    2728    def __init__(self):
     
    5657            selblk = 0
    5758        else:                       # choose from options               
    58             selblk = self.PhaseSelector(
     59            selblk = G2IO.PhaseSelector(
    5960                phasenames,
    6061                ParentFrame=ParentFrame,
  • trunk/imports/G2phase_INS.py

    r2738 r2817  
    1818import numpy as np
    1919import random as ran
    20 import GSASIIIO as G2IO
     20import GSASIIobj as G2obj
    2121import GSASIIspc as G2spc
    2222import GSASIIlattice as G2lat
     
    2424GSASIIpath.SetVersionNumber("$Revision: 1812 $")
    2525
    26 class PhaseReaderClass(G2IO.ImportPhase):
     26class PhaseReaderClass(G2obj.ImportPhase):
    2727    'Opens a .INS file and pulls out a selected phase'
    2828    def __init__(self):
     
    8787                Volume = G2lat.calc_V(G2lat.cell2A(cell))
    8888                AA,AB = G2lat.cell2AB(cell)
    89                 SGData = G2IO.SGData # P 1
     89                SGData = G2obj.P1SGData # P 1
    9090                self.warnings += '\nThe space group is not given in an ins file and has been set to "P 1".'
    9191                self.warnings += "\nChange this in phase's General tab; NB: it might be in the Phase name."
     
    139139        file.close()
    140140        self.errors = 'Error after read complete'
    141         Phase = G2IO.SetNewPhase(Name='ShelX phase',SGData=SGData,cell=cell+[Volume,])
     141        Phase = G2obj.SetNewPhase(Name='ShelX phase',SGData=SGData,cell=cell+[Volume,])
    142142        Phase['General']['Name'] = Title
    143143        Phase['General']['Type'] = 'nuclear'
  • trunk/imports/G2pwd_BrukerRAW.py

    r2811 r2817  
    1919import struct as st
    2020import numpy as np
    21 import GSASIIIO as G2IO
     21import GSASIIobj as G2obj
    2222import GSASIIpath
    2323GSASIIpath.SetVersionNumber("$Revision: 1620 $")
    24 class raw_ReaderClass(G2IO.ImportPowderData):
     24class raw_ReaderClass(G2obj.ImportPowderData):
    2525    'Routines to import powder data from a binary Bruker .RAW file'
    2626    def __init__(self):
  • trunk/imports/G2pwd_CIF.py

    r2738 r2817  
    1616import numpy as np
    1717import os.path
     18import GSASIIobj as G2obj
    1819import GSASIIIO as G2IO
    1920import CifFile as cif # PyCifRW from James Hester
     
    2122GSASIIpath.SetVersionNumber("$Revision$")
    2223
    23 class CIFpwdReader(G2IO.ImportPowderData):
     24class CIFpwdReader(G2obj.ImportPowderData):
    2425    'Routines to import powder data from a CIF file'
    2526    def __init__(self):
     
    9394            selections = rdbuffer.get('selections')
    9495        if cf is None:
    95             self.ShowBusy() # this can take a while
    9696            print "Starting parse of CIF file"
    97             cf = G2IO.ReadCIF(filename)
    98             self.DoneBusy()
     97            cf = G2obj.ReadCIF(filename)
    9998            print "CIF file parsed"
    10099        # scan all blocks for sets of data
     
    179178                    'Block '+str(blk)+', '+str(l)+' points. X='+sx+' & Y='+sy
    180179                    )
    181             selections = self.MultipleBlockSelector(
     180            selections = G2IO.MultipleBlockSelector(
    182181                choices,
    183182                ParentFrame=ParentFrame,
     
    218217            chlbls.append('Divide intensities by data item')
    219218            choices.append(['none']+modch)
    220             res = self.MultipleChoicesDialog(choices,chlbls)
     219            res = G2IO.MultipleChoicesSelector(choices,chlbls)
    221220            if not res:
    222221                self.errors = "Abort: data items not selected"
     
    225224
    226225        # now read in the values
    227         self.ShowBusy() # this can also take a while
    228226        # x-values
    229227        xcf = xch[xi]
     
    300298            w /= np.array(vl)
    301299        N = len(x)
    302         self.DoneBusy()
    303300        print "CIF file, read from selected block"
    304301
  • trunk/imports/G2pwd_FP.py

    r2802 r2817  
    1818import os.path as ospath
    1919import numpy as np
    20 import GSASIIIO as G2IO
     20import GSASIIobj as G2obj
    2121import GSASIIpath
    2222GSASIIpath.SetVersionNumber("$Revision: 1620 $")
    23 class xye_ReaderClass(G2IO.ImportPowderData):
     23class xye_ReaderClass(G2obj.ImportPowderData):
    2424    'Routines to import powder data from a FullProf 1-10 column .dat file'
    2525    def __init__(self):
  • trunk/imports/G2pwd_GPX.py

    r2738 r2817  
    1313
    1414'''
    15 import sys
    1615import cPickle
    1716import numpy as np
     17import GSASIIobj as G2obj
    1818import GSASIIIO as G2IO
    1919import GSASIIpath
    2020GSASIIpath.SetVersionNumber("$Revision$")
    2121
    22 class GSAS2_ReaderClass(G2IO.ImportPowderData):
     22class GSAS2_ReaderClass(G2obj.ImportPowderData):
    2323    """Routines to import powder data from a GSAS-II file
    2424    This should work to pull data out from a out of date .GPX file
     
    8282            if self.repeatcount >= len(selections): self.repeat = False
    8383        else:                       # choose from options               
    84             selections = self.MultipleBlockSelector(
     84            selections = G2IO.MultipleBlockSelector(
    8585                histnames,
    8686                ParentFrame=ParentFrame,
  • trunk/imports/G2pwd_Panalytical.py

    r2552 r2817  
    77# $Id: $
    88########### SVN repository information ###################
    9 import os
     9
    1010import os.path as ospath
    1111import xml.etree.ElementTree as ET
    1212import numpy as np
    13 import GSASIIIO as G2IO
     13import GSASIIobj as G2obj
    1414import GSASIIpath
    1515GSASIIpath.SetVersionNumber("$Revision: $")
    16 class Panalytical_ReaderClass(G2IO.ImportPowderData):
     16class Panalytical_ReaderClass(G2obj.ImportPowderData):
    1717    '''Routines to import powder data from a Pananalytical.xrdm (xml) file.
    1818   
  • trunk/imports/G2pwd_csv.py

    r2738 r2817  
    1818import os.path as ospath
    1919import numpy as np
    20 import GSASIIIO as G2IO
     20import GSASIIobj as G2obj
    2121import GSASIIpath
    2222GSASIIpath.SetVersionNumber("$Revision$")
    23 class csv_ReaderClass(G2IO.ImportPowderData):
     23class csv_ReaderClass(G2obj.ImportPowderData):
    2424    'Routines to import powder data from a .xye file'
    2525    def __init__(self):
  • trunk/imports/G2pwd_fxye.py

    r2738 r2817  
    1414
    1515'''
    16 import sys
    1716import os.path as ospath
    1817import numpy as np
     18import GSASIIobj as G2obj
    1919import GSASIIIO as G2IO
    2020import GSASIIpath
    2121GSASIIpath.SetVersionNumber("$Revision$")
    2222
    23 class GSAS_ReaderClass(G2IO.ImportPowderData):
     23class GSAS_ReaderClass(G2obj.ImportPowderData):
    2424    'Routines to import powder data from a GSAS files'
    2525    def __init__(self):
     
    323323        else:                       # choose from options
    324324            if not len(self.selections):    #use previous selection, otherwise...
    325                 self.selections = self.MultipleBlockSelector(
     325                self.selections = G2IO.MultipleBlockSelector(
    326326                    Banks,
    327327                    ParentFrame=ParentFrame,
  • trunk/imports/G2pwd_rigaku.py

    r2516 r2817  
    77# $Id: $
    88########### SVN repository information ###################
    9 import sys
     9
    1010import os
    1111import numpy as np
    12 import GSASIIIO as G2IO
     12import GSASIIobj as G2obj
    1313import GSASIIpath
    1414GSASIIpath.SetVersionNumber("$Revision: $")
    15 class Rigaku_ReaderClass(G2IO.ImportPowderData):
     15class Rigaku_ReaderClass(G2obj.ImportPowderData):
    1616    '''Routines to import powder data from a Rigaku .txt file with an angle and
    1717    then 1 or 11(!) intensity values on the line. The example file is proceeded
  • trunk/imports/G2pwd_xye.py

    r2783 r2817  
    1717import os.path as ospath
    1818import numpy as np
    19 import GSASIIIO as G2IO
     19import GSASIIobj as G2obj
    2020import GSASIIpath
    2121GSASIIpath.SetVersionNumber("$Revision$")
    22 class xye_ReaderClass(G2IO.ImportPowderData):
     22class xye_ReaderClass(G2obj.ImportPowderData):
    2323    'Routines to import powder data from a .xye/.chi file'
    2424    def __init__(self):
  • trunk/imports/G2rfd_xye.py

    r2808 r2817  
    1818import os.path as ospath
    1919import numpy as np
    20 import GSASIIIO as G2IO
     20import GSASIIobj as G2obj
    2121import GSASIIpath
    2222GSASIIpath.SetVersionNumber("$Revision: 2738 $")
     
    2525fourpi = 4.0*np.pi
    2626
    27 class txt_XRayReaderClass(G2IO.ImportReflectometryData):
     27class txt_XRayReaderClass(G2obj.ImportReflectometryData):
    2828    'Routines to import X-ray q REFD data from a .xrfd or .xdat file'
    2929    def __init__(self):
     
    125125        return True
    126126
    127 class txt_NeutronReaderClass(G2IO.ImportReflectometryData):
     127class txt_NeutronReaderClass(G2obj.ImportReflectometryData):
    128128    'Routines to import neutron q REFD data from a .nrfd or .ndat file'
    129129    def __init__(self):
     
    225225        return True
    226226
    227 class txt_XRayThetaReaderClass(G2IO.ImportReflectometryData):
     227class txt_XRayThetaReaderClass(G2obj.ImportReflectometryData):
    228228    'Routines to import X-ray theta REFD data from a .xtrfd or .xtdat file'
    229229    def __init__(self):
  • trunk/imports/G2sad_xye.py

    r2738 r2817  
    1616'''
    1717
    18 import sys
    1918import os.path as ospath
    2019import numpy as np
    21 import GSASIIIO as G2IO
     20import GSASIIobj as G2obj
    2221import GSASIIpath
    2322GSASIIpath.SetVersionNumber("$Revision$")
    2423npasind = lambda x: 180.*np.arcsin(x)/np.pi
    2524
    26 class txt_XRayReaderClass(G2IO.ImportSmallAngleData):
     25class txt_XRayReaderClass(G2obj.ImportSmallAngleData):
    2726    'Routines to import X-ray q SAXD data from a .xsad or .xdat file'
    2827    def __init__(self):
     
    114113        return True
    115114
    116 class txt_nmXRayReaderClass(G2IO.ImportSmallAngleData):
     115class txt_nmXRayReaderClass(G2obj.ImportSmallAngleData):
    117116    'Routines to import X-ray q SAXD data from a .xsad or .xdat file, q in nm-1'
    118117    def __init__(self):
     
    204203        return True
    205204
    206 class txt_CWNeutronReaderClass(G2IO.ImportSmallAngleData):
     205class txt_CWNeutronReaderClass(G2obj.ImportSmallAngleData):
    207206    'Routines to import neutron CW q SAXD data from a .nsad or .ndat file'
    208207    def __init__(self):
     
    296295        return True
    297296
    298 class txt_nmCWNeutronReaderClass(G2IO.ImportSmallAngleData):
     297class txt_nmCWNeutronReaderClass(G2obj.ImportSmallAngleData):
    299298    'Routines to import neutron CW q in nm-1 SAXD data from a .nsad or .ndat file'
    300299    def __init__(self):
  • trunk/imports/G2sfact.py

    r2738 r2817  
    1616import sys
    1717import numpy as np
    18 import GSASIIIO as G2IO
     18import GSASIIobj as G2obj
    1919import GSASIIpath
    2020GSASIIpath.SetVersionNumber("$Revision$")
     
    4343
    4444
    45 class HKLF_ReaderClass(G2IO.ImportStructFactor):
     45class HKLF_ReaderClass(G2obj.ImportStructFactor):
    4646    'Routines to import F, sig(F) reflections from a HKLF file'
    4747    def __init__(self):
     
    7777        return True
    7878
    79 class HKLMF_ReaderClass(G2IO.ImportStructFactor):
     79class HKLMF_ReaderClass(G2obj.ImportStructFactor):
    8080    'Routines to import F, reflections from a REMOS HKLMF file'
    8181    def __init__(self):
     
    113113        return True
    114114
    115 class SHELX4_ReaderClass(G2IO.ImportStructFactor):
     115class SHELX4_ReaderClass(G2obj.ImportStructFactor):
    116116    'Routines to import F**2, sig(F**2) reflections from a Shelx HKLF 4 file'
    117117    def __init__(self):
     
    156156        return True
    157157           
    158 class SHELX5_ReaderClass(G2IO.ImportStructFactor):
     158class SHELX5_ReaderClass(G2obj.ImportStructFactor):
    159159    'Routines to import F**2, sig(F**2) twin/incommensurate reflections from a fixed format SHELX HKLF5 file'
    160160    def __init__(self):
     
    252252        return True
    253253
    254 class SHELX6_ReaderClass(G2IO.ImportStructFactor):
     254class SHELX6_ReaderClass(G2obj.ImportStructFactor):
    255255    'Routines to import F**2, sig(F**2) twin/incommensurate reflections from a fixed format SHELX HKLF6 file'
    256256    def __init__(self):
     
    337337        return True
    338338
    339 class M90_ReaderClass(G2IO.ImportStructFactor):
     339class M90_ReaderClass(G2obj.ImportStructFactor):
    340340    'Routines to import F**2, sig(F**2) reflections from a JANA M90 file'
    341341    def __init__(self):
     
    402402        return True
    403403           
    404 class NT_HKLF2_ReaderClass(G2IO.ImportStructFactor):
     404class NT_HKLF2_ReaderClass(G2obj.ImportStructFactor):
    405405    'Routines to import neutron TOF F**2, sig(F**2) reflections from a HKLF file'
    406406    def __init__(self):
     
    467467        return True
    468468
    469 class NT_JANA2K_ReaderClass(G2IO.ImportStructFactor):
     469class NT_JANA2K_ReaderClass(G2obj.ImportStructFactor):
    470470    'Routines to import neutron TOF F**2, sig(F**2) reflections from a JANA2000 file'
    471471    def __init__(self):
     
    530530        return True
    531531
    532 class ISIS_SXD_INT_ReaderClass(G2IO.ImportStructFactor):
     532class ISIS_SXD_INT_ReaderClass(G2obj.ImportStructFactor):
    533533    'Routines to import neutron TOF F**2, sig(F**2) reflections from a ISIS int file'
    534534    def __init__(self):
  • trunk/imports/G2sfact_CIF.py

    r2738 r2817  
    1515# routines to read in structure factors from a CIF
    1616#
    17 import sys
    1817import numpy as np
    1918import os.path
     19import GSASIIobj as G2obj
    2020import GSASIIIO as G2IO
    2121import GSASIIpath
     
    2323import CifFile as cif # PyCifRW from James Hester
    2424
    25 class CIFhklReader(G2IO.ImportStructFactor):
     25class CIFhklReader(G2obj.ImportStructFactor):
    2626    'Routines to import Phase information from a CIF file'
    2727    def __init__(self):
     
    9494            print 'Reusing previously parsed CIF'
    9595        if cf is None:
    96             self.ShowBusy() # this can take a while
    97             cf = G2IO.ReadCIF(filename)
    98             self.DoneBusy()
     96            cf = G2obj.ReadCIF(filename)
    9997        # scan blocks for reflections
    10098        self.errors = 'Error during scan of blocks for datasets'
     
    162160                if self.repeatcount >= len(blklist): self.repeat = False
    163161            else:
    164                 selblk = self.BlockSelector(
     162                selblk = G2IO.BlockSelector(
    165163                    choice,
    166164                    ParentFrame=ParentFrame,
Note: See TracChangeset for help on using the changeset viewer.