Changeset 4590


Ignore:
Timestamp:
Oct 12, 2020 10:57:49 AM (13 months ago)
Author:
toby
Message:

complete scripting for Parameter Limits

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIobj.py

    r4588 r4590  
    12111211Frozen parameters are not included in refinements through removal from the
    12121212list of parameters to be refined (``varyList``) in :func:`GSASIIstrMain.Refine` or
    1213 :func:`GSASIIstrMain.SeqRefine`. Once a variable is frozen, it will not be refined in any
     1213:func:`GSASIIstrMain.SeqRefine`.
     1214The data window for the Controls tree item shows the number of Frozen variables and
     1215the individual variables can be viewed with the Calculate/"View LS parms" menu window or
     1216obtained with :meth:`GSASIIscriptable.G2Project.get_Frozen`.
     1217Once a variable is frozen, it will not be refined in any
    12141218future refinements unless the the variable is removed (manually) from the list. This can also
    1215 be done with the Calculate/"View LS parms" menu window or ...
     1219be done with the Calculate/"View LS parms" menu window or
     1220:meth:`GSASIIscriptable.G2Project.set_Frozen`.
     1221
    12161222
    12171223.. seealso::
    1218   :class:`G2VarObj` 
     1224  :class:`G2VarObj`
    12191225  :func:`getVarDescr`
    12201226  :func:`CompileVarDesc`
     
    12271233  :func:`GSASIIstrMain.dropOOBvars`
    12281234  :meth:`GSASIIscriptable.G2Project.set_Controls`
     1235  :meth:`GSASIIscriptable.G2Project.get_Frozen`
     1236  :meth:`GSASIIscriptable.G2Project.set_Frozen`
    12291237
    12301238*Classes and routines*
     
    20322040    :param name: a GSAS-II parameter name (str, see :func:`getVarDescr`
    20332041      and :func:`CompileVarDesc`) or a :class:`G2VarObj` object.
    2034       If this contains a wildcard (* for
    2035       histogram or atom number) only the exact same name (with
    2036       that wildcard) will be matched in parmDict
    20372042    :param dict prmDict: a min/max dictionary, (parmMinDict
    20382043      or parmMaxDict in Controls) where keys are :class:`G2VarObj`
     
    20452050       * **value** *(float)* which contains the parameter limit.
    20462051    '''
    2047     keyLookup = {str(key):key for key in prmDict}
    2048     sn = str(name).split(':')
    2049     if str(name) in keyLookup:
    2050         return keyLookup[str(name)],prmDict[keyLookup[str(name)]]
    2051     elif sn[1] != '':
    2052         sn[1] = '*'
    2053         wname = ':'.join(sn)
    2054     elif len(sn) >= 4 and sn[3] != '':
    2055         sn[3] = '*'
    2056         wname = ':'.join(sn)
    2057     else:
    2058         return None,None
    2059     if wname in keyLookup:
    2060         return keyLookup[wname],prmDict[keyLookup[wname]]
    2061     else:
    2062         return None,None
     2052    for key,value in prmDict.items():
     2053        if str(key) == str(name): return key,value
     2054        if key == name: return key,value
     2055    return None,None
    20632056       
    20642057
  • trunk/GSASIIscriptable.py

    r4588 r4590  
    19691969
    19701970def patchControls(Controls):
    1971     '''patch routine to convert variable names used in parmeter limits
    1972     to G2VarObj objects
     1971    '''patch routine to convert variable names used in parameter limits
     1972    to G2VarObj objects
     1973    (See :ref:`Parameter Limits<ParameterLimits>` description.)
    19731974    '''
    19741975    #patch (added Oct 2020) convert variable names for parm limits to G2VarObj
     
    33513352        return parmDict,covData
    33523353               
    3353     def get_Controls(self, control):
     3354    def set_Frozen(self, variable=None, histogram=None, mode='remove'):
     3355        '''Removes one or more Frozen variables (or adds one)
     3356        (See :ref:`Parameter Limits<ParameterLimits>` description.)
     3357        Note that use of this
     3358        will cause the project to be saved if not already done so.
     3359
     3360        :param str variable: a variable name as a str or
     3361          (as a :class:`GSASIIobj.G2VarObj` object). Should
     3362          not contain wildcards.
     3363          If None (default), all frozen variables are deleted
     3364          from the project, unless a sequential fit and
     3365          a histogram is specified.
     3366        :param histogram: A reference to a histogram,
     3367          which can be reference by object, name, or number.
     3368          Used for sequential fits only.
     3369        :param str mode: The default mode is to remove variables
     3370          from the appropriate Frozen list, but if the mode
     3371          is specified as 'add', the variable is added to the
     3372          list.
     3373        :returns: True if the variable was added or removed, False
     3374          otherwise. Exceptions are generated with invalid requests.
     3375        '''
     3376        Controls = self.data['Controls']['data']
     3377        for key in ('parmMinDict','parmMaxDict','parmFrozen'):
     3378            if key not in Controls: Controls[key] = {}
     3379        if G2obj.TestIndexAll(): self.index_ids()
     3380        patchControls(Controls)
     3381
     3382        if mode == 'remove':
     3383            if variable is None and histogram is None:
     3384                Controls['parmFrozen'] = {}
     3385                return True
     3386        elif mode == 'add':
     3387            if variable is None:
     3388                raise Exception('set_Frozen error: variable must be specified')
     3389        else:
     3390            raise Exception('Undefined mode ({}) in set_Frozen'.format(mode))
     3391       
     3392        if histogram is None:
     3393            h = 'FrozenList'
     3394        else:
     3395            hist = self.histogram(histogram)
     3396            if hist:
     3397                h = hist.name
     3398                if h not in Controls['parmFrozen']: # no such list, not found
     3399                    return False
     3400            else:
     3401                raise Exception('set_Frozen error: histogram {} not found'.format(histogram))
     3402        if mode == 'remove':
     3403            if variable is None:
     3404                Controls['parmFrozen'][h] = []
     3405                return True
     3406            if h not in Controls['parmFrozen']:
     3407                return True
     3408            delList = []
     3409            for i,v in enumerate(Controls['parmFrozen'][h]):
     3410                if v == variable: delList.append(i)
     3411            if delList:
     3412                for i in reversed(delList):
     3413                    del Controls['parmFrozen'][h][i]
     3414                return True
     3415            return False
     3416        elif mode == 'add':
     3417            if type(variable) is str:
     3418                variable = G2obj.G2VarObj(variable)
     3419            elif type(v) is not G2obj.G2VarObj:
     3420                raise Exception(
     3421                    'set_Frozen error: variable {} wrong type ({})'
     3422                    .format(variable,type(variable)))
     3423            if h not in Controls['parmFrozen']: Controls['parmFrozen'][h] = []
     3424            Controls['parmFrozen'][h].append(variable)
     3425            return True
     3426
     3427    def get_Frozen(self, histogram=None):
     3428        '''Gets a list of Frozen variables.
     3429        (See :ref:`Parameter Limits<ParameterLimits>` description.)
     3430        Note that use of this
     3431        will cause the project to be saved if not already done so.
     3432
     3433        :param histogram: A reference to a histogram,
     3434          which can be reference by object, name, or number. Used
     3435          for sequential fits only. If left as the default (None)
     3436          for a sequential fit, all Frozen variables in all
     3437          histograms are returned.
     3438        :returns: a list containing variable names, as str values
     3439        '''
     3440        Controls = self.data['Controls']['data']
     3441        for key in ('parmMinDict','parmMaxDict','parmFrozen'):
     3442            if key not in Controls: Controls[key] = {}
     3443        if G2obj.TestIndexAll(): self.index_ids()
     3444        patchControls(Controls)
     3445        if histogram:
     3446            hist = self.histogram(histogram)
     3447            if hist:
     3448                h = hist.name
     3449                return [str(i) for i in Controls['parmFrozen'][h]]
     3450            elif histogram.lower() == 'all':
     3451                names = set()
     3452                for h in self.histograms():
     3453                    if h.name not in Controls['parmFrozen']: continue
     3454                    names = names.union([str(i) for i in Controls['parmFrozen'][h.name]])
     3455                return list(names)
     3456            else:
     3457                raise Exception('histogram {} not recognized'.format(histogram))
     3458        elif 'FrozenList' in Controls['parmFrozen']:
     3459            return [str(i) for i in Controls['parmFrozen']['FrozenList']]
     3460        else:
     3461            return []
     3462       
     3463    def get_Controls(self, control, variable=None):
    33543464        '''Return project controls settings
    33553465
    33563466        :param str control: the item to be returned. See below for allowed values.
     3467        :param str variable: a variable name as a str or
     3468          (as a :class:`GSASIIobj.G2VarObj` object).
     3469          Used only with control set to "parmMin" or "parmMax".
    33573470        :returns: The value for the control.
    33583471
     
    33673480              each sequential fit are used as the starting point for the next
    33683481              histogram.
     3482            * parmMin & parmMax: retrieves a maximum or minimum value for
     3483              a refined parameter. Note that variable will be a GSAS-II
     3484              variable name, optionally with * specified for a histogram
     3485              or atom number. Return value will be a float.
     3486              (See :ref:`Parameter Limits<ParameterLimits>` description.)
    33693487            * Anything else returns the value in the Controls dict, if present. An
    33703488              exception is raised if the control value is not present.
     
    33733491            :meth:`set_Controls`
    33743492        '''
     3493        if control.startswith('parmM'):
     3494            if not variable:
     3495                raise Exception('set_Controls requires a value for variable for control=parmMin or parmMax')
     3496            for key in ('parmMinDict','parmMaxDict','parmFrozen'):
     3497                if key not in self.data['Controls']['data']: self.data['Controls']['data'][key] = {}
     3498            if G2obj.TestIndexAll(): self.index_ids()
     3499            patchControls(self.data['Controls']['data'])
    33753500        if control == 'cycles':
    33763501            return self.data['Controls']['data']['max cyc']
     
    33813506        elif control == 'seqCopy':
    33823507            return self.data['Controls']['data']['Copy2Next']
     3508        elif control == 'parmMin' or control == 'parmMax':
     3509            key = G2obj.G2VarObj(variable)
     3510            return G2obj.prmLookup(
     3511                variable,
     3512                self.data['Controls']['data'][control+'Dict'])[1]
    33833513        elif control in self.data['Controls']['data']:
    33843514            return self.data['Controls']['data'][control]
     
    33973527        :param str variable: used only with control set to "parmMin" or "parmMax"
    33983528
    3399         Allowed values for parameter control:
    3400 
    3401             * cycles: sets the maximum number of cycles (value must be int)
    3402             * sequential: sets the histograms to be used for a sequential refinement.
    3403               Use an empty list to turn off sequential fitting.
    3404               The values in the list may be the name of the histogram (a str), or
    3405               a ranId or index (int values), see :meth:`histogram`.
    3406             * seqCopy: when True, the results from each sequential fit are used as
    3407               the starting point for the next. After each fit is is set to False.
    3408               Ignored for non-sequential fits.
    3409             * Reverse Seq: when True, sequential refinement is performed on the
    3410               reversed list of histograms.
    3411             * parmMin & parmMax: set a maximum or minimum value for a refined
    3412               parameter. Note that variable will be a GSAS-II variable name,
    3413               optionally with * specified for a histogram or atom number and
    3414               value must be a float.
    3415               (See :ref:`Parameter Limits<ParameterLimits>` description.)
     3529        Allowed values for *control* parameter:
     3530
     3531        * ``'cycles'``: sets the maximum number of cycles (value must be int)
     3532        * ``'sequential'``: sets the histograms to be used for a sequential refinement.
     3533          Use an empty list to turn off sequential fitting.
     3534          The values in the list may be the name of the histogram (a str), or
     3535          a ranId or index (int values), see :meth:`histogram`.
     3536        * ``'seqCopy'``: when True, the results from each sequential fit are used as
     3537          the starting point for the next. After each fit is is set to False.
     3538          Ignored for non-sequential fits.
     3539        * ``'Reverse Seq'``: when True, sequential refinement is performed on the
     3540          reversed list of histograms.
     3541        * ``'parmMin'`` & ``'parmMax'``: set a maximum or minimum value for a refined
     3542          parameter. Note that variable will be a GSAS-II variable name,
     3543          optionally with * specified for a histogram or atom number and
     3544          value must be a float.
     3545          (See :ref:`Parameter Limits<ParameterLimits>` description.)
    34163546
    34173547        .. seealso::
Note: See TracChangeset for help on using the changeset viewer.