Changeset 482


Ignore:
Timestamp:
Feb 13, 2012 11:33:35 AM (10 years ago)
Author:
vondreele
Message:

move FileDlgFixExt? to G2IO
begin to add a save selected seq results to file
move IO routines called in G2struct back there
remove wx stuff from G2pwd & G2struct
put progress bar in G2pwdGUI (not G2pwd)

Location:
trunk
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r481 r482  
    9090] = [wx.NewId() for _init_coll_Export_Items in range(7)]
    9191
    92 def FileDlgFixExt(dlg,file):            #this is needed to fix a problem in linux wx.FileDialog
    93     ext = dlg.GetWildcard().split('|')[2*dlg.GetFilterIndex()+1].strip('*')
    94     if ext not in file:
    95         file += ext
    96     return file
    97    
    9892class GSASII(wx.Frame):
    9993   
     
    10421036                        if dlg.ShowModal() == wx.ID_OK:
    10431037                            newimagefile = dlg.GetPath()
    1044                             newimagefile = FileDlgFixExt(dlg,newimagefile)
     1038                            newimagefile = G2IO.FileDlgFixExt(dlg,newimagefile)
    10451039                            G2IO.PutG2Image(newimagefile,Comments,Data,Npix,newImage)
    10461040                            Imax = np.amax(newImage)
     
    12551249                if dlg.ShowModal() == wx.ID_OK:
    12561250                    self.GSASprojectfile = dlg.GetPath()
    1257                     self.GSASprojectfile = FileDlgFixExt(dlg,self.GSASprojectfile)
     1251                    self.GSASprojectfile = G2IO.FileDlgFixExt(dlg,self.GSASprojectfile)
    12581252                    self.dirname = dlg.GetDirectory()
    12591253                    G2IO.ProjFileOpen(self)
     
    13121306            if dlg.ShowModal() == wx.ID_OK:
    13131307                self.GSASprojectfile = dlg.GetPath()
    1314                 self.GSASprojectfile = FileDlgFixExt(dlg,self.GSASprojectfile)
     1308                self.GSASprojectfile = G2IO.FileDlgFixExt(dlg,self.GSASprojectfile)
    13151309                self.PatternTree.SetItemText(self.root,'Loaded Data: '+self.GSASprojectfile)
    13161310                G2IO.ProjFileSave(self)
     
    15471541                if dlg.ShowModal() == wx.ID_OK:
    15481542                    powderfile = dlg.GetPath()
    1549                     powderfile = FileDlgFixExt(dlg,powderfile)
     1543                    powderfile = G2IO.FileDlgFixExt(dlg,powderfile)
    15501544                    if 'fxye' in powderfile:
    15511545                        G2IO.powderFxyeSave(self,exports,powderfile)
     
    15611555            if dlg.ShowModal() == wx.ID_OK:
    15621556                self.peaklistfile = dlg.GetPath()
    1563                 self.peaklistfile = FileDlgFixExt(dlg,self.peaklistfile)
     1557                self.peaklistfile = G2IO.FileDlgFixExt(dlg,self.peaklistfile)
    15641558                file = open(self.peaklistfile,'w')               
    15651559                item, cookie = self.PatternTree.GetFirstChild(self.root)
  • trunk/GSASIIIO.py

    r475 r482  
    3636        return 0
    3737
     38def FileDlgFixExt(dlg,file):
     39    #this is needed to fix a problem in linux wx.FileDialog
     40    ext = dlg.GetWildcard().split('|')[2*dlg.GetFilterIndex()+1].strip('*')
     41    if ext not in file:
     42        file += ext
     43    return file
     44   
    3845def SelectPowderData(G2frame, filename):
    3946    """Selects banks of data from a filename of any GSAS powder data format
     
    849856        print 'project save successful'
    850857
    851 def GetControls(GPXfile):
    852     ''' Returns dictionary of control items found in GSASII gpx file
    853     input:
    854         GPXfile = .gpx full file name
    855     return:
    856         Controls = dictionary of control items
    857     '''
    858     Controls = {'deriv type':'analytical','min dM/M':0.0001,'shift factor':1.}
    859     file = open(GPXfile,'rb')
    860     while True:
    861         try:
    862             data = cPickle.load(file)
    863         except EOFError:
    864             break
    865         datum = data[0]
    866         if datum[0] == 'Controls':
    867             Controls.update(datum[1])
    868     file.close()
    869     return Controls
    870    
    871 def GetConstraints(GPXfile):
    872     constList = []
    873     file = open(GPXfile,'rb')
    874     while True:
    875         try:
    876             data = cPickle.load(file)
    877         except EOFError:
    878             break
    879         datum = data[0]
    880         if datum[0] == 'Constraints':
    881             constDict = datum[1]
    882             for item in constDict:
    883                 constList += constDict[item]
    884     file.close()
    885     constDict = []
    886     constFlag = []
    887     fixedList = []
    888     for item in constList:
    889         if item[-2]:
    890             fixedList.append(str(item[-2]))
    891         else:
    892             fixedList.append('0')
    893         if item[-1]:
    894             constFlag.append(['VARY'])
    895         else:
    896             constFlag.append([])
    897         itemDict = {}
    898         for term in item[:-2]:
    899             itemDict[term[1]] = term[0]
    900         constDict.append(itemDict)
    901     return constDict,constFlag,fixedList
    902    
    903 def GetPhaseNames(GPXfile):
    904     ''' Returns a list of phase names found under 'Phases' in GSASII gpx file
    905     input:
    906         GPXfile = gpx full file name
    907     return:
    908         PhaseNames = list of phase names
    909     '''
    910     file = open(GPXfile,'rb')
    911     PhaseNames = []
    912     while True:
    913         try:
    914             data = cPickle.load(file)
    915         except EOFError:
    916             break
    917         datum = data[0]
    918         if 'Phases' == datum[0]:
    919             for datus in data[1:]:
    920                 PhaseNames.append(datus[0])
    921     file.close()
    922     return PhaseNames
    923 
    924 def GetAllPhaseData(GPXfile,PhaseName):
    925     ''' Returns the entire dictionary for PhaseName from GSASII gpx file
    926     input:
    927         GPXfile = gpx full file name
    928         PhaseName = phase name
    929     return:
    930         phase dictionary
    931     '''       
    932     file = open(GPXfile,'rb')
    933     General = {}
    934     Atoms = []
    935     while True:
    936         try:
    937             data = cPickle.load(file)
    938         except EOFError:
    939             break
    940         datum = data[0]
    941         if 'Phases' == datum[0]:
    942             for datus in data[1:]:
    943                 if datus[0] == PhaseName:
    944                     break
    945     file.close()
    946     return datus[1]
    947    
    948 def GetHistograms(GPXfile,hNames):
    949     """ Returns a dictionary of histograms found in GSASII gpx file
    950     input:
    951         GPXfile = .gpx full file name
    952         hNames = list of histogram names
    953     return:
    954         Histograms = dictionary of histograms (types = PWDR & HKLF)
    955     """
    956     file = open(GPXfile,'rb')
    957     Histograms = {}
    958     while True:
    959         try:
    960             data = cPickle.load(file)
    961         except EOFError:
    962             break
    963         datum = data[0]
    964         hist = datum[0]
    965         if hist in hNames:
    966             if 'PWDR' in hist[:4]:
    967                 PWDRdata = {}
    968                 PWDRdata['Data'] = datum[1][1]          #powder data arrays
    969                 PWDRdata[data[2][0]] = data[2][1]       #Limits
    970                 PWDRdata[data[3][0]] = data[3][1]       #Background
    971                 PWDRdata[data[4][0]] = data[4][1]       #Instrument parameters
    972                 PWDRdata[data[5][0]] = data[5][1]       #Sample parameters
    973                 try:
    974                     PWDRdata[data[9][0]] = data[9][1]       #Reflection lists might be missing
    975                 except IndexError:
    976                     PWDRdata['Reflection lists'] = {}
    977    
    978                 Histograms[hist] = PWDRdata
    979             elif 'HKLF' in hist[:4]:
    980                 HKLFdata = []
    981                 datum = data[0]
    982                 HKLFdata = datum[1:][0]
    983                 Histograms[hist] = HKLFdata           
    984     file.close()
    985     return Histograms
    986    
    987 def GetHistogramNames(GPXfile,hType):
    988     """ Returns a list of histogram names found in GSASII gpx file
    989     input:
    990         GPXfile = .gpx full file name
    991         hType = list ['PWDR','HKLF']
    992     return:
    993         HistogramNames = list of histogram names (types = PWDR & HKLF)
    994     """
    995     file = open(GPXfile,'rb')
    996     HistogramNames = []
    997     while True:
    998         try:
    999             data = cPickle.load(file)
    1000         except EOFError:
    1001             break
    1002         datum = data[0]
    1003         if datum[0][:4] in hType:
    1004             HistogramNames.append(datum[0])
    1005     file.close()
    1006     return HistogramNames
    1007    
    1008 def GetUsedHistogramsAndPhases(GPXfile):
    1009     ''' Returns all histograms that are found in any phase
    1010     and any phase that uses a histogram
    1011     input:
    1012         GPXfile = .gpx full file name
    1013     return:
    1014         Histograms = dictionary of histograms as {name:data,...}
    1015         Phases = dictionary of phases that use histograms
    1016     '''
    1017     phaseNames = GetPhaseNames(GPXfile)
    1018     histoList = GetHistogramNames(GPXfile,['PWDR','HKLF'])
    1019     allHistograms = GetHistograms(GPXfile,histoList)
    1020     phaseData = {}
    1021     for name in phaseNames:
    1022         phaseData[name] =  GetAllPhaseData(GPXfile,name)
    1023     Histograms = {}
    1024     Phases = {}
    1025     for phase in phaseData:
    1026         Phase = phaseData[phase]
    1027         if Phase['Histograms']:
    1028             if phase not in Phases:
    1029                 pId = phaseNames.index(phase)
    1030                 Phase['pId'] = pId
    1031                 Phases[phase] = Phase
    1032             for hist in Phase['Histograms']:
    1033                 if hist not in Histograms:
    1034                     Histograms[hist] = allHistograms[hist]
    1035                     #future restraint, etc. histograms here           
    1036                     hId = histoList.index(hist)
    1037                     Histograms[hist]['hId'] = hId
    1038     return Histograms,Phases
    1039    
    1040 def GPXBackup(GPXfile,makeBack=True):
    1041     import distutils.file_util as dfu
    1042     GPXpath,GPXname = ospath.split(GPXfile)
    1043     if GPXpath == '': GPXpath = '.'
    1044     Name = ospath.splitext(GPXname)[0]
    1045     files = os.listdir(GPXpath)
    1046     last = 0
    1047     for name in files:
    1048         name = name.split('.')
    1049         if len(name) >= 3 and name[0] == Name and 'bak' in name[-2]:
    1050             if makeBack:
    1051                 last = max(last,int(name[-2].strip('bak'))+1)
    1052             else:
    1053                 last = max(last,int(name[-2].strip('bak')))
    1054     GPXback = ospath.join(GPXpath,GPXname.rstrip('.'.join(name[-2:]))+'.bak'+str(last)+'.gpx')
    1055     dfu.copy_file(GPXfile,GPXback)
    1056     return GPXback
    1057        
    1058 def SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,CovData,makeBack=True):
    1059     ''' Updates gpxfile from all histograms that are found in any phase
    1060     and any phase that used a histogram
    1061     input:
    1062         GPXfile = .gpx full file name
    1063         Histograms = dictionary of histograms as {name:data,...}
    1064         Phases = dictionary of phases that use histograms
    1065         CovData = dictionary of refined variables, varyList, & covariance matrix
    1066         makeBack = True if new backup of .gpx file is to be made; else use the last one made
    1067     '''
    1068                        
    1069     GPXback = GPXBackup(GPXfile,makeBack)
    1070     print '\n',135*'-'
    1071     print 'Read from file:',GPXback
    1072     print 'Save to file  :',GPXfile
    1073     infile = open(GPXback,'rb')
    1074     outfile = open(GPXfile,'wb')
    1075     while True:
    1076         try:
    1077             data = cPickle.load(infile)
    1078         except EOFError:
    1079             break
    1080         datum = data[0]
    1081 #        print 'read: ',datum[0]
    1082         if datum[0] == 'Phases':
    1083             for iphase in range(len(data)):
    1084                 if data[iphase][0] in Phases:
    1085                     phaseName = data[iphase][0]
    1086                     data[iphase][1].update(Phases[phaseName])
    1087         elif datum[0] == 'Covariance':
    1088             data[0][1] = CovData
    1089         try:
    1090             histogram = Histograms[datum[0]]
    1091 #            print 'found ',datum[0]
    1092             data[0][1][1] = histogram['Data']
    1093             for datus in data[1:]:
    1094 #                print '    read: ',datus[0]
    1095                 if datus[0] in ['Background','Instrument Parameters','Sample Parameters','Reflection Lists']:
    1096                     datus[1] = histogram[datus[0]]
    1097         except KeyError:
    1098             pass
    1099                                
    1100         cPickle.dump(data,outfile,1)
    1101     infile.close()
    1102     outfile.close()
    1103     print 'GPX file save successful'
    1104    
    1105 def SetSeqResult(GPXfile,Histograms,SeqResult):
    1106     GPXback = GPXBackup(GPXfile)
    1107     print '\n',135*'-'
    1108     print 'Read from file:',GPXback
    1109     print 'Save to file  :',GPXfile
    1110     infile = open(GPXback,'rb')
    1111     outfile = open(GPXfile,'wb')
    1112     while True:
    1113         try:
    1114             data = cPickle.load(infile)
    1115         except EOFError:
    1116             break
    1117         datum = data[0]
    1118         if datum[0] == 'Sequental results':
    1119             data[0][1] = SeqResult
    1120         try:
    1121             histogram = Histograms[datum[0]]
    1122             data[0][1][1] = histogram['Data']
    1123             for datus in data[1:]:
    1124                 if datus[0] in ['Background','Instrument Parameters','Sample Parameters','Reflection Lists']:
    1125                     datus[1] = histogram[datus[0]]
    1126         except KeyError:
    1127             pass
    1128                                
    1129         cPickle.dump(data,outfile,1)
    1130     infile.close()
    1131     outfile.close()
    1132     print 'GPX file save successful'
    1133                        
    1134 def GetPWDRdata(GPXfile,PWDRname):
    1135     ''' Returns powder data from GSASII gpx file
    1136     input:
    1137         GPXfile = .gpx full file name
    1138         PWDRname = powder histogram name as obtained from GetHistogramNames
    1139     return:
    1140         PWDRdata = powder data dictionary with:
    1141             Data - powder data arrays, Limits, Instrument Parameters, Sample Parameters
    1142        
    1143     '''
    1144     file = open(GPXfile,'rb')
    1145     PWDRdata = {}
    1146     while True:
    1147         try:
    1148             data = cPickle.load(file)
    1149         except EOFError:
    1150             break
    1151         datum = data[0]
    1152         if datum[0] == PWDRname:
    1153             PWDRdata['Data'] = datum[1][1]          #powder data arrays
    1154             PWDRdata[data[2][0]] = data[2][1]       #Limits
    1155             PWDRdata[data[3][0]] = data[3][1]       #Background
    1156             PWDRdata[data[4][0]] = data[4][1]       #Instrument parameters
    1157             PWDRdata[data[5][0]] = data[5][1]       #Sample parameters
    1158             try:
    1159                 PWDRdata[data[9][0]] = data[9][1]       #Reflection lists might be missing
    1160             except IndexError:
    1161                 PWDRdata['Reflection lists'] = {}
    1162     file.close()
    1163     return PWDRdata
    1164    
    1165 def GetHKLFdata(GPXfile,HKLFname):
    1166     ''' Returns single crystal data from GSASII gpx file
    1167     input:
    1168         GPXfile = .gpx full file name
    1169         HKLFname = single crystal histogram name as obtained from GetHistogramNames
    1170     return:
    1171         HKLFdata = single crystal data list of reflections: for each reflection:
    1172             HKLF = [np.array([h,k,l]),FoSq,sigFoSq,FcSq,Fcp,Fcpp,phase]
    1173     '''
    1174     file = open(GPXfile,'rb')
    1175     HKLFdata = []
    1176     while True:
    1177         try:
    1178             data = cPickle.load(file)
    1179         except EOFError:
    1180             break
    1181         datum = data[0]
    1182         if datum[0] == HKLFname:
    1183             HKLFdata = datum[1:][0]
    1184     file.close()
    1185     return HKLFdata
    1186    
    1187858def SaveIntegration(G2frame,PickId,data):
    1188859    azms = G2frame.Integrate[1]
  • trunk/GSASIIgrid.py

    r478 r482  
    8585[ wxID_RESTRAINTADD,
    8686] = [wx.NewId() for _init_coll_Restraint_Items in range(1)]
     87
     88[ wxID_SAVESEQSEL,
     89] = [wx.NewId() for _init_coll_Sequential_Items in range(1)]
    8790
    8891[ wxID_SELECTPHASE,
     
    264267        self.RestraintEdit.Append(id=wxID_RESTRAINTADD, kind=wx.ITEM_NORMAL,text='Add restraint',
    265268            help='restraint dummy menu item')
     269           
     270# Sequential results
     271        self.SequentialMenu = wx.MenuBar()
     272        self.SequentialFile = wx.Menu(title='')
     273        self.SequentialMenu.Append(menu=self.SequentialFile, title='File')
     274        self.SequentialMenu.Append(menu=MyHelp(self,helpType='Sequential'),title='&Help')
     275        self.SequentialFile.Append(id=wxID_SAVESEQSEL, kind=wx.ITEM_NORMAL,text='Save...',
     276            help='Save selected sequential refinement results')
    266277           
    267278# PDR / Limits
     
    924935            name = histNames[rows[0]]
    925936            G2plt.PlotCovariance(G2frame,Data=data[name])
     937           
     938    def OnSaveSelSeq(event):       
     939        cols = G2frame.dataDisplay.GetSelectedCols()
     940        if cols:
     941            numRows = G2frame.SeqTable.GetNumberRows()
     942            dataNames = []
     943            saveNames = [G2frame.SeqTable.GetRowLabelValue(r) for r in range(numRows)]
     944            saveData = []
     945            for col in cols:
     946                dataNames.append(G2frame.SeqTable.GetColLabelValue(col))
     947                saveData.append(zip(G2frame.SeqTable.GetColValues(col),GetSigData(col)))
     948            saveData = np.array(saveData)
     949            dlg = wx.FileDialog(self, 'Choose text output file for your selection', '.', '',
     950                'Text output file (*.txt)|*.txt',wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.CHANGE_DIR)
     951            try:
     952                if dlg.ShowModal() == wx.ID_OK:
     953                    SeqTextFile = dlg.GetPath()
     954                    SeqTextFile = G2IO.FileDlgFixExt(dlg,SeqTextFile)
     955                    SeqFile = open(SeqTextFile,'w')
     956            finally:
     957                dlg.Destroy()
     958           
     959            print dataNames,saveData.shape
    926960               
    927961    if G2frame.dataDisplay:
     
    938972            atomList[newAtomDict[item][0]] = item
    939973    sampleParms = GetSampleParms()
    940     G2frame.dataFrame.SetMenuBar(G2frame.dataFrame.BlankMenu)
     974    G2frame.dataFrame.SetMenuBar(G2frame.dataFrame.SequentialMenu)
    941975    G2frame.dataFrame.SetLabel('Sequental refinement results')
    942976    G2frame.dataFrame.CreateStatusBar()
     977    G2frame.dataFrame.Bind(wx.EVT_MENU, OnSaveSelSeq, id=wxID_SAVESEQSEL)
    943978    colLabels = data['varyList']+atomList.keys()+cellList.keys()
    944979    Types = len(data['varyList']+atomList.keys()+cellList.keys())*[wg.GRID_VALUE_FLOAT,]
  • trunk/GSASIIpwd.py

    r453 r482  
    1111import sys
    1212import math
    13 import wx
    1413import time
    1514
     
    2322
    2423import GSASIIpath
    25 import GSASIIplot as G2plt
    2624import GSASIIlattice as G2lat
    2725import GSASIIElem as G2elem
     
    945943    parmdict.update(zip(varylist,values))
    946944   
    947 def DoPeakFit(FitPgm,Peaks,Background,Limits,Inst,data,oneCycle=False,controls=None):
     945def DoPeakFit(FitPgm,Peaks,Background,Limits,Inst,data,oneCycle=False,controls=None,dlg=None):
    948946   
    949947    def SetBackgroundParms(Background):
     
    12001198        values =  np.array(Dict2Values(parmDict, varyList))
    12011199        if FitPgm == 'LSQ':
    1202             dlg = wx.ProgressDialog('Residual','Peak fit Rwp = ',101.0,
    1203             style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT)
    1204             screenSize = wx.ClientDisplayRect()
    1205             Size = dlg.GetSize()
    1206             dlg.SetPosition(wx.Point(screenSize[2]-Size[0]-305,screenSize[1]+5))
    12071200            try:
    12081201                result = so.leastsq(errPeakProfile,values,Dfun=devPeakProfile,full_output=True,ftol=Ftol,col_deriv=True,
  • trunk/GSASIIpwdGUI.py

    r468 r482  
    120120        data = G2frame.PatternTree.GetItemPyData(PatternId)[1]
    121121        wx.BeginBusyCursor()
    122         try:
    123             G2pwd.DoPeakFit(FitPgm,peaks,background,limits,inst,data,oneCycle,controls)
     122        dlg = wx.ProgressDialog('Residual','Peak fit Rwp = ',101.0,
     123            style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT)
     124        screenSize = wx.ClientDisplayRect()
     125        Size = dlg.GetSize()
     126        dlg.SetPosition(wx.Point(screenSize[2]-Size[0]-305,screenSize[1]+5))
     127        try:
     128            G2pwd.DoPeakFit(FitPgm,peaks,background,limits,inst,data,oneCycle,controls,dlg)
    124129        finally:
    125130            wx.EndBusyCursor()   
  • trunk/GSASIIstruct.py

    r480 r482  
    88########### SVN repository information ###################
    99import sys
    10 import numpy as np
    11 import numpy.linalg as nl
     10import os
    1211import os.path as ospath
    1312import time
    1413import math
     14import cPickle
     15import numpy as np
     16import numpy.linalg as nl
     17import scipy.optimize as so
    1518import GSASIIpath
    16 import GSASIIIO as G2IO
    1719import GSASIIElem as G2el
    1820import GSASIIlattice as G2lat
     
    2123import GSASIImapvars as G2mv
    2224import GSASIImath as G2mth
    23 import scipy.optimize as so
    2425
    2526sind = lambda x: np.sin(x*np.pi/180.)
     
    3132
    3233
     34def GetControls(GPXfile):
     35    ''' Returns dictionary of control items found in GSASII gpx file
     36    input:
     37        GPXfile = .gpx full file name
     38    return:
     39        Controls = dictionary of control items
     40    '''
     41    Controls = {'deriv type':'analytical','min dM/M':0.0001,'shift factor':1.}
     42    file = open(GPXfile,'rb')
     43    while True:
     44        try:
     45            data = cPickle.load(file)
     46        except EOFError:
     47            break
     48        datum = data[0]
     49        if datum[0] == 'Controls':
     50            Controls.update(datum[1])
     51    file.close()
     52    return Controls
     53   
     54def GetConstraints(GPXfile):
     55    constList = []
     56    file = open(GPXfile,'rb')
     57    while True:
     58        try:
     59            data = cPickle.load(file)
     60        except EOFError:
     61            break
     62        datum = data[0]
     63        if datum[0] == 'Constraints':
     64            constDict = datum[1]
     65            for item in constDict:
     66                constList += constDict[item]
     67    file.close()
     68    constDict = []
     69    constFlag = []
     70    fixedList = []
     71    for item in constList:
     72        if item[-2]:
     73            fixedList.append(str(item[-2]))
     74        else:
     75            fixedList.append('0')
     76        if item[-1]:
     77            constFlag.append(['VARY'])
     78        else:
     79            constFlag.append([])
     80        itemDict = {}
     81        for term in item[:-2]:
     82            itemDict[term[1]] = term[0]
     83        constDict.append(itemDict)
     84    return constDict,constFlag,fixedList
     85   
     86def GetPhaseNames(GPXfile):
     87    ''' Returns a list of phase names found under 'Phases' in GSASII gpx file
     88    input:
     89        GPXfile = gpx full file name
     90    return:
     91        PhaseNames = list of phase names
     92    '''
     93    file = open(GPXfile,'rb')
     94    PhaseNames = []
     95    while True:
     96        try:
     97            data = cPickle.load(file)
     98        except EOFError:
     99            break
     100        datum = data[0]
     101        if 'Phases' == datum[0]:
     102            for datus in data[1:]:
     103                PhaseNames.append(datus[0])
     104    file.close()
     105    return PhaseNames
     106
     107def GetAllPhaseData(GPXfile,PhaseName):
     108    ''' Returns the entire dictionary for PhaseName from GSASII gpx file
     109    input:
     110        GPXfile = gpx full file name
     111        PhaseName = phase name
     112    return:
     113        phase dictionary
     114    '''       
     115    file = open(GPXfile,'rb')
     116    General = {}
     117    Atoms = []
     118    while True:
     119        try:
     120            data = cPickle.load(file)
     121        except EOFError:
     122            break
     123        datum = data[0]
     124        if 'Phases' == datum[0]:
     125            for datus in data[1:]:
     126                if datus[0] == PhaseName:
     127                    break
     128    file.close()
     129    return datus[1]
     130   
     131def GetHistograms(GPXfile,hNames):
     132    """ Returns a dictionary of histograms found in GSASII gpx file
     133    input:
     134        GPXfile = .gpx full file name
     135        hNames = list of histogram names
     136    return:
     137        Histograms = dictionary of histograms (types = PWDR & HKLF)
     138    """
     139    file = open(GPXfile,'rb')
     140    Histograms = {}
     141    while True:
     142        try:
     143            data = cPickle.load(file)
     144        except EOFError:
     145            break
     146        datum = data[0]
     147        hist = datum[0]
     148        if hist in hNames:
     149            if 'PWDR' in hist[:4]:
     150                PWDRdata = {}
     151                PWDRdata['Data'] = datum[1][1]          #powder data arrays
     152                PWDRdata[data[2][0]] = data[2][1]       #Limits
     153                PWDRdata[data[3][0]] = data[3][1]       #Background
     154                PWDRdata[data[4][0]] = data[4][1]       #Instrument parameters
     155                PWDRdata[data[5][0]] = data[5][1]       #Sample parameters
     156                try:
     157                    PWDRdata[data[9][0]] = data[9][1]       #Reflection lists might be missing
     158                except IndexError:
     159                    PWDRdata['Reflection lists'] = {}
     160   
     161                Histograms[hist] = PWDRdata
     162            elif 'HKLF' in hist[:4]:
     163                HKLFdata = []
     164                datum = data[0]
     165                HKLFdata = datum[1:][0]
     166                Histograms[hist] = HKLFdata           
     167    file.close()
     168    return Histograms
     169   
     170def GetHistogramNames(GPXfile,hType):
     171    """ Returns a list of histogram names found in GSASII gpx file
     172    input:
     173        GPXfile = .gpx full file name
     174        hType = list ['PWDR','HKLF']
     175    return:
     176        HistogramNames = list of histogram names (types = PWDR & HKLF)
     177    """
     178    file = open(GPXfile,'rb')
     179    HistogramNames = []
     180    while True:
     181        try:
     182            data = cPickle.load(file)
     183        except EOFError:
     184            break
     185        datum = data[0]
     186        if datum[0][:4] in hType:
     187            HistogramNames.append(datum[0])
     188    file.close()
     189    return HistogramNames
     190   
     191def GetUsedHistogramsAndPhases(GPXfile):
     192    ''' Returns all histograms that are found in any phase
     193    and any phase that uses a histogram
     194    input:
     195        GPXfile = .gpx full file name
     196    return:
     197        Histograms = dictionary of histograms as {name:data,...}
     198        Phases = dictionary of phases that use histograms
     199    '''
     200    phaseNames = GetPhaseNames(GPXfile)
     201    histoList = GetHistogramNames(GPXfile,['PWDR','HKLF'])
     202    allHistograms = GetHistograms(GPXfile,histoList)
     203    phaseData = {}
     204    for name in phaseNames:
     205        phaseData[name] =  GetAllPhaseData(GPXfile,name)
     206    Histograms = {}
     207    Phases = {}
     208    for phase in phaseData:
     209        Phase = phaseData[phase]
     210        if Phase['Histograms']:
     211            if phase not in Phases:
     212                pId = phaseNames.index(phase)
     213                Phase['pId'] = pId
     214                Phases[phase] = Phase
     215            for hist in Phase['Histograms']:
     216                if hist not in Histograms:
     217                    Histograms[hist] = allHistograms[hist]
     218                    #future restraint, etc. histograms here           
     219                    hId = histoList.index(hist)
     220                    Histograms[hist]['hId'] = hId
     221    return Histograms,Phases
     222   
     223def GPXBackup(GPXfile,makeBack=True):
     224    import distutils.file_util as dfu
     225    GPXpath,GPXname = ospath.split(GPXfile)
     226    if GPXpath == '': GPXpath = '.'
     227    Name = ospath.splitext(GPXname)[0]
     228    files = os.listdir(GPXpath)
     229    last = 0
     230    for name in files:
     231        name = name.split('.')
     232        if len(name) >= 3 and name[0] == Name and 'bak' in name[-2]:
     233            if makeBack:
     234                last = max(last,int(name[-2].strip('bak'))+1)
     235            else:
     236                last = max(last,int(name[-2].strip('bak')))
     237    GPXback = ospath.join(GPXpath,GPXname.rstrip('.'.join(name[-2:]))+'.bak'+str(last)+'.gpx')
     238    dfu.copy_file(GPXfile,GPXback)
     239    return GPXback
     240       
     241def SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,CovData,makeBack=True):
     242    ''' Updates gpxfile from all histograms that are found in any phase
     243    and any phase that used a histogram
     244    input:
     245        GPXfile = .gpx full file name
     246        Histograms = dictionary of histograms as {name:data,...}
     247        Phases = dictionary of phases that use histograms
     248        CovData = dictionary of refined variables, varyList, & covariance matrix
     249        makeBack = True if new backup of .gpx file is to be made; else use the last one made
     250    '''
     251                       
     252    GPXback = GPXBackup(GPXfile,makeBack)
     253    print '\n',135*'-'
     254    print 'Read from file:',GPXback
     255    print 'Save to file  :',GPXfile
     256    infile = open(GPXback,'rb')
     257    outfile = open(GPXfile,'wb')
     258    while True:
     259        try:
     260            data = cPickle.load(infile)
     261        except EOFError:
     262            break
     263        datum = data[0]
     264#        print 'read: ',datum[0]
     265        if datum[0] == 'Phases':
     266            for iphase in range(len(data)):
     267                if data[iphase][0] in Phases:
     268                    phaseName = data[iphase][0]
     269                    data[iphase][1].update(Phases[phaseName])
     270        elif datum[0] == 'Covariance':
     271            data[0][1] = CovData
     272        try:
     273            histogram = Histograms[datum[0]]
     274#            print 'found ',datum[0]
     275            data[0][1][1] = histogram['Data']
     276            for datus in data[1:]:
     277#                print '    read: ',datus[0]
     278                if datus[0] in ['Background','Instrument Parameters','Sample Parameters','Reflection Lists']:
     279                    datus[1] = histogram[datus[0]]
     280        except KeyError:
     281            pass
     282                               
     283        cPickle.dump(data,outfile,1)
     284    infile.close()
     285    outfile.close()
     286    print 'GPX file save successful'
     287   
     288def SetSeqResult(GPXfile,Histograms,SeqResult):
     289    GPXback = GPXBackup(GPXfile)
     290    print '\n',135*'-'
     291    print 'Read from file:',GPXback
     292    print 'Save to file  :',GPXfile
     293    infile = open(GPXback,'rb')
     294    outfile = open(GPXfile,'wb')
     295    while True:
     296        try:
     297            data = cPickle.load(infile)
     298        except EOFError:
     299            break
     300        datum = data[0]
     301        if datum[0] == 'Sequental results':
     302            data[0][1] = SeqResult
     303        try:
     304            histogram = Histograms[datum[0]]
     305            data[0][1][1] = histogram['Data']
     306            for datus in data[1:]:
     307                if datus[0] in ['Background','Instrument Parameters','Sample Parameters','Reflection Lists']:
     308                    datus[1] = histogram[datus[0]]
     309        except KeyError:
     310            pass
     311                               
     312        cPickle.dump(data,outfile,1)
     313    infile.close()
     314    outfile.close()
     315    print 'GPX file save successful'
     316                       
     317def GetPWDRdata(GPXfile,PWDRname):
     318    ''' Returns powder data from GSASII gpx file
     319    input:
     320        GPXfile = .gpx full file name
     321        PWDRname = powder histogram name as obtained from GetHistogramNames
     322    return:
     323        PWDRdata = powder data dictionary with:
     324            Data - powder data arrays, Limits, Instrument Parameters, Sample Parameters
     325       
     326    '''
     327    file = open(GPXfile,'rb')
     328    PWDRdata = {}
     329    while True:
     330        try:
     331            data = cPickle.load(file)
     332        except EOFError:
     333            break
     334        datum = data[0]
     335        if datum[0] == PWDRname:
     336            PWDRdata['Data'] = datum[1][1]          #powder data arrays
     337            PWDRdata[data[2][0]] = data[2][1]       #Limits
     338            PWDRdata[data[3][0]] = data[3][1]       #Background
     339            PWDRdata[data[4][0]] = data[4][1]       #Instrument parameters
     340            PWDRdata[data[5][0]] = data[5][1]       #Sample parameters
     341            try:
     342                PWDRdata[data[9][0]] = data[9][1]       #Reflection lists might be missing
     343            except IndexError:
     344                PWDRdata['Reflection lists'] = {}
     345    file.close()
     346    return PWDRdata
     347   
     348def GetHKLFdata(GPXfile,HKLFname):
     349    ''' Returns single crystal data from GSASII gpx file
     350    input:
     351        GPXfile = .gpx full file name
     352        HKLFname = single crystal histogram name as obtained from GetHistogramNames
     353    return:
     354        HKLFdata = single crystal data list of reflections: for each reflection:
     355            HKLF = [np.array([h,k,l]),FoSq,sigFoSq,FcSq,Fcp,Fcpp,phase]
     356    '''
     357    file = open(GPXfile,'rb')
     358    HKLFdata = []
     359    while True:
     360        try:
     361            data = cPickle.load(file)
     362        except EOFError:
     363            break
     364        datum = data[0]
     365        if datum[0] == HKLFname:
     366            HKLFdata = datum[1:][0]
     367    file.close()
     368    return HKLFdata
     369   
    33370def ShowBanner():
    34371    print 80*'*'
     
    22772614    calcControls = {}
    22782615    G2mv.InitVars()   
    2279     Controls = G2IO.GetControls(GPXfile)
     2616    Controls = GetControls(GPXfile)
    22802617    ShowControls(Controls)           
    2281     constrDict,constrFlag,fixedList = G2IO.GetConstraints(GPXfile)
    2282     Histograms,Phases = G2IO.GetUsedHistogramsAndPhases(GPXfile)
     2618    constrDict,constrFlag,fixedList = GetConstraints(GPXfile)
     2619    Histograms,Phases = GetUsedHistogramsAndPhases(GPXfile)
    22832620    if not Phases:
    22842621        print ' *** ERROR - you have no histograms to refine! ***'
     
    23922729    SetHistogramData(parmDict,sigDict,Histograms)
    23932730    G2mv.PrintIndependentVars(parmDict,varyList,sigDict)
    2394     G2IO.SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,covData)
     2731    SetUsedHistogramsAndPhases(GPXfile,Histograms,Phases,covData)
    23952732   
    23962733#for testing purposes!!!
     
    24182755    print ' Sequential Refinement'
    24192756    G2mv.InitVars()   
    2420     Controls = G2IO.GetControls(GPXfile)
     2757    Controls = GetControls(GPXfile)
    24212758    ShowControls(Controls)           
    2422     constrDict,constrFlag,fixedList = G2IO.GetConstraints(GPXfile)
    2423     Histograms,Phases = G2IO.GetUsedHistogramsAndPhases(GPXfile)
     2759    constrDict,constrFlag,fixedList = GetConstraints(GPXfile)
     2760    Histograms,Phases = GetUsedHistogramsAndPhases(GPXfile)
    24242761    if not Phases:
    24252762        print ' *** ERROR - you have no histograms to refine! ***'
     
    24342771        histNames = Controls['Seq Data']
    24352772    else:
    2436         histNames = G2IO.GetHistogramNames(GPXfile,['PWDR',])
     2773        histNames = GetHistogramNames(GPXfile,['PWDR',])
    24372774    if 'Reverse Seq' in Controls:
    24382775        if Controls['Reverse Seq']:
     
    25522889        SetHistogramData(parmDict,sigDict,Histo,ifPrint)
    25532890        SeqResult[histogram] = covData
    2554         G2IO.SetUsedHistogramsAndPhases(GPXfile,Histo,Phases,covData,makeBack)
     2891        SetUsedHistogramsAndPhases(GPXfile,Histo,Phases,covData,makeBack)
    25552892        makeBack = False
    2556     G2IO.SetSeqResult(GPXfile,Histograms,SeqResult)
     2893    SetSeqResult(GPXfile,Histograms,SeqResult)
    25572894
    25582895def DistAngle(DisAglCtls,DisAglData):
Note: See TracChangeset for help on using the changeset viewer.