Ignore:
Timestamp:
Oct 12, 2013 10:47:06 PM (9 years ago)
Author:
toby
Message:

change exports to always have lists of phases & histograms; new export examples; CIF export fixes

File:
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/exports/G2export_examples.py

    • Property svn:keywords set to Date Author Revision URL Id
    r1088 r1102  
    22# -*- coding: utf-8 -*-
    33########### SVN repository information ###################
    4 # $Date: $
    5 # $Author: $
    6 # $Revision: -1 $
    7 # $URL: https://subversion.xor.aps.anl.gov/pyGSAS/trunk/exports/G2export_CIF.py $
    8 # $Id: G2export_CIF.py -1   $
     4# $Date$
     5# $Author$
     6# $Revision$
     7# $URL$
     8# $Id$
    99########### SVN repository information ###################
    1010'''Code to demonstrate how export routines are created
     
    1212import os.path
    1313import GSASIIpath
    14 GSASIIpath.SetVersionNumber("$Revision: -1 $")
     14GSASIIpath.SetVersionNumber("$Revision$")
    1515import GSASIIIO as G2IO
    1616#import GSASIIgrid as G2gd
    17 import GSASIIstrIO as G2stIO
    18 #import GSASIImath as G2mth
    19 import GSASIIlattice as G2lat
    20 import GSASIIspc as G2spc
     17#import GSASIIstrIO as G2stIO
     18import GSASIImath as G2mth
     19#import GSASIIlattice as G2lat
     20#import GSASIIspc as G2spc
    2121#import GSASIIphsGUI as G2pg
    2222#import GSASIIstrMain as G2stMn
    2323
    24 class ExportPhaseShelx(G2IO.ExportBaseclass):
    25     '''Used to create a SHELX .ins file for a phase
    26 
    27     :param wx.Frame G2frame: reference to main GSAS-II frame
    28     '''
    29     def __init__(self,G2frame):
    30         super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
    31             G2frame=G2frame,
    32             formatName = 'SHELX',
    33             extension='.ins',
    34             longFormatName = 'Export phase as SHELX .ins file'
     24class ExportPhaseText(G2IO.ExportBaseclass):
     25    '''Used to create a text file for a phase
     26
     27    :param wx.Frame G2frame: reference to main GSAS-II frame
     28    '''
     29    def __init__(self,G2frame):
     30        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
     31            G2frame=G2frame,
     32            formatName = 'text',
     33            extension='.txt',
     34            longFormatName = 'Export phase as text file'
    3535            )
    3636        self.exporttype = ['phase']
    37         self.multiple = True
    38 
    39     def Exporter(self,event=None):
    40         '''Export as a SHELX .ins file
     37        self.multiple = True # allow multiple phases to be selected
     38
     39    def Exporter(self,event=None):
     40        '''Export a phase as a text file
    4141        '''
    4242        # the export process starts here
     
    4545        # create a dict with refined values and their uncertainties
    4646        self.loadParmDict()
    47         if self.SetupExport(event,                         # set export parameters
    48                             AskFile=True
    49                             ): return
     47        if self.SetupExport( # set export parameters
     48            event,                         
     49            AskFile=True     # prompt the user for a file name
     50            ): return
     51        self.OpenFile(self.filename)
     52        # if more than one format is selected, put them into a single file
    5053        for phasenam in self.phasenam:
    5154            phasedict = self.Phases[phasenam] # pointer to current phase info           
    5255            i = self.Phases[phasenam]['pId']
    53             if len(self.phasenam) > 1: # if more than one filename is included, add a phase #
    54                 nam,ext = os.path.splitext(self.filename)
    55                 fil = nam+"_"+str(i)+ext
    56             else:
    57                 fil = self.filename
    58             fp = self.OpenFile(fil)
    59             self.Write("TITL from "+str(self.G2frame.GSASprojectfile)+" phase "+str(phasenam))
    60             # get cell parameters
    61             pfx = str(phasedict['pId'])+'::'
    62             A,sigA = G2stIO.cellFill(pfx,phasedict['General']['SGData'],self.parmDict,self.sigDict)
    63             #cellSig = G2stIO.getCellEsd(pfx,
    64             #                           phasedict['General']['SGData'],A,
    65             #                           self.OverallParms['Covariance'])  # returns 7 vals, includes sigVol
    66             #cellList = G2lat.A2cell(A) + (G2lat.calc_V(A),)
    67             # write out cell parameters with dummy (0.5A) wavelength
    68             self.Write("CELL 0.5 {:.5f} {:.5f} {:.5f} {:.3f} {:.3f} {:.3f}".format(*G2lat.A2cell(A)))
    69            
    70 
    71             self.CloseFile()
    72             print('Phase '+str(phasenam)+' written to file '+str(fil))
     56            self.Write('\n'+80*'=')
     57            self.Write("Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile))
     58            self.Write("\nSpace group = "+str(phasedict['General']['SGData']['SpGrp'].strip()))
     59            # get cell parameters & print them
     60            cellList,cellSig = self.GetCell(phasenam)
     61            prevsig = 0
     62            for lbl,defsig,val,sig in zip(
     63                ['a','b','c','alpha','beta ','gamma','volume'],
     64                3*[-0.00001] + 3*[-0.001] + [-0.01], # sign values to use when no sigma
     65                cellList,cellSig
     66                ):
     67                if sig:
     68                    txt = G2mth.ValEsd(val,sig)
     69                    prevsig = -sig # use this as the significance for next value
     70                else:
     71                    txt = G2mth.ValEsd(val,min(defsig,prevsig),True)
     72                self.Write(lbl+' = '+txt)
     73            # get atoms and print them in nice columns
     74            AtomsList = self.GetAtoms(phasenam)
     75            fmt = "{:8s} {:4s} {:4s} {:12s} {:12s} {:12s} {:10s} {:10s}"
     76            self.Write('\nAtoms\n'+80*'-')
     77            self.Write(fmt.format("label","elem","mult","x","y","z","frac","Uiso"))
     78            self.Write(80*'-')
     79            aniso = False
     80            for lbl,typ,mult,xyz,td in AtomsList:
     81                vals = [lbl,typ,str(mult)]
     82                if xyz[3][0] == 0: continue
     83                for val,sig in xyz:
     84                    vals.append(G2mth.ValEsd(val,sig))
     85                if len(td) == 1:
     86                    vals.append(G2mth.ValEsd(td[0][0],td[0][1]))
     87                else:
     88                    vals.append("aniso")
     89                    aniso = True
     90                self.Write(fmt.format(*vals))
     91            # print anisotropic values, if any
     92            if aniso:
     93                self.Write('\nAnisotropic parameters')
     94                self.Write(80*'-')
     95                fmt = "{:8s} {:4s} {:10s} {:10s} {:10s} {:10s} {:10s} {:10s}"
     96                self.Write(fmt.format("label","elem",'U11','U22','U33','U12','U13','U23'))
     97                self.Write(80*'-')
     98                for lbl,typ,mult,xyz,td in AtomsList:
     99                    if len(td) == 1: continue
     100                    if xyz[3][0] == 0: continue
     101                    vals = [lbl,typ]
     102                    for val,sig in td:
     103                        vals.append(G2mth.ValEsd(val,sig))
     104                    self.Write(fmt.format(*vals))
     105            print('Phase '+str(phasenam)+' written to file '+str(self.filename))                       
     106        self.CloseFile()
     107
     108class ExportPowderText(G2IO.ExportBaseclass):
     109    '''Used to create a text file for a powder data set
     110
     111    :param wx.Frame G2frame: reference to main GSAS-II frame
     112    '''
     113    def __init__(self,G2frame):
     114        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
     115            G2frame=G2frame,
     116            formatName = 'text',
     117            extension='.txt',
     118            longFormatName = 'Export powder data as text file'
     119            )
     120        self.exporttype = ['powder']
     121        self.multiple = False # only allow one histogram to be selected
     122
     123    def Exporter(self,event=None):
     124        '''Export a set of powder data as a text file
     125        '''
     126        # the export process starts here
     127        # load all of the tree into a set of dicts
     128        self.loadTree()
     129        print 'Exporter',self.defaultSaveFile()
     130        if self.SetupExport( # set export parameters
     131            event,
     132            AskFile=False # use the default file name
     133            #AskFile=True
     134            ): return
     135        self.OpenFile()
     136        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
     137        histblk = self.Histograms[hist]
     138        #inst = histblk['Instrument Parameters'][0]
     139        #hId = histblk['hId']
     140        #pfx = ':' + str(hId) + ':'
     141        fmt = 2*"{:12.3f} " + "{:12.5f} " + 2*"{:12.3f} "
     142        hfmt = 5*"{:>12s} "
     143        self.Write(hfmt.format("x","y_obs","weight","y_calc","y_bkg"))
     144        for x,yobs,yw,ycalc,ybkg,obsmcalc in zip(histblk['Data'][0],
     145                                                 histblk['Data'][1],
     146                                                 histblk['Data'][2],
     147                                                 histblk['Data'][3],
     148                                                 histblk['Data'][4],
     149                                                 histblk['Data'][5],
     150                                                 ):
     151            self.Write(fmt.format(x,yobs,yw,ycalc,ybkg))
     152        self.CloseFile()
     153        print(str(hist)+' written to file '+str(self.filename))                       
     154
     155class ExportPowderReflText(G2IO.ExportBaseclass):
     156    '''Used to create a text file of reflections from a powder data set
     157
     158    :param wx.Frame G2frame: reference to main GSAS-II frame
     159    '''
     160    def __init__(self,G2frame):
     161        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
     162            G2frame=G2frame,
     163            formatName = 'reflection list as text',
     164            extension='.txt',
     165            longFormatName = 'Export powder reflection list as a text file'
     166            )
     167        self.exporttype = ['powder']
     168        self.multiple = False # only allow one histogram to be selected
     169
     170    def Exporter(self,event=None):
     171        '''Export a set of powder reflections as a text file
     172        '''
     173        # load all of the tree into a set of dicts
     174        self.loadTree()
     175        if self.SetupExport( # set export parameters
     176            event,
     177            AskFile=False # use the default file name
     178            #AskFile=True
     179            ): return
     180        self.OpenFile()
     181        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
     182        histblk = self.Histograms[hist]
     183        hklfmt = "{:.0f},{:.0f},{:.0f}"
     184        hfmt = "{:>8s} {:>8s} {:>12s} {:>12s} {:>7s} {:>6s}"
     185        fmt = "{:>8s} {:8.3f} {:12.3f} {:12.3f} {:7.2f} {:6.0f}"
     186        for phasenam in histblk['Reflection Lists']:
     187            self.Write('\nPhase '+str(phasenam))
     188            self.Write(80*'=')
     189            self.Write(hfmt.format("h,k,l","2-theta","F_obs","F_calc","phase","mult"))
     190            self.Write(80*'=')
     191            for (
     192                h,k,l,mult,dsp,pos,sig,gam,Fobs,Fcalc,phase,eqlist,phaselist,Icorr,FFdict
     193                ) in histblk['Reflection Lists'][phasenam]:
     194                self.Write(fmt.format(hklfmt.format(h,k,l),pos,Fobs,Fcalc,phase,mult))
     195        self.CloseFile()
     196        print(str(hist)+'reflections written to file '+str(self.filename))                       
     197
     198class ExportSingleText(G2IO.ExportBaseclass):
     199    '''Used to create a text file with single crystal reflection data
     200
     201    :param wx.Frame G2frame: reference to main GSAS-II frame
     202    '''
     203    def __init__(self,G2frame):
     204        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
     205            G2frame=G2frame,
     206            formatName = 'reflection list as text',
     207            extension='.txt',
     208            longFormatName = 'Export reflection list as a text file'
     209            )
     210        self.exporttype = ['single']
     211        self.multiple = False # only allow one histogram to be selected
     212
     213    def Exporter(self,event=None):
     214        '''Export a set of single crystal data as a text file
     215        '''
     216        # the export process starts here
     217        # load all of the tree into a set of dicts
     218        self.loadTree()
     219        if self.SetupExport( # set export parameters
     220            event,
     221            AskFile=False # use the default file name
     222            #AskFile=True
     223            ): return
     224        self.OpenFile()
     225        hist = self.histnam[0] # there should only be one histogram, in any case take the 1st
     226        histblk = self.Histograms[hist]
     227        hklfmt = "{:.0f},{:.0f},{:.0f}"
     228        hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}"
     229        fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}"
     230        self.Write(80*'=')
     231        self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","mult"))
     232        self.Write(80*'=')
     233        for (
     234            h,k,l,mult,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,eqlist,phaselist,Icorr,FFdict
     235            ) in histblk['Data']:
     236            self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,mult))
     237        self.CloseFile()
     238        print(str(hist)+' written to file '+str(self.filename))                       
     239
Note: See TracChangeset for help on using the changeset viewer.