Changeset 4119


Ignore:
Timestamp:
Aug 28, 2019 11:11:22 PM (2 years ago)
Author:
toby
Message:

add reflection output in scripting

Location:
trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIIO.py

    r4032 r4119  
    18331833        #GSASIIpath.IPyBreak()
    18341834
    1835     def SetFromArray(self,hist,histname):
    1836         '''Load a histogram into the exporter in preparation for use of the .Writer
    1837         rather than the main tree. This is used in GSASIIscriptable when wx
    1838         is not present.
    1839         '''
    1840         self.Histograms[histname] =  {}
    1841         self.Histograms[histname]['Data'] = hist['data'][1]
    1842         self.Histograms[histname]['Instrument Parameters'] = hist['Instrument Parameters']
    1843         self.Histograms[histname]['Sample Parameters'] = hist['Sample Parameters']
    1844 
    18451835    # Tools to pull information out of the data arrays
    18461836    def GetCell(self,phasenam):
  • trunk/GSASIIscriptable.py

    r4088 r4119  
    184184:meth:`G2PwdrData.fit_fixed_points`                   Fits background to the specified fixed points.
    185185:meth:`G2PwdrData.getdata`                            Provides access to the diffraction data associated with the histogram.
     186:meth:`G2PwdrData.reflections`                        Provides access to the reflection lists for the histogram.
    186187:meth:`G2PwdrData.Export`                             Writes the diffraction data into a file
    187188:meth:`G2PwdrData.add_peak`                           Adds a peak to the peak list. Also see :ref:`PeakRefine`.
     
    684685
    685686Note that the parameters must match the object type and method (phase vs. histogram vs. HAP).
     687=================================
     688Code Examples
     689=================================
    686690
    687691.. _PeakRefine:
    688692
    689 =================================
     693--------------------
    690694Peak Refinement
    691 =================================
     695--------------------
    692696Peak refinement is performed with routines
    693697:meth:`G2PwdrData.add_peak`, :meth:`G2PwdrData.set_peakFlags` and
     
    731735    hist.Export_peaks('pkfit.txt')
    732736    #gpx.save()  # gpx file is not written without this
     737
     738
     739--------------------
     740Pattern Simulation
     741--------------------
     742
     743This shows an example where a structure is read from a CIF, a
     744pattern is computed and the pattern and reflection list are computed.
     745
     746.. code-block::  python
     747
     748    import os,sys
     749    sys.path.insert(0,'/Users/toby/software/G2/GSASII')
     750    import GSASIIscriptable as G2sc
     751    datadir = "/Users/toby/software/G2/Tutorials/PythonScript/data"
     752    PathWrap = lambda fil: os.path.join(datadir,fil)
     753    gpx = G2sc.G2Project(filename='PbSO4sim.gpx') # create a project
     754    # add a phase to the project
     755    phase0 = gpx.add_phase(PathWrap("PbSO4-Wyckoff.cif"),
     756             phasename="PbSO4",fmthint='CIF')
     757    # add a simulated histogram and link it to the previous phase(s)
     758    hist1 = gpx.add_simulated_powder_histogram("PbSO4 simulation",
     759                PathWrap("inst_d1a.prm"),5.,120.,0.01,
     760                phases=gpx.phases())
     761    # Set the scale factor to adjust the y scale
     762    hist1.SampleParameters['Scale'][0] = 1000000.
     763    # parameter optimization and calculate pattern
     764    gpx.data['Controls']['data']['max cyc'] = 0 # refinement not needed
     765    gpx.do_refinements([{}])
     766    gpx.save()
     767    # save results
     768    gpx.histogram(0).Export('PbSO4data','.csv','hist') # data
     769    gpx.histogram(0).Export('PbSO4refl','.csv','refl') # reflections
     770
    733771
    734772.. _CommandlineInterface:
     
    891929            if typ not in exportersByExtension:
    892930                exportersByExtension[typ] = {obj.extension:obj}
     931            elif obj.extension in exportersByExtension[typ]:
     932                if type(exportersByExtension[typ][obj.extension]) is list:
     933                    exportersByExtension[typ][obj.extension].append(obj)
     934                else:
     935                    exportersByExtension[typ][obj.extension] = [
     936                        exportersByExtension[typ][obj.extension],
     937                        obj]
    893938            else:
    894939                exportersByExtension[typ][obj.extension] = obj
     
    31283173       
    31293174    def y_calc(self):
     3175        '''Returns the calculated intensity values; better to
     3176        use :meth:`getdata`
     3177        '''
    31303178        return self.data['data'][1][3]
    31313179
    3132     def Export(self,fileroot,extension):
     3180    def reflections(self):
     3181        '''Returns a dict with an entry for every phase in the
     3182        current histogram. Within each entry is a dict with keys
     3183        'RefList' (reflection list, see
     3184        :ref:`Powder Reflections <PowderRefl_table>`),
     3185        'Type' (histogram type), 'FF'
     3186        (form factor information), 'Super' (True if this is superspace
     3187        group).
     3188        '''
     3189        return self.data['Reflection Lists']
     3190   
     3191    def Export(self,fileroot,extension,fmthint=None):
    31333192        '''Write the histogram into a file. The path is specified by fileroot and
    31343193        extension.
     
    31383197        :param str extension: includes '.', must match an extension in global
    31393198           exportersByExtension['powder'] or a Exception is raised.
     3199        :param str fmthint: If specified, the first exporter where the format
     3200           name (obj.formatName, as shown in Export menu) contains the
     3201          supplied string will be used. If not specified, an error
     3202          will be generated showing the possible choices.
    31403203        :returns: name of file that was written
    31413204        '''
     
    31463209        fil = os.path.abspath(os.path.splitext(fileroot)[0]+extension)
    31473210        obj = exportersByExtension['powder'][extension]
    3148         obj.SetFromArray(hist=self.data,histname=self.name)
     3211        if type(obj) is list:
     3212            if fmthint is None:
     3213                print('Defined ',extension,'exporters are:')
     3214                for o in obj:
     3215                    print('\t',o.formatName)
     3216                raise G2ScriptException('No format hint for file type = "'+extension+'"')
     3217            for o in obj:
     3218              if fmthint.lower() in o.formatName.lower():
     3219                  obj = o
     3220                  break
     3221            else:
     3222                print('Hint ',fmthint,'not found. Defined ',extension,'exporters are:')
     3223                for o in obj:
     3224                    print('\t',o.formatName)
     3225                raise G2ScriptException('Bad format hint for file type = "'+exten+'"')
     3226        self._SetFromArray(obj)
    31493227        obj.Writer(self.name,fil)
    31503228        return fil
    31513229   
     3230    def _SetFromArray(self,expObj):
     3231        '''Load a histogram into the exporter in preparation for use of
     3232        the .Writer method in the object.
     3233
     3234        :param Exporter expObj: Exporter object
     3235        '''
     3236        expObj.Histograms[self.name] =  {}
     3237        expObj.Histograms[self.name]['Data'] = self.data['data'][1]
     3238        for key in 'Instrument Parameters','Sample Parameters','Reflection Lists':
     3239            expObj.Histograms[self.name][key] = self.data[key]
     3240           
    31523241    def plot(self, Yobs=True, Ycalc=True, Background=True, Residual=True):
    31533242        try:
  • trunk/exports/G2export_csv.py

    r3825 r4119  
    167167        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
    168168            G2frame=G2frame,
    169             formatName = 'CSV file',
     169            formatName = 'histogram CSV file',
    170170            extension='.csv',
    171171            longFormatName = 'Export powder data as comma-separated (csv) file'
     
    293293        self.multiple = False # only allow one histogram to be selected
    294294
     295    def Writer(self,TreeName,filename=None):
     296        print(filename)
     297        self.OpenFile(filename)
     298        histblk = self.Histograms[TreeName]
     299        self.write(TreeName,histblk)
     300        self.CloseFile()
     301        print(TreeName+' reflections written to file '+self.fullpath)
     302       
    295303    def Exporter(self,event=None):
    296304        '''Export a set of powder reflections as a csv file
     
    300308        self.loadTree()
    301309        if self.ExportSelect(): return  # set export parameters, get file name
    302         self.OpenFile()
    303310        hist = list(self.histnam)[0] # there should only be one histogram, in any case take the 1st
    304311        histblk = self.Histograms[hist]
     312        self.OpenFile()
     313        self.write(hist,histblk)
     314        self.CloseFile()
     315        print(hist+' reflections written to file '+self.fullpath)
     316       
     317    def write(self,hist,histblk):
    305318        self.Write('"Histogram"')
    306319        self.Write('"'+hist+'"')
     
    351364                        FWHM = G2pwd.getgamFW(g,s)
    352365                        self.Write(fmt.format(h,k,l,dsp,pos,Fobs,Fcalc,phase,mult,s,g,FWHM,Prfo,i))
    353         self.CloseFile()
    354         print(hist+' reflections written to file '+self.fullpath)
    355 
     366       
    356367class ExportSASDCSV(G2IO.ExportBaseclass):
    357368    '''Used to create a csv file for a small angle data set
Note: See TracChangeset for help on using the changeset viewer.