Ignore:
Timestamp:
Jan 7, 2018 9:06:19 PM (4 years ago)
Author:
toby
Message:

add data & parameter access in scripting

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIscriptable.py

    r3213 r3216  
    99########### SVN repository information ###################
    1010#
    11 # TODO: Export patterns
    1211# TODO: integrate 2d data based on a model
    13 # TODO: export entire project as a JSON file?
    1412#
    1513"""
     
    463461PwdrDataReaders = []
    464462PhaseReaders = []
     463exportersByExtension = {}
     464'''Specifies the list of extensions that are supported for Powder data export'''
    465465
    466466def LoadG2fil():
    467467    """Delay importing this module, it is slow"""
    468468    global G2fil
    469     global PwdrDataReaders
    470     global PhaseReaders
    471469    if G2fil is None:
    472470        import GSASIIfiles
    473471        G2fil = GSASIIfiles
     472        global PwdrDataReaders
     473        global PhaseReaders
    474474        PwdrDataReaders = G2fil.LoadImportRoutines("pwd", "Powder_Data")
    475475        PhaseReaders = G2fil.LoadImportRoutines("phase", "Phase")
    476 
     476        AllExporters = G2fil.LoadExportRoutines(None)
     477        global exportersByExtension
     478        exportersByExtension = {}
     479        for obj in AllExporters:
     480            try:
     481                obj.Writer
     482            except AttributeError:
     483                continue
     484            for typ in obj.exporttype:
     485                if typ not in exportersByExtension:
     486                    exportersByExtension[typ] = {obj.extension:obj}
     487                else:
     488                    exportersByExtension[typ][obj.extension] = obj
    477489
    478490def LoadDictFromProjFile(ProjFile):
     
    19051917    @property
    19061918    def residuals(self):
     1919        '''Provides a dictionary with with the R-factors for this histogram.
     1920        Includes the weighted and unweighted profile terms (R, Rb, wR, wRb, wRmin)
     1921        as well as the Bragg R-values for each phase (ph:H:Rf and ph:H:Rf^2).
     1922        '''
    19071923        data = self.data['data'][0]
    1908         return {key: data[key]
    1909                 for key in ['R', 'Rb', 'wR', 'wRb', 'wRmin']}
    1910 
     1924        return {key: data[key] for key in data
     1925                if key in ['R', 'Rb', 'wR', 'wRb', 'wRmin']
     1926                   or ':' in key}
     1927
     1928    @property
     1929    def InstrumentParameters(self):
     1930        '''Provides a dictionary with with the Instrument Parameters
     1931        for this histogram.
     1932        '''
     1933        return self.data['Instrument Parameters'][0]
     1934
     1935    @property
     1936    def SampleParameters(self):
     1937        '''Provides a dictionary with with the Sample Parameters
     1938        for this histogram.
     1939        '''
     1940        return self.data['Sample Parameters']
     1941   
    19111942    @property
    19121943    def id(self):
     
    19882019        self.proj.save()
    19892020
     2021    def getdata(self,datatype):
     2022        '''Provides access to the histogram data of the selected data type
     2023
     2024        :param str datatype: must be one of the following values (case is ignored)
     2025       
     2026           * 'X': the 2theta or TOF values for the pattern
     2027           * 'Yobs': the observed intensity values
     2028           * 'Yweight': the weights for each data point (1/sigma**2)
     2029           * 'Ycalc': the computed intensity values
     2030           * 'Background': the computed background values
     2031           * 'Residual': the difference between Yobs and Ycalc (obs-calc)
     2032
     2033        :returns: an numpy MaskedArray with data values of the requested type
     2034       
     2035        '''
     2036        enums = ['x', 'yobs', 'yweight', 'ycalc', 'background', 'residual']
     2037        if datatype.lower() not in enums:
     2038            raise G2ScriptException("Invalid datatype = "+datatype+" must be one of "+enums)
     2039        return self.data['data'][1][enums.index(datatype.lower())]
     2040       
    19902041    def y_calc(self):
    19912042        return self.data['data'][1][3]
    19922043
     2044    def Export(self,fileroot,extension):
     2045        '''Write the histogram into a file. The path is specified by fileroot and
     2046        extension.
     2047       
     2048        :param str fileroot: name of the file, optionally with a path (extension is
     2049           ignored)
     2050        :param str extension: includes '.', must match an extension in global
     2051           exportersByExtension['powder'] or a Exception is raised.
     2052        :returns: name of file that was written
     2053        '''
     2054        if extension not in exportersByExtension.get('powder',[]):
     2055            raise G2ScriptException('No Writer for file type = "'+extension+'"')
     2056        fil = os.path.abspath(os.path.splitext(fileroot)[0]+extension)
     2057        obj = exportersByExtension['powder'][extension]
     2058        obj.SetFromArray(hist=self.data,histname=self.name)
     2059        obj.Writer(self.name,fil)
     2060           
    19932061    def plot(self, Yobs=True, Ycalc=True, Background=True, Residual=True):
    19942062        try:
     
    25222590                    print(u'Unknown HAP key: '+key)
    25232591
     2592    def getHAPvalues(self, histname):
     2593        """Returns a dict with HAP values for the selected histogram
     2594
     2595        :param histogram: is a histogram object (:class:`G2PwdrData`) or
     2596            a histogram name or the index number of the histogram
     2597
     2598        :returns: HAP value dict
     2599        """
     2600        if isinstance(histname, G2PwdrData):
     2601            histname = histname.name
     2602        elif histname in self.data['Histograms']:
     2603            pass
     2604        elif type(histname) is int:
     2605            histname = self.proj.histograms()[histname].name
     2606        else:
     2607            raise G2ScriptException("Invalid histogram reference: "+str(histname))
     2608        return self.data['Histograms'][histname]
     2609                   
    25242610    def clear_HAP_refinements(self, refs, histograms='all'):
    25252611        """Clears the given HAP refinement parameters between this phase and
Note: See TracChangeset for help on using the changeset viewer.