Changeset 2433 for trunk/GSASIIIO.py


Ignore:
Timestamp:
Aug 18, 2016 5:42:08 PM (5 years ago)
Author:
toby
Message:

update for sequential export

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIIO.py

    r2422 r2433  
    11101110       
    11111111    selections are placed in self.chosen when OK is pressed
     1112
     1113    Also see GSASIIctrls
    11121114    '''
    11131115    def __init__(self,choicelist,headinglist,
     
    17211723
    17221724######################################################################
     1725def striphist(var,insChar=''):
     1726    'strip a histogram number from a var name'
     1727    sv = var.split(':')
     1728    if len(sv) <= 1: return var
     1729    if sv[1]:
     1730        sv[1] = insChar
     1731    return ':'.join(sv)
    17231732class ExportBaseclass(object):
    17241733    '''Defines a base class for the exporting of GSAS-II results.
     
    19531962        else:
    19541963            raise Exception('This should not happen!')
    1955        
     1964
    19561965    def loadParmDict(self):
    19571966        '''Load the GSAS-II refinable parameters from the tree into a dict (self.parmDict). Update
     
    20452054        self.Phases = {}
    20462055        self.Histograms = {}
     2056        self.SeqRefdata = None
     2057        self.SeqRefhist = None
    20472058        if self.G2frame.PatternTree.IsEmpty(): return # nothing to do
    20482059        histType = None       
     
    21242135
    21252136    def dumpTree(self,mode='type'):
    2126         '''Print out information on the data tree dicts loaded in loadTree
     2137        '''Print out information on the data tree dicts loaded in loadTree.
     2138        Used for testing only.
    21272139        '''
     2140        if self.SeqRefdata and self.SeqRefhist:
     2141            print('Note that dumpTree does not show sequential results')
    21282142        print '\nOverall'
    21292143        if mode == 'type':
     
    22052219          saved as self.fp
    22062220        '''
     2221        if mode == 'd': # debug mode
     2222            self.fullpath = '(stdout)'
     2223            self.fp = sys.stdout
     2224            return
    22072225        if not fil:
    22082226            if not os.path.splitext(self.filename)[1]:
     
    22192237        '''
    22202238        self.fp.write(line+'\n')
     2239       
    22212240    def CloseFile(self,fp=None):
    22222241        '''Close a file opened in OpenFile
     
    22252244          file object self.fp is closed.
    22262245        '''
     2246        if self.fp == sys.stdout: return # debug mode
    22272247        if fp is None:
    22282248            fp = self.fp
    22292249            self.fp = None
    22302250        fp.close()
     2251       
     2252    def SetSeqRef(self,data,hist):
     2253        '''Set the exporter to retrieve results from a sequential refinement
     2254        rather than the main tree
     2255        '''
     2256        self.SeqRefdata = data
     2257        self.SeqRefhist = hist
     2258        data_name = data[hist]
     2259        for i,val in zip(data_name['varyList'],data_name['sig']):
     2260            self.sigDict[i] = val
     2261            self.sigDict[striphist(i)] = val
     2262        for i in data_name['parmDict']:
     2263            self.parmDict[striphist(i)] = data_name['parmDict'][i]
     2264            self.parmDict[i] = data_name['parmDict'][i]
     2265            # zero out the dA[xyz] terms, they would only bring confusion
     2266            key = i.split(':')
     2267            if len(key) < 3: continue
     2268            if key[2].startswith('dA'):
     2269                self.parmDict[i] = 0.0
     2270        for i,(val,sig) in data_name.get('depParmDict',{}).iteritems():
     2271            self.parmDict[i] = val
     2272            self.sigDict[i] = sig
     2273        #GSASIIpath.IPyBreak()
     2274               
    22312275    # Tools to pull information out of the data arrays
    22322276    def GetCell(self,phasenam):
     
    22382282          cell values and `cellSig` has their uncertainties.
    22392283        """
     2284        if self.SeqRefdata and self.SeqRefhist:
     2285            return self.GetSeqCell(phasenam,self.SeqRefdata[self.SeqRefhist])
    22402286        phasedict = self.Phases[phasenam] # pointer to current phase info
    22412287        try:
     
    22492295            cell = phasedict['General']['Cell'][1:]
    22502296            return cell,7*[0]
    2251    
     2297           
     2298    def GetSeqCell(self,phasenam,data_name):
     2299        """Gets the unit cell parameters and their s.u.'s for a selected phase
     2300        and histogram in a sequential fit
     2301
     2302        :param str phasenam: the name for the selected phase
     2303        :param dict data_name: the sequential refinement parameters for the selected histogram
     2304        :returns: `cellList,cellSig` where each is a 7 element list corresponding
     2305          to a, b, c, alpha, beta, gamma, volume where `cellList` has the
     2306          cell values and `cellSig` has their uncertainties.
     2307        """
     2308        phasedict = self.Phases[phasenam]
     2309        SGdata = phasedict['General']['SGData']
     2310        pId = phasedict['pId']
     2311        RecpCellTerms = G2lat.cell2A(phasedict['General']['Cell'][1:7])
     2312        ESDlookup = {}
     2313        Dlookup = {}
     2314        varied = [striphist(i) for i in data_name['varyList']]
     2315        for item,val in data_name['newCellDict'].iteritems():
     2316            if item in varied:
     2317                ESDlookup[val[0]] = item
     2318                Dlookup[item] = val[0]
     2319        A = RecpCellTerms[:]
     2320        for i in range(6):
     2321            var = str(pId)+'::A'+str(i)
     2322            if var in ESDlookup:
     2323                A[i] = data_name['newCellDict'][ESDlookup[var]][1] # override with refined value
     2324        cellDict = dict(zip([str(pId)+'::A'+str(i) for i in range(6)],A))
     2325        zeroDict = {i:0.0 for i in cellDict}
     2326        A,zeros = G2stIO.cellFill(str(pId)+'::',SGdata,cellDict,zeroDict)
     2327        covData = {
     2328            'varyList': [Dlookup.get(striphist(v),v) for v in data_name['varyList']],
     2329            'covMatrix': data_name['covMatrix']
     2330            }
     2331        return list(G2lat.A2cell(A)) + [G2lat.calc_V(A)], G2stIO.getCellEsd(str(pId)+'::',SGdata,A,covData)
     2332               
    22522333    def GetAtoms(self,phasenam):
    22532334        """Gets the atoms associated with a phase. Can be used with standard
     
    22852366            for j,v in enumerate(('x','y','z')):
    22862367                val = at[cx+j]
    2287                 pfx = str(phasedict['pId'])+'::dA'+v+':'+str(i)
    2288                 sig = self.sigDict.get(pfx,-0.000009)
     2368                pfx = str(phasedict['pId']) + '::A' + v + ':' + str(i)
     2369                val = self.parmDict.get(pfx, val)
     2370                dpfx = str(phasedict['pId'])+'::dA'+v+':'+str(i)
     2371                sig = self.sigDict.get(dpfx,-0.000009)
    22892372                xyz.append((val,sig))
    22902373            xyz.append((fval,fsig))
     
    23062389def ExportPowderList(G2frame):
    23072390    '''Returns a list of extensions supported by :func:`GSASIIIO:ExportPowder`
     2391    This is used in :meth:`GSASIIimgGUI.AutoIntFrame` only.
    23082392   
    23092393    :param wx.Frame G2frame: the GSAS-II main data tree window
     
    23202404
    23212405def ExportPowder(G2frame,TreeName,fileroot,extension):
    2322     '''Writes a single powder histogram using the Export routines
     2406    '''Writes a single powder histogram using the Export routines.
     2407    This is used in :meth:`GSASIIimgGUI.AutoIntFrame` only.
    23232408
    23242409    :param wx.Frame G2frame: the GSAS-II main data tree window
     
    23482433    else:
    23492434        print('No Export routine supports extension '+extension)
    2350        
     2435
     2436def ExportSequential(G2frame,data,obj,exporttype):
     2437    '''
     2438    Used to export from every phase/dataset in a sequential refinement using
     2439    a .Writer method for either projects or phases. Prompts to select histograms
     2440    and for phase exports, which phase(s).
     2441
     2442    :param wx.Frame G2frame: the GSAS-II main data tree window
     2443    :param dict data: the sequential refinement data object
     2444    :param str exporttype: indicates the type of export ('project' or 'phase')
     2445    '''
     2446    if len(data['histNames']) == 0:
     2447        G2G.G2MessageBox(G2frame,'There are no sequential histograms','Warning')
     2448    obj.InitExport(None)
     2449    obj.loadTree()
     2450    obj.loadParmDict()
     2451    if len(data['histNames']) == 1:
     2452        histlist = data['histNames']
     2453    else:
     2454        dlg = G2G.G2MultiChoiceDialog(G2frame,'Select histograms to export from list',
     2455                                 'Select histograms',data['histNames'])
     2456        if dlg.ShowModal() == wx.ID_OK:
     2457            histlist = [data['histNames'][l] for l in dlg.GetSelections()]
     2458            dlg.Destroy()
     2459        else:
     2460            dlg.Destroy()
     2461            return
     2462    if exporttype == 'Phase':
     2463        phaselist = obj.Phases.keys()
     2464        if len(obj.Phases) == 0:
     2465            G2G.G2MessageBox(G2frame,'There are no phases in sequential ref.','Warning')
     2466            return
     2467        elif len(obj.Phases) > 1:
     2468            dlg = G2G.G2MultiChoiceDialog(G2frame,'Select phases to export from list',
     2469                                    'Select phases', phaselist)
     2470            if dlg.ShowModal() == wx.ID_OK:
     2471                phaselist = [phaselist[l] for l in dlg.GetSelections()]
     2472                dlg.Destroy()
     2473            else:
     2474                dlg.Destroy()
     2475                return
     2476        filename = obj.askSaveFile()
     2477        if not filename: return True
     2478        obj.dirname,obj.filename = os.path.split(filename)
     2479        print('Writing output to file '+str(obj.filename)+"...")
     2480        mode = 'w'
     2481        for p in phaselist:
     2482            for h in histlist:
     2483                obj.SetSeqRef(data,h)
     2484                #GSASIIpath.IPyBreak()
     2485                obj.Writer(h,phasenam=p,mode=mode)
     2486                mode = 'a'
     2487        print('...done')
     2488    elif exporttype == 'Project':
     2489        filename = obj.askSaveFile()
     2490        if not filename: return True
     2491        obj.dirname,obj.filename = os.path.split(filename)
     2492        print('Writing output to file '+str(obj.filename)+"...")
     2493        mode = 'w'
     2494        for h in histlist:
     2495            obj.SetSeqRef(data,h)
     2496            obj.Writer(h,mode=mode)
     2497            print('\t'+str(h)+' written')
     2498            mode = 'a'
     2499        print('...done')
     2500
    23512501def ReadDIFFaX(DIFFaXfile):
    23522502    print 'read ',DIFFaXfile
Note: See TracChangeset for help on using the changeset viewer.