Changeset 4878 for trunk


Ignore:
Timestamp:
Apr 10, 2021 4:16:31 PM (2 years ago)
Author:
toby
Message:

implement constraints in scriptable, part 1

Location:
trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIobj.py

    r4834 r4878  
    22462246                    pass
    22472247                else:
    2248                     raise Exception("Too many colons in var name "+str(args[0]))
     2248                    raise Exception("Incorrect number of colons in var name "+str(args[0]))
    22492249            self.name = lst[2]
    22502250        elif len(args) == 4:
  • trunk/GSASIIscriptable.py

    r4821 r4878  
    113113                                                      fit. (Also see :meth:`G2Project.get_Controls` to read values.)
    114114:meth:`G2Project.imageMultiDistCalib`                 Performs a global calibration fit with images at multiple distance settings.
     115:meth:`G2Project.get_Constraints`                     Retrieves :ref:`constraint definition <Constraint_definitions_table>` entries.
     116:meth:`G2Project.add_HoldConstr`                      Adds a hold constraint on one or more variables
     117:meth:`G2Project.add_EquivConstr`                     Adds an equivalence constraint on two or more variables
     118
    115119==================================================    ===============================================================================================================
    116120
     
    18891893    # end patch
    18901894
     1895def _constr_type(var):
     1896    '''returns the constraint type based on phase/histogram use
     1897    in a variable
     1898    '''
     1899    if var.histogram and var.phase:
     1900        return 'HAP'
     1901    elif var.phase:
     1902        return 'Phase'
     1903    elif var.histogram:
     1904        return 'Hist'
     1905    else:
     1906        return 'Global'
     1907   
    18911908class G2ObjectWrapper(object):
    18921909    """Base class for all GSAS-II object wrappers.
     
    29382955        return G2strIO.GetUsedHistogramsAndPhases(self.filename)
    29392956
     2957    def get_Constraints(self,ctype):
     2958        '''Returns a list of constraints of the type selected.
     2959
     2960        :param str ctype: one of the following keywords: 'Hist', 'HAP', 'Phase', 'Global'
     2961        :returns: a list of constraints, see the
     2962          :ref:`constraint definition descriptions <Constraint_definitions_table>`. Note that
     2963          if this list is changed (for example by deleting elements or by changing them)
     2964          the constraints in the project are changed.
     2965        '''
     2966        if ctype in ('Hist', 'HAP', 'Phase', 'Global'):
     2967            return self.data['Constraints']['data'][ctype]
     2968        else:
     2969            raise Exception(("get_Constraints error: value of ctype ({})"
     2970                    +" must be 'Hist', 'HAP', 'Phase', or 'Global'.")
     2971                                .format(ctype))
     2972       
     2973    def add_HoldConstr(self,varlist,reloadIdx=True):
     2974        '''Set a hold constraint on a list of variables.
     2975
     2976        Note that this will cause the project to be saved if not
     2977        already done so. It will always save the .gpx file before
     2978        creating constraint(s) if reloadIdx is True.
     2979
     2980        :param list varlist: A list of variables to hold.
     2981          Each value in the list may be one of the following three items:
     2982          (A) a :class:`GSASIIobj.G2VarObj` object,
     2983          (B) a variable name (str), or
     2984          (C) a list/tuple of arguments for :meth:`make_var_obj`.
     2985        :param bool reloadIdx: If True (default) the .gpx file will be
     2986          saved and indexed prior to use. This is essential if atoms, phases
     2987          or histograms have been added to the project.
     2988       
     2989        Example::
     2990       
     2991            gpx.add_HoldConstr(('0::A4','0:1:D12',':0:Lam'))
     2992
     2993        '''
     2994        if reloadIdx:
     2995            self.index_ids()
     2996        elif G2obj.TestIndexAll():
     2997            self.index_ids()
     2998        for var in varlist:
     2999            # make var object
     3000            if isinstance(var, str):
     3001                var = self.make_var_obj(var,reloadIdx=False)
     3002            elif not isinstance(var, G2obj.G2VarObj):
     3003                var = self.make_var_obj(*var,reloadIdx=False)
     3004            # make constraint
     3005            self.add_constraint_raw(_constr_type(var), [[1.0, var], None, None, 'h'])
     3006               
     3007    def add_EquivConstr(self,varlist,multlist=[],reloadIdx=True):
     3008        '''Set a equivalence on a list of variables.
     3009
     3010        Note that this will cause the project to be saved if not
     3011        already done so. It will always save the .gpx file before
     3012        creating a constraint if reloadIdx is True.
     3013
     3014        :param list varlist: A list of variables to make equivalent to the
     3015          first item in the list.
     3016          Each value in the list may be one of the following three items:
     3017          (A) a :class:`GSASIIobj.G2VarObj` object,
     3018          (B) a variable name (str), or
     3019          (C) a list/tuple of arguments for :meth:`make_var_obj`.
     3020        :param list multlist: a list of multipliers for each variable in
     3021          varlist. If there are fewer values than supplied for varlist
     3022          then missing values will be set to 1. The default is [] which
     3023          means that all multipliers are 1.         
     3024        :param bool reloadIdx: If True (default) the .gpx file will be
     3025          saved and indexed prior to use. This is essential if atoms, phases
     3026          or histograms have been added to the project.
     3027
     3028        Examples::
     3029       
     3030            gpx.add_EquivConstr(('0::AUiso:0','0::AUiso:1','0::AUiso:2'))
     3031            gpx.add_EquivConstr(('0::dAx:0','0::dAx:1'),[1,-1])
     3032
     3033        '''
     3034        if reloadIdx:
     3035            self.index_ids()
     3036        elif G2obj.TestIndexAll():
     3037            self.index_ids()
     3038        if len(varlist) < 2:
     3039            raise Exception('add_EquivConstr Error: varlist must have at least 2 variables')
     3040        constr = []
     3041        typ_prev = None
     3042        for i,var in enumerate(varlist):
     3043            m = 1.
     3044            try:
     3045                m = float(multlist[i])
     3046            except IndexError:
     3047                pass
     3048            # make var object
     3049            if isinstance(var, str):
     3050                var = self.make_var_obj(var,reloadIdx=False)
     3051            elif not isinstance(var, G2obj.G2VarObj):
     3052                var = self.make_var_obj(*var,reloadIdx=False)
     3053            # make constraint
     3054            constr.append([m,var])
     3055            typ = _constr_type(var)
     3056            if typ_prev is None:
     3057                typ_prev = typ
     3058                var_prev = var
     3059            if typ_prev != typ:
     3060                msg = 'Type ({}) for var {} is different from {} ({})'.format(typ,var,var_prev,typ_prev)
     3061                raise Exception('add_EquivConstr Error: '+msg)
     3062            typ_prev = typ
     3063            var_prev = var   
     3064        constr += [None, None, 'e']
     3065        self.add_constraint_raw(typ, constr)
     3066
     3067    def add_EquivEquation(self,total,varlist,multlist=[],reloadIdx=True):
     3068        '''Set a constraint equation on a list of variables.
     3069
     3070        Note that this will cause the project to be saved if not
     3071        already done so. It will always save the .gpx file before
     3072        creating a constraint if reloadIdx is True.
     3073
     3074        :param float total: A value that the constraint must equal
     3075        :param list varlist: A list of variables to make equivalent to the
     3076          first item in the list.
     3077          Each value in the list may be one of the following three items:
     3078          (A) a :class:`GSASIIobj.G2VarObj` object,
     3079          (B) a variable name (str), or
     3080          (C) a list/tuple of arguments for :meth:`make_var_obj`.
     3081        :param list multlist: a list of multipliers for each variable in
     3082          varlist. If there are fewer values than supplied for varlist
     3083          then missing values will be set to 1. The default is [] which
     3084          means that all multipliers are 1.         
     3085        :param bool reloadIdx: If True (default) the .gpx file will be
     3086          saved and indexed prior to use. This is essential if atoms, phases
     3087          or histograms have been added to the project.
     3088
     3089        Example::
     3090       
     3091            gpx.add_EquivEquation(1.0,('0::Ax:0','0::Ax:1'),[1,1])
     3092
     3093        '''
     3094        if reloadIdx:
     3095            self.index_ids()
     3096        elif G2obj.TestIndexAll():
     3097            self.index_ids()
     3098        if len(varlist) < 2:
     3099            raise Exception('add_EquivEquation Error: varlist must have at least 2 variables')
     3100        try:
     3101            float(total)
     3102        except:
     3103            raise Exception('add_EquivEquation Error: total be a valid float')
     3104        constr = []
     3105        typ_prev = None
     3106        for i,var in enumerate(varlist):
     3107            m = 1.
     3108            try:
     3109                m = float(multlist[i])
     3110            except IndexError:
     3111                pass
     3112            # make var object
     3113            if isinstance(var, str):
     3114                var = self.make_var_obj(var,reloadIdx=False)
     3115            elif not isinstance(var, G2obj.G2VarObj):
     3116                var = self.make_var_obj(*var,reloadIdx=False)
     3117            # make constraint
     3118            constr.append([m,var])
     3119            typ = _constr_type(var)
     3120            if typ_prev is None:
     3121                typ_prev = typ
     3122                var_prev = var
     3123            if typ_prev != typ:
     3124                msg = 'Type ({}) for var {} is different from {} ({})'.format(typ,var,var_prev,typ_prev)
     3125                raise Exception('add_EquivConstr Error: '+msg)
     3126            typ_prev = typ
     3127            var_prev = var   
     3128        constr += [float(total), None, 'c']
     3129        self.add_constraint_raw(typ, constr)
     3130           
    29403131    def add_constraint_raw(self, cons_scope, constr):
    2941         """Adds a constraint of type consType to the project.
    2942         cons_scope should be one of "Hist", "Phase", "HAP", or "Global".
    2943 
    2944         WARNING it does not check the constraint is well-constructed"""
     3132        """Adds a constraint to the project.
     3133
     3134        :param str cons_scope: should be one of "Hist", "Phase", "HAP", or "Global".
     3135        :param list constr: a constraint coded with  :class:`GSASIIobj.G2VarObj`
     3136          objects as described in the
     3137          :ref:`constraint definition descriptions <Constraint_definitions_table>`.
     3138
     3139        WARNING this function does not check the constraint is well-constructed.
     3140        Please use :meth:`G2Project.add_HoldConstr` or
     3141        :meth:`G2Project.add_EquivConstr` (etc.) instead, unless you are really
     3142        certain you know what you are doing.
     3143        """
    29453144        constrs = self.data['Constraints']['data']
    29463145        if 'Global' not in constrs:
     
    29483147        constrs[cons_scope].append(constr)
    29493148
    2950     def hold_many(self, vars, type):
     3149    def hold_many(self, vars, ctype):
    29513150        """Apply holds for all the variables in vars, for constraint of a given type.
    2952 
    2953         type is passed directly to add_constraint_raw as consType
    2954 
    2955         :param list vars: A list of variables to hold. Either :class:`GSASIIobj.G2VarObj` objects,
    2956             string variable specifiers, or arguments for :meth:`make_var_obj`
    2957         :param str type: A string constraint type specifier. See
    2958             :class:`G2Project.add_constraint_raw`
    2959 
     3151        This routine has been superceeded by :meth:`add_Hold`
     3152
     3153        :param list vars: A list of variables to hold. Each may be a
     3154          :class:`GSASIIobj.G2VarObj` object, a variable name (str), or a
     3155          list/tuple of arguments for :meth:`make_var_obj`.
     3156        :param str ctype: A string constraint type specifier, passed directly to
     3157          :meth:`add_constraint_raw` as consType. Should be one of "Hist", "Phase",
     3158          or "HAP" ("Global" not implemented).
    29603159        """
     3160        print('G2Phase.hold_many Warning: replace calls to hold_many() with add_Hold()')
    29613161        for var in vars:
    29623162            if isinstance(var, str):
     
    29643164            elif not isinstance(var, G2obj.G2VarObj):
    29653165                var = self.make_var_obj(*var)
    2966             self.add_constraint_raw(type, [[1.0, var], None, None, 'h'])
     3166            self.add_constraint_raw(ctype, [[1.0, var], None, None, 'h'])
    29673167
    29683168    def make_var_obj(self, phase=None, hist=None, varname=None, atomId=None,
  • trunk/exports/G2export_CIF.py

    r4876 r4878  
    21492149                    return
    21502150                dlg.Destroy()
    2151 
     2151            # scan over histograms used in this phase for
     2152            pId = self.Phases[phasenam]['pId']
     2153            for h in phasedict['Histograms']:
     2154                if not phasedict['Histograms'][h]['Use']: continue
     2155                hId = self.Histograms[h]['hId']
     2156                T = self.Histograms[h]['Sample Parameters']['Temperature']
     2157               
    21522158        # check if temperature values & pressure are defaulted
    21532159        default = 0
Note: See TracChangeset for help on using the changeset viewer.