Changeset 2433
- Timestamp:
- Aug 18, 2016 5:42:08 PM (7 years ago)
- Location:
- trunk
- Files:
-
- 5 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIIO.py
r2422 r2433 1110 1110 1111 1111 selections are placed in self.chosen when OK is pressed 1112 1113 Also see GSASIIctrls 1112 1114 ''' 1113 1115 def __init__(self,choicelist,headinglist, … … 1721 1723 1722 1724 ###################################################################### 1725 def 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) 1723 1732 class ExportBaseclass(object): 1724 1733 '''Defines a base class for the exporting of GSAS-II results. … … 1953 1962 else: 1954 1963 raise Exception('This should not happen!') 1955 1964 1956 1965 def loadParmDict(self): 1957 1966 '''Load the GSAS-II refinable parameters from the tree into a dict (self.parmDict). Update … … 2045 2054 self.Phases = {} 2046 2055 self.Histograms = {} 2056 self.SeqRefdata = None 2057 self.SeqRefhist = None 2047 2058 if self.G2frame.PatternTree.IsEmpty(): return # nothing to do 2048 2059 histType = None … … 2124 2135 2125 2136 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. 2127 2139 ''' 2140 if self.SeqRefdata and self.SeqRefhist: 2141 print('Note that dumpTree does not show sequential results') 2128 2142 print '\nOverall' 2129 2143 if mode == 'type': … … 2205 2219 saved as self.fp 2206 2220 ''' 2221 if mode == 'd': # debug mode 2222 self.fullpath = '(stdout)' 2223 self.fp = sys.stdout 2224 return 2207 2225 if not fil: 2208 2226 if not os.path.splitext(self.filename)[1]: … … 2219 2237 ''' 2220 2238 self.fp.write(line+'\n') 2239 2221 2240 def CloseFile(self,fp=None): 2222 2241 '''Close a file opened in OpenFile … … 2225 2244 file object self.fp is closed. 2226 2245 ''' 2246 if self.fp == sys.stdout: return # debug mode 2227 2247 if fp is None: 2228 2248 fp = self.fp 2229 2249 self.fp = None 2230 2250 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 2231 2275 # Tools to pull information out of the data arrays 2232 2276 def GetCell(self,phasenam): … … 2238 2282 cell values and `cellSig` has their uncertainties. 2239 2283 """ 2284 if self.SeqRefdata and self.SeqRefhist: 2285 return self.GetSeqCell(phasenam,self.SeqRefdata[self.SeqRefhist]) 2240 2286 phasedict = self.Phases[phasenam] # pointer to current phase info 2241 2287 try: … … 2249 2295 cell = phasedict['General']['Cell'][1:] 2250 2296 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 2252 2333 def GetAtoms(self,phasenam): 2253 2334 """Gets the atoms associated with a phase. Can be used with standard … … 2285 2366 for j,v in enumerate(('x','y','z')): 2286 2367 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) 2289 2372 xyz.append((val,sig)) 2290 2373 xyz.append((fval,fsig)) … … 2306 2389 def ExportPowderList(G2frame): 2307 2390 '''Returns a list of extensions supported by :func:`GSASIIIO:ExportPowder` 2391 This is used in :meth:`GSASIIimgGUI.AutoIntFrame` only. 2308 2392 2309 2393 :param wx.Frame G2frame: the GSAS-II main data tree window … … 2320 2404 2321 2405 def 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. 2323 2408 2324 2409 :param wx.Frame G2frame: the GSAS-II main data tree window … … 2348 2433 else: 2349 2434 print('No Export routine supports extension '+extension) 2350 2435 2436 def 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 2351 2501 def ReadDIFFaX(DIFFaXfile): 2352 2502 print 'read ',DIFFaXfile -
trunk/GSASIIgrid.py
r2431 r2433 1505 1505 id=wxDOPARFIT, kind=wx.ITEM_NORMAL,text='Fit to equation(s)', 1506 1506 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 1507 1534 self.PostfillDataMenu() 1508 1535 … … 3206 3233 variableLabels[var] = dlg.GetValue() 3207 3234 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 3209 3244 #def GridRowLblToolTip(row): return 'Row ='+str(row) 3210 3245 … … 3271 3306 RcellLbls = {} 3272 3307 zeroDict = {} 3273 Rcelldict = {}3274 3308 for phase in Phases: 3275 3309 phasedict = Phases[phase] … … 3280 3314 zeroDict[pId] = dict(zip(RcellLbls[pId],6*[0.,])) 3281 3315 SGdata[pId] = phasedict['General']['SGData'] 3282 Rcelldict.update({lbl:val for lbl,val in zip(RcellLbls[pId],RecpCellTerms[pId])})3283 3316 laue = SGdata[pId]['SGLaue'] 3284 3317 if laue == '2/m': … … 3315 3348 G2frame.dataFrame.Bind(wx.EVT_MENU, EditParFitEq, id=wxEDITPARFIT) 3316 3349 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 3317 3354 EnablePseudoVarMenus() 3318 3355 EnableParFitEqMenus() … … 3438 3475 colList += zip(*vals) 3439 3476 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] 3440 3498 3441 3499 # tabulate constrained variables, removing histogram numbers if needed -
trunk/GSASIIobj.py
r2363 r2433 1369 1369 'pos$': 'peak position', 1370 1370 'int$': 'peak intensity', 1371 'WgtFrac':'phase weight fraction', 1371 1372 }.items(): 1372 1373 VarDesc[key] = value -
trunk/exports/G2export_CIF.py
r2354 r2433 14 14 This implements a complex exporter :class:`ExportCIF` that can implement an 15 15 entire project in a complete CIF intended for submission as a 16 publication. In addition, there are two subclasses of :class:`ExportCIF`: 16 publication. In addition, there are three subclasses of :class:`ExportCIF`: 17 :class:`ExportProjectCIF`, 17 18 :class:`ExportPhaseCIF` and :class:`ExportDataCIF` that 18 export a single phase or data set. Note that ``self.mode`` determines19 export a project, single phase or data set. Note that ``self.mode`` determines 19 20 what is written: 20 21 … … 54 55 55 56 class 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 59 58 ''' 60 59 def __init__(self,G2frame): … … 65 64 longFormatName = 'Export project as CIF' 66 65 ) 67 self.exporttype = [ 'project']66 self.exporttype = [] 68 67 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). 73 72 "simple" skips data, distances & angles, etc. and can only include 74 73 a single phase while "full" is intended for for publication submission. … … 272 271 s += s1 273 272 return s 273 274 274 def FormatBackground(bkg,hId): 275 275 '''Display the Background information as a descriptive text string. … … 813 813 WriteCIFitem(line) 814 814 815 def WritePhaseInfo(phasenam ):815 def WritePhaseInfo(phasenam,hist=None): 816 816 'Write out the phase information for the selected phase' 817 817 WriteCIFitem('\n# phase info for '+str(phasenam) + ' follows') … … 848 848 849 849 # 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: 851 851 # report pointers to the histograms used in this phase 852 852 histlist = [] … … 1599 1599 #***** end of functions for export method ======================================= 1600 1600 #================================================================================= 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] 1603 1762 self.InitExport(event) 1604 1763 # load all of the tree into a set of dicts … … 1617 1776 # print j 1618 1777 1619 self.CIFdate = dt.datetime.strftime(dt.datetime.now(),"%Y-%m-%dT%H:%M")1620 1778 # is there anything to export? 1621 1779 if len(self.Phases) == len(self.powderDict) == len(self.xtalDict) == 0: … … 1624 1782 'Project does not contain any data or phases. Are they interconnected?') 1625 1783 return 1626 # get the project file name1627 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 one1632 self.G2frame.OnFileSaveas(None)1633 if not self.G2frame.GSASprojectfile: return1634 self.CIFname = os.path.splitext(1635 os.path.split(self.G2frame.GSASprojectfile)[1]1636 )[0]1637 self.CIFname = self.CIFname.replace(' ','')1638 1784 # test for quick CIF mode or no data 1639 1785 self.quickmode = False … … 1659 1805 else: # one phase, one dataset, Full CIF 1660 1806 oneblock = True 1661 1662 # make sure required information is present1663 # get CIF author name -- required for full CIFs1664 try:1665 self.author = self.OverallParms['Controls'].get("Author",'').strip()1666 except KeyError:1667 pass1668 while not (self.author or self.quickmode):1669 if not EditAuthor(): return1670 self.shortauthorname = self.author.replace(',','').replace(' ','')[:20]1671 1807 1672 1808 # check there is an instrument name for every histogram … … 1783 1919 phasenam = self.Phases.keys()[0] 1784 1920 #print 'phasenam',phasenam 1785 phaseblk = self.Phases[phasenam] # pointer to current phase info1921 #phaseblk = self.Phases[phasenam] # pointer to current phase info 1786 1922 # report the phase info 1787 1923 WritePhaseInfo(phasenam) … … 1792 1928 phasenam = self.Phases.keys()[0] 1793 1929 #print 'phasenam',phasenam 1794 phaseblk = self.Phases[phasenam] # pointer to current phase info1930 #phaseblk = self.Phases[phasenam] # pointer to current phase info 1795 1931 instnam = instnam.replace(' ','') 1796 1932 WriteCIFitem('_pd_block_id', … … 1963 2099 # end of CIF export 1964 2100 2101 class 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 1965 2130 class ExportPhaseCIF(ExportCIF): 1966 '''Used to create a simple CIF of at mostone phase. Uses exact same code as2131 '''Used to create a simple CIF with one phase. Uses exact same code as 1967 2132 :class:`ExportCIF` except that `self.mode` is set to "simple" in `self.InitExport`. 1968 2133 Shows up in menu as Quick CIF. … … 1982 2147 self.mode = 'simple' 1983 2148 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 1984 2162 class ExportDataCIF(ExportCIF): 1985 2163 '''Used to create a simple CIF containing diffraction data only. Uses exact same code as … … 2001 2179 self.mode = 'simple' 2002 2180 2181 def Exporter(self,event=None): 2182 self._Exporter(self,event=event) 2183 2003 2184 #=============================================================================== 2004 2185 # misc CIF utilities -
trunk/exports/G2export_csv.py
r2152 r2433 53 53 self.multiple = True # allow multiple phases to be selected 54 54 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 55 102 def Exporter(self,event=None): 56 103 '''Export a phase as a csv file … … 64 111 if self.ExportSelect(): return # set export parameters; get file name 65 112 self.OpenFile() 66 # if more than one formatis selected, put them into a single file113 # if more than one phase is selected, put them into a single file 67 114 for phasenam in self.phasenam: 68 115 phasedict = self.Phases[phasenam] # pointer to current phase info … … 127 174 128 175 def Writer(self,TreeName,filename=None): 129 print filename176 #print filename 130 177 self.OpenFile(filename) 131 178 histblk = self.Histograms[TreeName]
Note: See TracChangeset
for help on using the changeset viewer.