Changeset 2433


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

update for sequential export

Location:
trunk
Files:
5 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
  • trunk/GSASIIgrid.py

    r2431 r2433  
    15051505            id=wxDOPARFIT, kind=wx.ITEM_NORMAL,text='Fit to equation(s)',
    15061506            help='Perform a parametric minimization')
     1507        # fill sequential Export menu
     1508        self.SeqExportLookup = {}
     1509        self.SequentialEx = wx.Menu(title='')
     1510        self.SequentialMenu.Append(menu=self.SequentialEx, title='Seq Export')
     1511        for lbl,txt in (('Phase','Export selected phase(s)'),
     1512                        ('Project','Export entire sequential fit')):
     1513            objlist = []
     1514            for obj in self.G2frame.exporterlist:
     1515                if lbl.lower() in obj.exporttype:
     1516                    try:
     1517                        obj.Writer
     1518                    except AttributeError:
     1519                        continue
     1520                    objlist.append(obj)
     1521            if objlist:
     1522                submenu = wx.Menu()
     1523                item = self.SequentialEx.AppendMenu(
     1524                    wx.ID_ANY, lbl+' as',
     1525                    submenu, help=txt)
     1526                for obj in objlist:
     1527                    item = submenu.Append(
     1528                        wx.ID_ANY,
     1529                        help=obj.longFormatName,
     1530                        kind=wx.ITEM_NORMAL,
     1531                        text=obj.formatName)
     1532                    self.SeqExportLookup[item.GetId()] = (obj,lbl) # lookup table for submenu item
     1533       
    15071534        self.PostfillDataMenu()
    15081535           
     
    32063233            variableLabels[var] = dlg.GetValue()
    32073234        dlg.Destroy()
    3208        
     3235
     3236    def DoSequentialExport(event):
     3237        '''Event handler for all Sequential Export menu items
     3238        '''
     3239        vals = G2frame.dataFrame.SeqExportLookup.get(event.GetId())
     3240        if vals is None:
     3241            print('Error: Id not found. This should not happen!')
     3242        G2IO.ExportSequential(G2frame,data,*vals)
     3243   
    32093244    #def GridRowLblToolTip(row): return 'Row ='+str(row)
    32103245   
     
    32713306    RcellLbls = {}
    32723307    zeroDict = {}
    3273     Rcelldict = {}
    32743308    for phase in Phases:
    32753309        phasedict = Phases[phase]
     
    32803314        zeroDict[pId] = dict(zip(RcellLbls[pId],6*[0.,]))
    32813315        SGdata[pId] = phasedict['General']['SGData']
    3282         Rcelldict.update({lbl:val for lbl,val in zip(RcellLbls[pId],RecpCellTerms[pId])})
    32833316        laue = SGdata[pId]['SGLaue']
    32843317        if laue == '2/m':
     
    33153348    G2frame.dataFrame.Bind(wx.EVT_MENU, EditParFitEq, id=wxEDITPARFIT)
    33163349    G2frame.dataFrame.Bind(wx.EVT_MENU, DoParEqFit, id=wxDOPARFIT)
     3350
     3351    for id in G2frame.dataFrame.SeqExportLookup:       
     3352        G2frame.dataFrame.Bind(wx.EVT_MENU, DoSequentialExport, id=id)
     3353
    33173354    EnablePseudoVarMenus()
    33183355    EnableParFitEqMenus()
     
    34383475    colList += zip(*vals)
    34393476    colSigs += zip(*esds)
     3477    # compute and add weight fractions to table if varied
     3478    for phase in Phases:
     3479        var = str(Phases[phase]['pId'])+':*:Scale'
     3480        if var not in combinedVaryList: continue
     3481        wtFrList = []
     3482        sigwtFrList = []
     3483        for i,name in enumerate(histNames):
     3484            wtFrSum = 0.
     3485            for phase1 in Phases:
     3486                wtFrSum += Phases[phase1]['Histograms'][name]['Scale'][0]*Phases[phase1]['General']['Mass']
     3487            var = str(Phases[phase]['pId'])+':'+str(i)+':Scale'
     3488            wtFr = Phases[phase]['Histograms'][name]['Scale'][0]*Phases[phase]['General']['Mass']/wtFrSum
     3489            wtFrList.append(wtFr)
     3490            if var in data[name]['varyList']:
     3491                sig = data[name]['sig'][data[name]['varyList'].index(var)]*wtFr/Phases[phase]['Histograms'][name]['Scale'][0]
     3492            else:
     3493                sig = 0.0
     3494            sigwtFrList.append(sig)
     3495        colLabels.append(str(Phases[phase]['pId'])+':*:WgtFrac')
     3496        colList += [wtFrList]
     3497        colSigs += [sigwtFrList]
    34403498               
    34413499    # tabulate constrained variables, removing histogram numbers if needed
  • trunk/GSASIIobj.py

    r2363 r2433  
    13691369        'pos$': 'peak position',
    13701370        'int$': 'peak intensity',
     1371        'WgtFrac':'phase weight fraction',
    13711372        }.items():
    13721373        VarDesc[key] = value
  • trunk/exports/G2export_CIF.py

    r2354 r2433  
    1414This implements a complex exporter :class:`ExportCIF` that can implement an
    1515entire project in a complete CIF intended for submission as a
    16 publication. In addition, there are two subclasses of :class:`ExportCIF`:
     16publication. In addition, there are three subclasses of :class:`ExportCIF`:
     17:class:`ExportProjectCIF`,
    1718:class:`ExportPhaseCIF` and :class:`ExportDataCIF` that
    18 export a single phase or data set. Note that ``self.mode`` determines
     19export a project, single phase or data set. Note that ``self.mode`` determines
    1920what is written:
    2021
     
    5455
    5556class ExportCIF(G2IO.ExportBaseclass):
    56     '''Used to create a CIF of an entire project
    57 
    58     :param wx.Frame G2frame: reference to main GSAS-II frame
     57    '''Base class for CIF exports
    5958    '''
    6059    def __init__(self,G2frame):
     
    6564            longFormatName = 'Export project as CIF'
    6665            )
    67         self.exporttype = ['project']
     66        self.exporttype = []
    6867        self.author = ''
    69         self.mode = 'full'
    70 
    71     def Exporter(self,event=None):
    72         '''Export a CIF. Export can be full or simple (as set by self.mode).
     68        self.mode = ''
     69
     70    def _Exporter(self,event=None,phaseOnly=None,histOnly=None):
     71        '''Basic code to export a CIF. Export can be full or simple (as set by self.mode).
    7372        "simple" skips data, distances & angles, etc. and can only include
    7473        a single phase while "full" is intended for for publication submission.
     
    272271                    s += s1
    273272            return s
     273       
    274274        def FormatBackground(bkg,hId):
    275275            '''Display the Background information as a descriptive text string.
     
    813813                    WriteCIFitem(line)
    814814
    815         def WritePhaseInfo(phasenam):
     815        def WritePhaseInfo(phasenam,hist=None):
    816816            'Write out the phase information for the selected phase'
    817817            WriteCIFitem('\n# phase info for '+str(phasenam) + ' follows')
     
    848848
    849849            # loop over histogram(s) used in this phase
    850             if not oneblock and not self.quickmode:
     850            if not oneblock and not self.quickmode and not hist:
    851851                # report pointers to the histograms used in this phase
    852852                histlist = []
     
    15991599#***** end of functions for export method =======================================
    16001600#=================================================================================
    1601 
    1602         # the export process starts here
     1601        # make sure required information is present
     1602        self.CIFdate = dt.datetime.strftime(dt.datetime.now(),"%Y-%m-%dT%H:%M")
     1603        self.CIFname = self.CIFname.replace(' ','')
     1604        if not self.CIFname: # none defined & needed, save as GPX to get one
     1605            self.G2frame.OnFileSaveas(None)
     1606            if not self.G2frame.GSASprojectfile: return
     1607            self.CIFname = os.path.splitext(
     1608                os.path.split(self.G2frame.GSASprojectfile)[1]
     1609                )[0]
     1610            self.CIFname = self.CIFname.replace(' ','')
     1611        # get CIF author name -- required for full CIFs
     1612        try:
     1613            self.author = self.OverallParms['Controls'].get("Author",'').strip()
     1614        except KeyError:
     1615            pass
     1616        while not (self.author or self.quickmode):
     1617            if not EditAuthor(): return
     1618        self.shortauthorname = self.author.replace(',','').replace(' ','')[:20]
     1619           
     1620        if phaseOnly:
     1621            oneblock = True
     1622            self.quickmode = True
     1623            #====Phase only CIF ====================================================
     1624            self.Write(' ')
     1625            self.Write(70*'#')
     1626            WriteCIFitem('data_'+self.CIFname)
     1627            #phaseblk = self.Phases[phaseOnly] # pointer to current phase info
     1628            # report the phase info
     1629            WritePhaseInfo(phaseOnly)
     1630            return
     1631        elif histOnly and len(self.Phases) == 1:
     1632            hist = histOnly
     1633            histname = histOnly.replace(' ','')
     1634            oneblock = True
     1635            self.quickmode = False
     1636            self.ifHKLF = False
     1637            self.ifPWDR = True
     1638            self.Write(' ')
     1639            self.Write(70*'#')
     1640            phasenam = self.Phases.keys()[0]
     1641            WriteCIFitem('data_'+self.CIFname)
     1642            #print 'phasenam',phasenam
     1643            #phaseblk = self.Phases[phasenam] # pointer to current phase info
     1644            instnam = instnam.replace(' ','')
     1645            WriteCIFitem('_pd_block_id',
     1646                         str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1647                         str(self.shortauthorname) + "|" + instnam + '|' + histname)
     1648            #WriteAudit()
     1649            #writeCIFtemplate(self.OverallParms['Controls'],'publ') # overall (publication) template
     1650            #WriteOverall()
     1651            #writeCIFtemplate(self.Phases[phasenam]['General'],'phase',phasenam) # write phase template
     1652            # report the phase info
     1653            WritePhaseInfo(phasenam,hist)
     1654            # preferred orientation
     1655            #SH = FormatSH(phasenam)
     1656            #MD = FormatHAPpo(phasenam)
     1657            #if SH and MD:
     1658            #    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + '\n' + MD)
     1659            #elif SH or MD:
     1660            #    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + MD)
     1661            #else:
     1662            #    WriteCIFitem('_pd_proc_ls_pref_orient_corr', 'none')
     1663            # report profile, since one-block: include both histogram and phase info
     1664            #WriteCIFitem('_pd_proc_ls_profile_function',
     1665            #    FormatInstProfile(histblk["Instrument Parameters"],histblk['hId'])
     1666            #        +'\n'+FormatPhaseProfile(phasenam))
     1667            histblk = self.Histograms[hist]["Sample Parameters"]
     1668            #writeCIFtemplate(histblk,'powder',histblk['InstrName']) # write powder template
     1669            WritePowderData(hist)
     1670            return
     1671        elif histOnly:
     1672            hist = histOnly
     1673            histname = '|' + histOnly.replace(' ','')
     1674            self.ifHKLF = False
     1675            if hist.startswith("PWDR"):
     1676                self.ifPWDR = True
     1677                if not self.Histograms[hist]["Sample Parameters"].get('InstrName'):
     1678                    self.Histograms[hist]["Sample Parameters"]['InstrName'] = 'Unknown'
     1679            else:
     1680                print("error: not Powder")
     1681                return
     1682            oneblock = False
     1683            self.quickmode = False
     1684            #=== multiblock: multiple phases and/or histograms ====================
     1685            self.Write(70*'#')
     1686            #WriteCIFitem('\ndata_'+self.CIFname+'_publ')
     1687            #WriteAudit()
     1688            #WriteCIFitem('_pd_block_id',
     1689            #    str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1690            #                 str(self.shortauthorname) + histname + "|Overall")
     1691            #writeCIFtemplate(self.OverallParms['Controls'],'publ') #insert the publication template
     1692                # ``template_publ.cif`` or a modified version
     1693                # overall info
     1694            WriteCIFitem('data_'+str(self.CIFname)+ histname +'_overall')
     1695            #WriteOverall() # this does not give right value
     1696            #============================================================
     1697            WriteCIFitem('# POINTERS TO PHASE AND HISTOGRAM BLOCKS')
     1698            datablockidDict = {} # save block names here -- N.B. check for conflicts between phase & hist names (unlikely!)
     1699            # loop over phase blocks
     1700            loopprefix = ''
     1701            WriteCIFitem('loop_   _pd_phase_block_id')
     1702
     1703            for phasenam in sorted(self.Phases.keys()):
     1704                i = self.Phases[phasenam]['pId']
     1705                datablockidDict[phasenam] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1706                                 'phase_'+ str(i) + '|' + str(self.shortauthorname) + histname)
     1707                WriteCIFitem(loopprefix,datablockidDict[phasenam])
     1708            # data block
     1709            loopprefix = '_pd_block_diffractogram_id'
     1710            histblk = self.Histograms[hist]
     1711            instnam = histblk["Sample Parameters"]['InstrName']
     1712            instnam = instnam.replace(' ','')
     1713            j = histblk['hId']
     1714            datablockidDict[hist] = (str(self.CIFdate) + "|" + str(self.CIFname) + "|" +
     1715                                             str(self.shortauthorname) + "|" +
     1716                                             instnam + "_hist_"+str(j))
     1717            WriteCIFitem(loopprefix,datablockidDict[hist])
     1718            #============================================================
     1719            # loop over phases, exporting them
     1720            phasebyhistDict = {} # create a cross-reference to phases by histogram
     1721            for j,phasenam in enumerate(sorted(self.Phases.keys())):
     1722                i = self.Phases[phasenam]['pId']
     1723                WriteCIFitem('\ndata_'+self.CIFname+"_phase_"+str(i))
     1724                WriteCIFitem('# Information for phase '+str(i))
     1725                WriteCIFitem('_pd_block_id',datablockidDict[phasenam])
     1726                # report the phase
     1727                #writeCIFtemplate(self.Phases[phasenam]['General'],'phase',phasenam) # write phase template
     1728                WritePhaseInfo(phasenam,hist)
     1729                # preferred orientation
     1730                #SH = FormatSH(phasenam)
     1731                #MD = FormatHAPpo(phasenam)
     1732                #if SH and MD:
     1733                #    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + '\n' + MD)
     1734                #elif SH or MD:
     1735                #    WriteCIFitem('_pd_proc_ls_pref_orient_corr', SH + MD)
     1736                #else:
     1737                #    WriteCIFitem('_pd_proc_ls_pref_orient_corr', 'none')
     1738                # report sample profile terms
     1739                #PP = FormatPhaseProfile(phasenam)
     1740                #if PP: WriteCIFitem('_pd_proc_ls_profile_function',PP)
     1741
     1742                #============================================================
     1743            # export selected histogram
     1744            histblk = self.Histograms[hist]
     1745            WriteCIFitem('\ndata_'+self.CIFname+"_pwd_"+str(i))
     1746                        #instnam = histblk["Sample Parameters"]['InstrName']
     1747                        # report instrumental profile terms
     1748            WriteCIFitem('_pd_proc_ls_profile_function',
     1749                    FormatInstProfile(histblk["Instrument Parameters"],histblk['hId']))
     1750            WriteCIFitem('# Information for histogram '+str(i)+': '+hist)
     1751            WriteCIFitem('_pd_block_id',datablockidDict[hist])
     1752            histprm = self.Histograms[hist]["Sample Parameters"]
     1753            #writeCIFtemplate(histprm,'powder',histprm['InstrName']) # powder template
     1754            WritePowderData(hist)
     1755            return
     1756
     1757        # the normal export process starts here
     1758        # get the project file name
     1759        self.CIFname = os.path.splitext(
     1760            os.path.split(self.G2frame.GSASprojectfile)[1]
     1761            )[0]
    16031762        self.InitExport(event)
    16041763        # load all of the tree into a set of dicts
     
    16171776        #        print j
    16181777
    1619         self.CIFdate = dt.datetime.strftime(dt.datetime.now(),"%Y-%m-%dT%H:%M")
    16201778        # is there anything to export?
    16211779        if len(self.Phases) == len(self.powderDict) == len(self.xtalDict) == 0:
     
    16241782               'Project does not contain any data or phases. Are they interconnected?')
    16251783           return
    1626         # get the project file name
    1627         self.CIFname = os.path.splitext(
    1628             os.path.split(self.G2frame.GSASprojectfile)[1]
    1629             )[0]
    1630         self.CIFname = self.CIFname.replace(' ','')
    1631         if not self.CIFname: # none defined & needed, save as GPX to get one
    1632             self.G2frame.OnFileSaveas(None)
    1633             if not self.G2frame.GSASprojectfile: return
    1634             self.CIFname = os.path.splitext(
    1635                 os.path.split(self.G2frame.GSASprojectfile)[1]
    1636                 )[0]
    1637             self.CIFname = self.CIFname.replace(' ','')
    16381784        # test for quick CIF mode or no data
    16391785        self.quickmode = False
     
    16591805        else: # one phase, one dataset, Full CIF
    16601806            oneblock = True
    1661 
    1662         # make sure required information is present
    1663         # get CIF author name -- required for full CIFs
    1664         try:
    1665             self.author = self.OverallParms['Controls'].get("Author",'').strip()
    1666         except KeyError:
    1667             pass
    1668         while not (self.author or self.quickmode):
    1669             if not EditAuthor(): return
    1670         self.shortauthorname = self.author.replace(',','').replace(' ','')[:20]
    16711807
    16721808        # check there is an instrument name for every histogram
     
    17831919                phasenam = self.Phases.keys()[0]
    17841920            #print 'phasenam',phasenam
    1785             phaseblk = self.Phases[phasenam] # pointer to current phase info
     1921            #phaseblk = self.Phases[phasenam] # pointer to current phase info
    17861922            # report the phase info
    17871923            WritePhaseInfo(phasenam)
     
    17921928                phasenam = self.Phases.keys()[0]
    17931929            #print 'phasenam',phasenam
    1794             phaseblk = self.Phases[phasenam] # pointer to current phase info
     1930            #phaseblk = self.Phases[phasenam] # pointer to current phase info
    17951931            instnam = instnam.replace(' ','')
    17961932            WriteCIFitem('_pd_block_id',
     
    19632099        # end of CIF export
    19642100
     2101class ExportProjectCIF(ExportCIF):
     2102    '''Used to create a CIF of an entire project
     2103
     2104    :param wx.Frame G2frame: reference to main GSAS-II frame
     2105    '''
     2106    def __init__(self,G2frame):
     2107        G2IO.ExportBaseclass.__init__(self,
     2108            G2frame=G2frame,
     2109            formatName = 'Full CIF',
     2110            extension='.cif',
     2111            longFormatName = 'Export project as CIF'
     2112            )
     2113        self.exporttype = ['project']
     2114
     2115    def Exporter(self,event=None):
     2116        self._Exporter(self,event=event)
     2117
     2118    def Writer(self,hist,mode='w'):
     2119        # set the project file name
     2120        self.CIFname = os.path.splitext(
     2121            os.path.split(self.G2frame.GSASprojectfile)[1]
     2122            )[0]+'_'+hist
     2123        self.CIFname = self.CIFname.replace(' ','')
     2124        self.OpenFile(mode=mode)
     2125        self._Exporter(histOnly=hist)
     2126        if mode == 'w':
     2127            print('CIF written to file '+str(self.fullpath))
     2128        self.CloseFile()
     2129       
    19652130class ExportPhaseCIF(ExportCIF):
    1966     '''Used to create a simple CIF of at most one phase. Uses exact same code as
     2131    '''Used to create a simple CIF with one phase. Uses exact same code as
    19672132    :class:`ExportCIF` except that `self.mode` is set to "simple" in `self.InitExport`.
    19682133    Shows up in menu as Quick CIF.
     
    19822147        self.mode = 'simple'
    19832148
     2149    def Exporter(self,event=None):
     2150        self._Exporter(self,event=event)
     2151
     2152    def Writer(self,hist,phasenam,mode='w'):
     2153        # set the project file name
     2154        self.CIFname = os.path.splitext(
     2155            os.path.split(self.G2frame.GSASprojectfile)[1]
     2156            )[0]+'_'+phasenam+'_'+hist
     2157        self.CIFname = self.CIFname.replace(' ','')
     2158        self.OpenFile(mode=mode)
     2159        self._Exporter(phaseOnly=phasenam)
     2160        self.CloseFile()
     2161
    19842162class ExportDataCIF(ExportCIF):
    19852163    '''Used to create a simple CIF containing diffraction data only. Uses exact same code as
     
    20012179        self.mode = 'simple'
    20022180
     2181    def Exporter(self,event=None):
     2182        self._Exporter(self,event=event)
     2183       
    20032184#===============================================================================
    20042185# misc CIF utilities
  • trunk/exports/G2export_csv.py

    r2152 r2433  
    5353        self.multiple = True # allow multiple phases to be selected
    5454
     55    def Writer(self,hist,phasenam,mode='w'):
     56        self.OpenFile(mode=mode)
     57        # test for aniso atoms
     58        aniso = False
     59        AtomsList = self.GetAtoms(phasenam)
     60        for lbl,typ,mult,xyz,td in AtomsList:
     61            if len(td) != 1:
     62                aniso = True
     63                break
     64        if mode == 'w':
     65            lbllist = ['hist','phase','a','b','c','alpha','beta','gamma','volume']
     66            lbllist += ["atm label","elem","mult","x","y","z","frac","Uiso"]
     67            if aniso: lbllist += ['U11','U22','U33','U12','U13','U23']
     68            WriteList(self,lbllist)
     69           
     70        cellList,cellSig = self.GetCell(phasenam)
     71        line = '"' + str(hist)+ '","' + str(phasenam) + '"'
     72        for defsig,val in zip(
     73            3*[-0.00001] + 3*[-0.001] + [-0.01], # sets sig. figs.
     74            cellList
     75            ):
     76            txt = G2mth.ValEsd(val,defsig)
     77            if line: line += ','
     78            line += txt
     79        self.Write(line)
     80
     81        # get atoms and print separated by commas
     82        AtomsList = self.GetAtoms(phasenam)
     83        for lbl,typ,mult,xyz,td in AtomsList:
     84            line = ",,,,,,,,,"
     85            line += '"' + lbl + '","' + typ + '",' + str(mult) + ','
     86            for val,sig in xyz:
     87                line += G2mth.ValEsd(val,-abs(sig))
     88                line += ","
     89            if len(td) == 1:
     90                line += G2mth.ValEsd(td[0][0],-abs(td[0][1]))
     91            else:
     92                line += ","
     93                for val,sig in td:
     94                    line += G2mth.ValEsd(val,-abs(sig))
     95                    line += ","
     96            self.Write(line)
     97
     98        if mode == 'w':
     99            print('Phase '+str(phasenam)+' written to file '+str(self.fullpath))
     100        self.CloseFile()
     101   
    55102    def Exporter(self,event=None):
    56103        '''Export a phase as a csv file
     
    64111        if self.ExportSelect(): return # set export parameters; get file name
    65112        self.OpenFile()
    66         # if more than one format is selected, put them into a single file
     113        # if more than one phase is selected, put them into a single file
    67114        for phasenam in self.phasenam:
    68115            phasedict = self.Phases[phasenam] # pointer to current phase info           
     
    127174
    128175    def Writer(self,TreeName,filename=None):
    129         print filename
     176        #print filename
    130177        self.OpenFile(filename)
    131178        histblk = self.Histograms[TreeName]
Note: See TracChangeset for help on using the changeset viewer.