diff --git a/docs/examples/gaussiangenerator.py b/docs/examples/gaussiangenerator.py index fedff5a5..ff65fb96 100644 --- a/docs/examples/gaussiangenerator.py +++ b/docs/examples/gaussiangenerator.py @@ -85,13 +85,13 @@ def __init__(self, name): # This initializes various parts of the generator ProfileGenerator.__init__(self, name) - # Here we create new Parameters using the '_newParameter' method of + # Here we create new Parameters using the '_new_parameter' method of # ProfileGenerator. The signature is - # _newParameter(name, value). + # _new_parameter(name, value). # See the API for full details. - self._newParameter("A", 1.0) - self._newParameter("x0", 0.0) - self._newParameter("sigma", 1.0) + self._new_parameter("A", 1.0) + self._new_parameter("x0", 0.0) + self._new_parameter("sigma", 1.0) return def __call__(self, x): @@ -101,7 +101,7 @@ def __call__(self, x): variable, x. We will define it as we did in gaussianrecipe.py. """ # First we must get the values of the Parameters. Since we used - # _newParameter to create them, the Parameters are accessible as + # _new_parameter to create them, the Parameters are accessible as # attributes by name. A = self.A.value x0 = self.x0.value diff --git a/docs/source/extending.rst b/docs/source/extending.rst index 464cd16c..6e3563de 100644 --- a/docs/source/extending.rst +++ b/docs/source/extending.rst @@ -236,9 +236,9 @@ structures. The restraint is applied with the ``restrainBVS`` method. The purpose of the method is to create the custom ``Restraint`` object, configure it and store it. Note that the optional `sig` and `scaled` flag are passed as part of this method. Both ``_restraints`` and -``_updateConfiguration`` come from ``ParameterSet``, from which +``_update_configuration`` come from ``ParameterSet``, from which ``SrRealParSet`` is derived. The ``_restraints`` attribute is a set of -``Restraints`` on the object. The ``_updateConfiguration`` method makes any +``Restraints`` on the object. The ``_update_configuration`` method makes any object containing the ``SrRealParSet`` aware of the configuration change. This gets propagated to the top-level ``FitRecipe``, if there is one. The restraint object is returned by the method so that it may be later removed. diff --git a/news/rm-camelcase-privatefuncs.rst b/news/rm-camelcase-privatefuncs.rst new file mode 100644 index 00000000..8852c31b --- /dev/null +++ b/news/rm-camelcase-privatefuncs.rst @@ -0,0 +1,23 @@ +**Added:** + +* No news needed, changed private functions from camelcase to snakecase. + +**Changed:** + +* + +**Deprecated:** + +* + +**Removed:** + +* + +**Fixed:** + +* + +**Security:** + +* diff --git a/src/diffpy/srfit/equation/builder.py b/src/diffpy/srfit/equation/builder.py index cca64f6b..4485087f 100644 --- a/src/diffpy/srfit/equation/builder.py +++ b/src/diffpy/srfit/equation/builder.py @@ -165,7 +165,7 @@ def makeEquation( Returns a callable Literal representing the equation string. """ - self._prepareBuilders(eqstr, buildargs, argclass, argkw) + self._prepare_builders(eqstr, buildargs, argclass, argkw) beq = eval(eqstr, {}, self.builders) # handle scalar numbers or numpy arrays if isinstance(beq, (numbers.Number, numpy.ndarray)): @@ -301,7 +301,7 @@ def wipeout(self, eq): eq.setRoot(nan) return - def _prepareBuilders(self, eqstr, buildargs, argclass, argkw): + def _prepare_builders(self, eqstr, buildargs, argclass, argkw): """Prepare builders so that equation string can be evaluated. This method checks the equation string for errors and missing @@ -332,7 +332,7 @@ def _prepareBuilders(self, eqstr, buildargs, argclass, argkw): Returns a dictionary of the name, BaseBuilder pairs. """ - eqargs = self._getUndefinedArgs(eqstr) + eqargs = self._get_undefined_args(eqstr) # Raise an error if there are arguments that need to be created, but # this is disallowed. @@ -353,7 +353,7 @@ def _prepareBuilders(self, eqstr, buildargs, argclass, argkw): return - def _getUndefinedArgs(self, eqstr): + def _get_undefined_args(self, eqstr): """Get the undefined arguments from eqstr. This tokenizes eqstr and extracts undefined arguments. An @@ -441,7 +441,7 @@ def getEquation(self): eq = Equation(name, self.literal) return eq - def __evalBinary(self, other, OperatorClass, onleft=True): + def __eval_binary(self, other, OperatorClass, onleft=True): """Evaluate a binary function. Other can be an BaseBuilder or a constant. @@ -479,7 +479,7 @@ def __evalBinary(self, other, OperatorClass, onleft=True): opbuilder.literal = op return opbuilder - def __evalUnary(self, OperatorClass): + def __eval_unary(self, OperatorClass): """Evaluate a unary function.""" op = OperatorClass() op.addLiteral(self.literal) @@ -488,28 +488,30 @@ def __evalUnary(self, OperatorClass): return opbuilder def __add__(self, other): - return self.__evalBinary(other, literals.AdditionOperator) + return self.__eval_binary(other, literals.AdditionOperator) def __radd__(self, other): - return self.__evalBinary(other, literals.AdditionOperator, False) + return self.__eval_binary(other, literals.AdditionOperator, False) def __sub__(self, other): - return self.__evalBinary(other, literals.SubtractionOperator) + return self.__eval_binary(other, literals.SubtractionOperator) def __rsub__(self, other): - return self.__evalBinary(other, literals.SubtractionOperator, False) + return self.__eval_binary(other, literals.SubtractionOperator, False) def __mul__(self, other): - return self.__evalBinary(other, literals.MultiplicationOperator) + return self.__eval_binary(other, literals.MultiplicationOperator) def __rmul__(self, other): - return self.__evalBinary(other, literals.MultiplicationOperator, False) + return self.__eval_binary( + other, literals.MultiplicationOperator, False + ) def __truediv__(self, other): - return self.__evalBinary(other, literals.DivisionOperator) + return self.__eval_binary(other, literals.DivisionOperator) def __rtruediv__(self, other): - return self.__evalBinary(other, literals.DivisionOperator, False) + return self.__eval_binary(other, literals.DivisionOperator, False) # Python 2 Compatibility ------------------------------------------------- @@ -520,19 +522,21 @@ def __rtruediv__(self, other): # ------------------------------------------------------------------------ def __pow__(self, other): - return self.__evalBinary(other, literals.ExponentiationOperator) + return self.__eval_binary(other, literals.ExponentiationOperator) def __rpow__(self, other): - return self.__evalBinary(other, literals.ExponentiationOperator, False) + return self.__eval_binary( + other, literals.ExponentiationOperator, False + ) def __mod__(self, other): - return self.__evalBinary(other, literals.RemainderOperator) + return self.__eval_binary(other, literals.RemainderOperator) def __rmod__(self, other): - return self.__evalBinary(other, literals.RemainderOperator, False) + return self.__eval_binary(other, literals.RemainderOperator, False) def __neg__(self): - return self.__evalUnary(literals.NegationOperator) + return self.__eval_unary(literals.NegationOperator) # These are used by the class. @@ -706,7 +710,7 @@ def getBuilder(name): return _builders[name] -def __wrapNumpyOperators(): +def __wrap_numpy_operators(): """Export all numpy operators as OperatorBuilder instances in the module namespace.""" for name in dir(numpy): @@ -716,11 +720,11 @@ def __wrapNumpyOperators(): return -__wrapNumpyOperators() +__wrap_numpy_operators() # Register other functions as well -def __wrapSrFitOperators(): +def __wrap_srfit_operators(): """Export all non-base operators from the diffpy.srfit.equation.literals.operators module as OperatorBuilder instances in the module namespace.""" @@ -744,6 +748,6 @@ def _is_exported_type(cls): return -__wrapSrFitOperators() +__wrap_srfit_operators() # End of file diff --git a/src/diffpy/srfit/equation/equationmod.py b/src/diffpy/srfit/equation/equationmod.py index aab8d99f..dd8293ec 100644 --- a/src/diffpy/srfit/equation/equationmod.py +++ b/src/diffpy/srfit/equation/equationmod.py @@ -125,10 +125,10 @@ def operation(self, *args, **kw): """ return self.__call__(*args, **kw) - def _getArgs(self): + def _get_args(self): return list(self.argdict.values()) - args = property(_getArgs) + args = property(_get_args) def __getattr__(self, name): """Gives access to the Arguments as attributes.""" diff --git a/src/diffpy/srfit/equation/literals/operators.py b/src/diffpy/srfit/equation/literals/operators.py index 98264bec..a7863808 100644 --- a/src/diffpy/srfit/equation/literals/operators.py +++ b/src/diffpy/srfit/equation/literals/operators.py @@ -113,7 +113,7 @@ def addLiteral(self, literal): Raises ValueError if the literal causes a self-reference. """ # Make sure we don't have self-reference - self._loopCheck(literal) + self._loop_check(literal) self.args.append(literal) literal.addObserver(self._flush) self._flush(other=(self,)) @@ -128,7 +128,7 @@ def getValue(self): value = property(lambda self: self.getValue()) - def _loopCheck(self, literal): + def _loop_check(self, literal): """Check if a literal causes self-reference.""" if literal is self: raise ValueError("'%s' causes self-reference" % literal) @@ -136,7 +136,7 @@ def _loopCheck(self, literal): # Check to see if I am a dependency of the literal. if hasattr(literal, "args"): for lit_arg in literal.args: - self._loopCheck(lit_arg) + self._loop_check(lit_arg) return diff --git a/src/diffpy/srfit/equation/visitors/printer.py b/src/diffpy/srfit/equation/visitors/printer.py index 4926c9ae..98cfab6a 100644 --- a/src/diffpy/srfit/equation/visitors/printer.py +++ b/src/diffpy/srfit/equation/visitors/printer.py @@ -87,7 +87,7 @@ def onOperator(self, op): """Process an Operator node.""" # We have to deal with infix operators if op.name != op.symbol and op.nin == 2: - self._onInfix(op) + self._on_infix(op) return self.output self.output += str(op.name) + "(" @@ -111,7 +111,7 @@ def onEquation(self, eq): eq.root.identify(self) return self.output - def _onInfix(self, op): + def _on_infix(self, op): """Process infix operators.""" self.output += "(" op.args[0].identify(self) diff --git a/src/diffpy/srfit/equation/visitors/swapper.py b/src/diffpy/srfit/equation/visitors/swapper.py index b5ddbf4d..a6135750 100644 --- a/src/diffpy/srfit/equation/visitors/swapper.py +++ b/src/diffpy/srfit/equation/visitors/swapper.py @@ -105,7 +105,7 @@ def onOperator(self, op): # Validate the new literal. If it fails, we need to restore the # old one try: - op._loopCheck(newlit) + op._loop_check(newlit) except ValueError: # Restore the old literal op.args.insert(idx, oldlit) @@ -135,9 +135,9 @@ def onEquation(self, eq): eq.setRoot(self.newlit) return - # Now move into the equation. We have to do a _loopCheck to make sure + # Now move into the equation. We have to do a _loop_check to make sure # that we won't have any loops in the equation. - eq._loopCheck(self.newlit) + eq._loop_check(self.newlit) eq.root.identify(self) # Reset the root in case anything changed underneath. diff --git a/src/diffpy/srfit/fitbase/configurable.py b/src/diffpy/srfit/fitbase/configurable.py index a06c62ba..8fb275bc 100644 --- a/src/diffpy/srfit/fitbase/configurable.py +++ b/src/diffpy/srfit/fitbase/configurable.py @@ -37,13 +37,13 @@ def __init__(self): self._configobjs = set() return - def _updateConfiguration(self): + def _update_configuration(self): """Notify Configurables in hierarchy of configuration change.""" for obj in self._configobjs: - obj._updateConfiguration() + obj._update_configuration() return - def _storeConfigurable(self, obj): + def _store_configurable(self, obj): """Store a Configurable. The passed obj is only stored if it is a a Configurable, diff --git a/src/diffpy/srfit/fitbase/fitcontribution.py b/src/diffpy/srfit/fitbase/fitcontribution.py index b203cb22..5db67996 100644 --- a/src/diffpy/srfit/fitbase/fitcontribution.py +++ b/src/diffpy/srfit/fitbase/fitcontribution.py @@ -188,7 +188,7 @@ def addProfileGenerator(self, gen, name=None): # Register the generator with the equation factory and add it as a # managed object. self._eqfactory.registerOperator(name, gen) - self._addObject(gen, self._generators, True) + self._add_object(gen, self._generators, True) # If we have a profile, set the profile of the generator. if self.profile is not None: @@ -231,7 +231,7 @@ def setEquation(self, eqstr, ns={}): # Register any new Parameters. for par in self._eqfactory.newargs: - self._addParameter(par) + self._add_parameter(par) # Register eq as an operator self._eqfactory.registerOperator("eq", eq) diff --git a/src/diffpy/srfit/fitbase/fitrecipe.py b/src/diffpy/srfit/fitbase/fitrecipe.py index 229d2447..ffc1d595 100644 --- a/src/diffpy/srfit/fitbase/fitrecipe.py +++ b/src/diffpy/srfit/fitbase/fitrecipe.py @@ -173,7 +173,7 @@ def pushFitHook(self, fithook, index=None): index = len(self.fithooks) self.fithooks.insert(index, fithook) # Make sure the added FitHook gets its reset method called. - self._updateConfiguration() + self._update_configuration() return def popFitHook(self, fithook=None, index=-1): @@ -220,7 +220,7 @@ def addContribution(self, con, weight=1.0): Raises ValueError if the FitContribution has the same name as some other managed object. """ - self._addObject(con, self._contributions, True) + self._add_object(con, self._contributions, True) self._weights.append(weight) return @@ -243,7 +243,7 @@ def addParameterSet(self, parset): Raises ValueError if the ParameterSet has the same name as some other managed object. """ - self._addObject(parset, self._parsets, True) + self._add_object(parset, self._parsets, True) return def removeParameterSet(self, parset): @@ -251,7 +251,7 @@ def removeParameterSet(self, parset): Raises ValueError if parset is not managed by this object. """ - self._removeObject(parset, self._parsets) + self._remove_object(parset, self._parsets) return def residual(self, p=[]): @@ -279,7 +279,7 @@ def residual(self, p=[]): fithook.precall(self) # Update the variable parameters. - self._applyValues(p) + self._apply_values(p) # Update the constraints. These are ordered such that the list only # needs to be cycled once. @@ -351,13 +351,13 @@ def _prepare(self): fithook.reset(self) # Check Profiles - self.__verifyProfiles() + self.__verify_profiles() # Check parameters - self.__verifyParameters() + self.__verify_parameters() # Update constraints and restraints. - self.__collectConstraintsAndRestraints() + self.__collect_constraints_and_restraints() # We do this here so that the calculations that take place during the # validation use the most current values of the parameters. In most @@ -372,7 +372,7 @@ def _prepare(self): return - def __verifyProfiles(self): + def __verify_profiles(self): """Verify that each FitContribution has a Profile.""" # Check for profile values for con in self._contributions.values(): @@ -389,7 +389,7 @@ def __verifyProfiles(self): raise AttributeError(m) return - def __verifyParameters(self): + def __verify_parameters(self): """Verify that all Parameters have values.""" # Get all parameters with a value of None @@ -403,7 +403,7 @@ def __verifyParameters(self): # Get the bad names badnames = [] for par in badpars: - objlist = self._locateManagedObject(par) + objlist = self._locate_managed_object(par) names = [obj.name for obj in objlist] badnames.append(".".join(names)) @@ -421,7 +421,7 @@ def __verifyParameters(self): return - def __collectConstraintsAndRestraints(self): + def __collect_constraints_and_restraints(self): """Collect the Constraints and Restraints from subobjects.""" from functools import cmp_to_key from itertools import chain @@ -430,8 +430,8 @@ def __collectConstraintsAndRestraints(self): cdict = {} for org in chain(self._contributions.values(), self._parsets.values()): - rset.update(org._getRestraints()) - cdict.update(org._getConstraints()) + rset.update(org._get_restraints()) + cdict.update(org._get_constraints()) cdict.update(self._constraints) # The order of the restraint list does not matter @@ -533,7 +533,7 @@ def addVar( if value is not None: var.setValue(value) - self._addParameter(var) + self._add_parameter(var) if fixed: self.fix(var) @@ -561,7 +561,7 @@ def delVar(self, var): Raises ValueError if var is not part of the FitRecipe. """ - self._removeParameter(var) + self._remove_parameter(var) self._tagmanager.untag(var) return @@ -605,7 +605,7 @@ def newVar(self, name, value=None, fixed=False, tag=None, tags=[]): Returns the new variable (Parameter instance). """ # This will fix the Parameter - var = self._newParameter(name, value) + var = self._new_parameter(name, value) # We may explicitly free it if not fixed: @@ -618,19 +618,19 @@ def newVar(self, name, value=None, fixed=False, tag=None, tags=[]): return var - def _newParameter(self, name, value, check=True): + def _new_parameter(self, name, value, check=True): """Overloaded to tag variables. - See RecipeOrganizer._newParameter + See RecipeOrganizer._new_parameter """ - par = RecipeOrganizer._newParameter(self, name, value, check) + par = RecipeOrganizer._new_parameter(self, name, value, check) # tag this self._tagmanager.tag(par, par.name) self._tagmanager.tag(par, "all") self.fix(par.name) return par - def __getVarAndCheck(self, var): + def __get_var_and_check(self, var): """Get the actual variable from var. Attributes @@ -649,7 +649,7 @@ def __getVarAndCheck(self, var): return var - def __getVarsFromArgs(self, *args, **kw): + def __get_vars_from_args(self, *args, **kw): """Get a list of variables from passed arguments. This method accepts string or variable arguments. An argument of @@ -705,7 +705,7 @@ def fix(self, *args, **kw): passed, or if a tag is passed in a keyword. """ # Check the inputs and get the variables from them - varargs = self.__getVarsFromArgs(*args, **kw) + varargs = self.__get_vars_from_args(*args, **kw) # Fix all of these for var in varargs: @@ -731,7 +731,7 @@ def free(self, *args, **kw): passed, or if a tag is passed in a keyword. """ # Check the inputs and get the variables from them - varargs = self.__getVarsFromArgs(*args, **kw) + varargs = self.__get_vars_from_args(*args, **kw) # Free all of these for var in varargs: @@ -781,7 +781,7 @@ def unconstrain(self, *pars): if update: # Our configuration changed - self._updateConfiguration() + self._update_configuration() return @@ -893,7 +893,7 @@ def boundsToRestraints(self, sig=1, scaled=False): ) return - def _applyValues(self, p): + def _apply_values(self, p): """Apply variable values to the variables.""" if len(p) == 0: return @@ -902,7 +902,7 @@ def _applyValues(self, p): var.setValue(pval) return - def _updateConfiguration(self): + def _update_configuration(self): """Notify RecipeContainers in hierarchy of configuration change.""" self._ready = False return diff --git a/src/diffpy/srfit/fitbase/fitresults.py b/src/diffpy/srfit/fitbase/fitresults.py index 108c2fcf..1949526a 100644 --- a/src/diffpy/srfit/fitbase/fitresults.py +++ b/src/diffpy/srfit/fitbase/fitresults.py @@ -165,7 +165,7 @@ def update(self): if self.varnames: # Calculate the covariance - self._calculateCovariance() + self._calculate_covariance() # Get the variable uncertainties self.varunc = [ @@ -173,7 +173,7 @@ def update(self): ] # Get the constraint uncertainties - self._calculateConstraintUncertainties() + self._calculate_constraint_uncertainties() # Store the fitting arrays and metrics for each FitContribution. self.conresults = OrderedDict() @@ -185,7 +185,7 @@ def update(self): # Calculate the metrics res = recipe.residual() self.residual = numpy.dot(res, res) - self._calculateMetrics() + self._calculate_metrics() # Calculate the restraints penalty w = self.chi2 / len(res) @@ -193,14 +193,14 @@ def update(self): return - def _calculateCovariance(self): + def _calculate_covariance(self): """Calculate the covariance matrix. This is called by update. This code borrowed from PARK. It finds the pseudo-inverse of the Jacobian using the singular value decomposition. """ try: - J = self._calculateJacobian() + J = self._calculate_jacobian() u, s, vh = numpy.linalg.svd(J, 0) self.cov = numpy.dot(vh.T.conj() / s**2, vh) except numpy.linalg.LinAlgError: @@ -209,7 +209,7 @@ def _calculateCovariance(self): self.cov = numpy.zeros((lvarvals, lvarvals), dtype=float) return - def _calculateJacobian(self): + def _calculate_jacobian(self): """Calculate the Jacobian for the fitting. Adapted from PARK. Returns the derivative wrt the fit variables @@ -276,7 +276,7 @@ def _calculateJacobian(self): jac = numpy.vstack(r).T return jac - def _calculateMetrics(self): + def _calculate_metrics(self): """Calculate chi2, cumchi2, rchi2, rw and cumrw for the recipe.""" cumchi2 = numpy.array([], dtype=float) # total weighed denominator for the ratio in the Rw formula @@ -303,7 +303,7 @@ def _calculateMetrics(self): self.cumrw = cumrw return - def _calculateConstraintUncertainties(self): + def _calculate_constraint_uncertainties(self): """Calculate the uncertainty on the constrained parameters.""" vu = self.varunc @@ -600,7 +600,7 @@ class ContributionResults(object): conlocs The location of the constrained parameters in the FitContribution (see the - RecipeContainer._locateManagedObject method). + RecipeContainer._locate_managed_object method). convals Values of the constrained parameters. conunc @@ -657,12 +657,12 @@ def _init(self, con, weight, fitres): self.ycalc = numpy.array(con.profile.ycalc) # The other metrics - self._calculateMetrics() + self._calculate_metrics() # Find the parameters for i, constraint in enumerate(recipe._oconstraints): par = constraint.par - loc = con._locateManagedObject(par) + loc = con._locate_managed_object(par) if loc: self.conlocs.append(loc) self.convals.append(fitres.convals[i]) @@ -671,7 +671,7 @@ def _init(self, con, weight, fitres): return # FIXME: factor rw, chi2, cumrw, cumchi2 to separate functions. - def _calculateMetrics(self): + def _calculate_metrics(self): """Calculate chi2 and Rw of the recipe.""" # We take absolute values in case the signal is complex num = numpy.abs(self.y - self.ycalc) diff --git a/src/diffpy/srfit/fitbase/parameterset.py b/src/diffpy/srfit/fitbase/parameterset.py index 53edb035..ce89326f 100644 --- a/src/diffpy/srfit/fitbase/parameterset.py +++ b/src/diffpy/srfit/fitbase/parameterset.py @@ -83,9 +83,9 @@ def __init__(self, name): return # Alias Parameter accessors. - addParameter = RecipeOrganizer._addParameter - newParameter = RecipeOrganizer._newParameter - removeParameter = RecipeOrganizer._removeParameter + addParameter = RecipeOrganizer._add_parameter + newParameter = RecipeOrganizer._new_parameter + removeParameter = RecipeOrganizer._remove_parameter def addParameterSet(self, parset): """Add a ParameterSet to the hierarchy. @@ -100,7 +100,7 @@ def addParameterSet(self, parset): Raises ValueError if the ParameterSet has the same name as some other managed object. """ - self._addObject(parset, self._parsets, True) + self._add_object(parset, self._parsets, True) return def removeParameterSet(self, parset): @@ -108,7 +108,7 @@ def removeParameterSet(self, parset): Raises ValueError if parset is not managed by this object. """ - self._removeObject(parset, self._parsets) + self._remove_object(parset, self._parsets) return def setConst(self, const=True): diff --git a/src/diffpy/srfit/fitbase/recipeorganizer.py b/src/diffpy/srfit/fitbase/recipeorganizer.py index a76593d5..3b95a216 100644 --- a/src/diffpy/srfit/fitbase/recipeorganizer.py +++ b/src/diffpy/srfit/fitbase/recipeorganizer.py @@ -50,7 +50,7 @@ class RecipeContainer(Observable, Configurable, Validatable): RecipeContainers are hierarchical organizations of Parameters and other RecipeContainers. This class provides attribute-access to these contained objects. Parameters and other RecipeContainers can be found within the - hierarchy with the _locateManagedObject method. + hierarchy with the _locate_managed_object method. A RecipeContainer can manage dictionaries for that store various objects. These dictionaries can be added to the RecipeContainer using the _manage @@ -112,7 +112,7 @@ def _manage(self, d): self.__managed.append(d) return - def _iterManaged(self): + def _iter_managed(self): """Get iterator over managed objects.""" return chain(*(d.values() for d in self.__managed)) @@ -210,7 +210,7 @@ def __delattr__(self, name): general way. """ if name in self._parameters: - self._removeParameter(self._parameters[name]) + self._remove_parameter(self._parameters[name]) return m = self.get(name) @@ -237,7 +237,7 @@ def getValues(self): """Get the values of managed parameters.""" return [p.value for p in self._parameters.values()] - def _addObject(self, obj, d, check=True): + def _add_object(self, obj, d, check=True): """Add an object to a managed dictionary. Attributes @@ -289,10 +289,10 @@ def _addObject(self, obj, d, check=True): obj.addObserver(self._flush) # Store this as a configurable object - self._storeConfigurable(obj) + self._store_configurable(obj) return - def _removeObject(self, obj, d): + def _remove_object(self, obj, d): """Remove an object from a managed dictionary. Raises ValueError if obj is not part of the dictionary. @@ -306,7 +306,7 @@ def _removeObject(self, obj, d): return - def _locateManagedObject(self, obj): + def _locate_managed_object(self, obj): """Find the location a managed object within the hierarchy. Attributes @@ -326,7 +326,7 @@ def _locateManagedObject(self, obj): if obj is self: return loc - for m in self._iterManaged(): + for m in self._iter_managed(): # Check locally for the object if m is obj: @@ -334,9 +334,9 @@ def _locateManagedObject(self, obj): return loc # Check within managed objects - if hasattr(m, "_locateManagedObject"): + if hasattr(m, "_locate_managed_object"): - subloc = m._locateManagedObject(obj) + subloc = m._locate_managed_object(obj) if subloc: return loc + subloc @@ -359,8 +359,8 @@ def _validate(self): Raises AttributeError if validation fails. """ - iterable = chain(self.__iter__(), self._iterManaged()) - self._validateOthers(iterable) + iterable = chain(self.__iter__(), self._iter_managed()) + self._validate_others(iterable) return @@ -374,7 +374,7 @@ class RecipeOrganizer(_recipeorganizer_interface, RecipeContainer): Restraints, as well as Equations that can be used in Constraint and Restraint equations. These constraints and Restraints can be placed at any level and a flattened list of them can be retrieved with the - _getConstraints and _getRestraints methods. + _get_constraints and _get_restraints methods. Attributes ---------- @@ -420,19 +420,19 @@ def __init__(self, name): # Parameter management - def _newParameter(self, name, value, check=True): + def _new_parameter(self, name, value, check=True): """Add a new Parameter to the container. This creates a new Parameter and adds it to the container using - the _addParameter method. + the _add_parameter method. Returns the Parameter. """ p = Parameter(name, value) - self._addParameter(p, check) + self._add_parameter(p, check) return p - def _addParameter(self, par, check=True): + def _add_parameter(self, par, check=True): """Store a Parameter. Parameters added in this way are registered with the _eqfactory. @@ -452,13 +452,13 @@ def _addParameter(self, par, check=True): """ # Store the Parameter - RecipeContainer._addObject(self, par, self._parameters, check) + RecipeContainer._add_object(self, par, self._parameters, check) # Register the Parameter self._eqfactory.registerArgument(par.name, par) return - def _removeParameter(self, par): + def _remove_parameter(self, par): """Remove a parameter. This de-registers the Parameter with the _eqfactory. The @@ -469,7 +469,7 @@ def _removeParameter(self, par): Raises ValueError if par is not part of the RecipeOrganizer. """ - self._removeObject(par, self._parameters) + self._remove_object(par, self._parameters) self._eqfactory.deRegisterBuilder(par.name) return @@ -492,7 +492,7 @@ def registerCalculator(self, f, argnames=None): extracted from the function. """ self._eqfactory.registerOperator(f.name, f) - self._addObject(f, self._calculators) + self._add_object(f, self._calculators) # Register arguments of the calculator if argnames is None: fncode = f.__call__.__func__.__code__ @@ -501,7 +501,7 @@ def registerCalculator(self, f, argnames=None): for pname in argnames: if pname not in self._eqfactory.builders: - par = self._newParameter(pname, 0) + par = self._new_parameter(pname, 0) else: par = self.get(pname) f.addLiteral(par) @@ -598,7 +598,7 @@ def registerFunction(self, f, name=None, argnames=None): # Make missing Parameters for pname in argnames: if pname not in self._eqfactory.builders: - self._newParameter(pname, 0) + self._new_parameter(pname, 0) # Initialize and register from diffpy.srfit.fitbase.calculator import Calculator @@ -649,7 +649,7 @@ def registerStringFunction(self, fstr, name, ns={}): # Register any new Parameters. for par in self._eqfactory.newargs: - self._addParameter(par) + self._add_parameter(par) # Register the equation as a callable function. argnames = eq.argdict.keys() @@ -733,7 +733,7 @@ def constrain(self, par, con, ns={}): self._constraints[par] = con # Our configuration changed - self._updateConfiguration() + self._update_configuration() return @@ -780,7 +780,7 @@ def unconstrain(self, *pars): if update: # Our configuration changed - self._updateConfiguration() + self._update_configuration() else: @@ -797,7 +797,7 @@ def getConstrainedPars(self, recurse=False): Recurse into managed objects and retrieve their constrained Parameters as well (default False). """ - const = self._getConstraints(recurse) + const = self._get_constraints(recurse) return const.keys() def clearConstraints(self, recurse=False): @@ -817,7 +817,7 @@ def clearConstraints(self, recurse=False): self.unconstrain(*self._constraints) if recurse: - for m in filter(_has_clear_constraints, self._iterManaged()): + for m in filter(_has_clear_constraints, self._iter_managed()): m.clearConstraints(recurse) return @@ -881,7 +881,7 @@ def addRestraint(self, res): """ self._restraints.add(res) # Our configuration changed. Notify observers. - self._updateConfiguration() + self._update_configuration() return def unrestrain(self, *ress): @@ -902,7 +902,7 @@ def unrestrain(self, *ress): if update: # Our configuration changed - self._updateConfiguration() + self._update_configuration() return @@ -917,30 +917,30 @@ def clearRestraints(self, recurse=False): """ self.unrestrain(*self._restraints) if recurse: - for msg in filter(_has_clear_restraints, self._iterManaged()): + for msg in filter(_has_clear_restraints, self._iter_managed()): msg.clearRestraints(recurse) return - def _getConstraints(self, recurse=True): + def _get_constraints(self, recurse=True): """Get the constrained Parameters for this and managed sub-objects.""" constraints = {} if recurse: - for m in filter(_has_get_constraints, self._iterManaged()): - constraints.update(m._getConstraints(recurse)) + for m in filter(_has_get_constraints, self._iter_managed()): + constraints.update(m._get_constraints(recurse)) constraints.update(self._constraints) return constraints - def _getRestraints(self, recurse=True): + def _get_restraints(self, recurse=True): """Get the Restraints for this and embedded ParameterSets. This returns a set of Restraint objects. """ restraints = set(self._restraints) if recurse: - for m in filter(_has_get_restraints, self._iterManaged()): - restraints.update(m._getRestraints(recurse)) + for m in filter(_has_get_restraints, self._iter_managed()): + restraints.update(m._get_restraints(recurse)) return restraints @@ -954,12 +954,12 @@ def _validate(self): """ RecipeContainer._validate(self) iterable = chain(self._restraints, self._constraints.values()) - self._validateOthers(iterable) + self._validate_others(iterable) return # For printing the configured recipe to screen - def _formatManaged(self, prefix=""): + def _format_managed(self, prefix=""): """Format hierarchy of managed parameters for showing. Parameters @@ -984,15 +984,15 @@ def _formatManaged(self, prefix=""): for n, p in self._parameters.items() ) # Recurse into managed objects. - for obj in self._iterManaged(): - if hasattr(obj, "_formatManaged"): + for obj in self._iter_managed(): + if hasattr(obj, "_format_managed"): oprefix = prefix + obj.name + "." - tlines = obj._formatManaged(prefix=oprefix) + tlines = obj._format_managed(prefix=oprefix) lines.extend([""] if lines and tlines else []) lines.extend(tlines) return lines - def _formatConstraints(self): + def _format_constraints(self): """Format constraints for showing. This collects constraints on all levels of the hierarchy and displays @@ -1004,11 +1004,11 @@ def _formatConstraints(self): List of formatted lines displaying the defined constraints. Return empty list when no constraints were defined. """ - cdict = self._getConstraints() + cdict = self._get_constraints() # Find each constraint and format the equation clines = [] for par, con in cdict.items(): - loc = self._locateManagedObject(par) + loc = self._locate_managed_object(par) if loc: locstr = ".".join(o.name for o in loc[1:]) clines.append("%s <-- %s" % (locstr, con.eqstr)) @@ -1017,7 +1017,7 @@ def _formatConstraints(self): clines.sort(key=numstr) return clines - def _formatRestraints(self): + def _format_restraints(self): """Format restraints for showing. This collects restraints on all levels of the hierarchy and displays @@ -1029,7 +1029,7 @@ def _formatRestraints(self): List of formatted lines displaying the defined restraints. Return empty list when no restraints were defined. """ - rset = self._getRestraints() + rset = self._get_restraints() rlines = [] for res in rset: line = "%s: lb = %f, ub = %f, sig = %f, scaled = %s" % ( @@ -1061,7 +1061,7 @@ def show(self, pattern="", textwidth=78): _pmatch_with_re = partial(_pmatch, regexp=regexp) # Show sub objects and their parameters lines = [] - tlines = self._formatManaged() + tlines = self._format_managed() if tlines: lines.extend(["Parameters", _DASHEDLINE]) linesok = filter(_pmatch_with_re, tlines) @@ -1076,7 +1076,7 @@ def show(self, pattern="", textwidth=78): # FIXME - parameter names in equations not particularly informative # Show constraints cmatch = regexp.search - tlines = self._formatConstraints() + tlines = self._format_constraints() if tlines: if lines: lines.append("") @@ -1085,7 +1085,7 @@ def show(self, pattern="", textwidth=78): # FIXME - parameter names in equations not particularly informative # Show restraints - tlines = self._formatRestraints() + tlines = self._format_restraints() if tlines: if lines: lines.append("") @@ -1165,11 +1165,11 @@ def _has_clear_restraints(msg): def _has_get_restraints(msg): - return hasattr(msg, "_getRestraints") + return hasattr(msg, "_get_restraints") def _has_get_constraints(msg): - return hasattr(msg, "_getConstraints") + return hasattr(msg, "_get_constraints") def _pmatch(inp_str, regexp): diff --git a/src/diffpy/srfit/fitbase/validatable.py b/src/diffpy/srfit/fitbase/validatable.py index a3aeac66..5a28b132 100644 --- a/src/diffpy/srfit/fitbase/validatable.py +++ b/src/diffpy/srfit/fitbase/validatable.py @@ -27,7 +27,7 @@ class Validatable(object): A Validatable has state that must be validated by a FitRecipe. """ - def _validateOthers(self, iterable): + def _validate_others(self, iterable): """Method to validate configuration of Validatables in iterable. This is provided as a convenience for derived classes. No need diff --git a/src/diffpy/srfit/interface/interface.py b/src/diffpy/srfit/interface/interface.py index a0b7a21a..63ccb573 100644 --- a/src/diffpy/srfit/interface/interface.py +++ b/src/diffpy/srfit/interface/interface.py @@ -81,19 +81,19 @@ def __imod__(self, args): return self def __iadd__(self, args): - """_newParameter or _addParameter with += + """_new_parameter or _add_parameter with += Think of "+" as addition of a Parameter. This accepts arguments for a single function call. """ - # Want to detect _addParameter or _newParameter + # Want to detect _add_parameter or _new_parameter def f(*args): if isinstance(args[0], six.string_types): - self._newParameter(*args) + self._new_parameter(*args) else: - self._addParameter(*args) + self._add_parameter(*args) return _applyargs(args, f) diff --git a/src/diffpy/srfit/pdf/basepdfgenerator.py b/src/diffpy/srfit/pdf/basepdfgenerator.py index da867bca..e91023e8 100644 --- a/src/diffpy/srfit/pdf/basepdfgenerator.py +++ b/src/diffpy/srfit/pdf/basepdfgenerator.py @@ -108,7 +108,7 @@ def __init__(self, name="pdf"): _parnames = ["delta1", "delta2", "qbroad", "scale", "qdamp"] - def _setCalculator(self, calc): + def _set_calculator(self, calc): """Set the SrReal calculator instance. Setting the calculator creates Parameters from the variable @@ -320,7 +320,7 @@ def __call__(self, r): if not numpy.array_equal(r, self._lastr): self._prepare(r) - rcalc, y = self._calc(self._phase._getSrRealStructure()) + rcalc, y = self._calc(self._phase._get_srreal_structure()) if numpy.isnan(y).any(): y = numpy.zeros_like(r) diff --git a/src/diffpy/srfit/pdf/debyepdfgenerator.py b/src/diffpy/srfit/pdf/debyepdfgenerator.py index 8b359779..641c577f 100644 --- a/src/diffpy/srfit/pdf/debyepdfgenerator.py +++ b/src/diffpy/srfit/pdf/debyepdfgenerator.py @@ -135,7 +135,7 @@ def __init__(self, name="pdf"): from diffpy.srreal.pdfcalculator import DebyePDFCalculator BasePDFGenerator.__init__(self, name) - self._setCalculator(DebyePDFCalculator()) + self._set_calculator(DebyePDFCalculator()) return diff --git a/src/diffpy/srfit/pdf/pdfcontribution.py b/src/diffpy/srfit/pdf/pdfcontribution.py index 68bdac86..2679a3ff 100644 --- a/src/diffpy/srfit/pdf/pdfcontribution.py +++ b/src/diffpy/srfit/pdf/pdfcontribution.py @@ -217,7 +217,7 @@ def addStructure(self, name, stru, periodic=True): # Set up the generator gen.setStructure(stru, "phase", periodic) - self._setupGenerator(gen) + self._setup_generator(gen) return gen.phase @@ -262,11 +262,11 @@ def addPhase(self, name, parset, periodic=True): # Set up the generator gen.setPhase(parset, periodic) - self._setupGenerator(gen) + self._setup_generator(gen) return gen.phase - def _setupGenerator(self, gen): + def _setup_generator(self, gen): """Setup a generator. The generator must already have a managed SrRealParSet, added @@ -293,7 +293,7 @@ def _setupGenerator(self, gen): # Calculation setup methods - def _getMetaValue(self, kwd): + def _get_meta_value(self, kwd): """Get metadata according to object hierarchy.""" # Check self, then generators then profile if kwd in self._meta: @@ -324,7 +324,7 @@ def getScatteringType(self): See 'setScatteringType'. """ - return self._getMetaValue("stype") + return self._get_meta_value("stype") def setQmax(self, qmax): """Set the qmax value.""" @@ -335,7 +335,7 @@ def setQmax(self, qmax): def getQmax(self): """Get the qmax value.""" - return self._getMetaValue("qmax") + return self._get_meta_value("qmax") def setQmin(self, qmin): """Set the qmin value.""" @@ -346,7 +346,7 @@ def setQmin(self, qmin): def getQmin(self): """Get the qmin value.""" - return self._getMetaValue("qmin") + return self._get_meta_value("qmin") # End of file diff --git a/src/diffpy/srfit/pdf/pdfgenerator.py b/src/diffpy/srfit/pdf/pdfgenerator.py index 3f30cb0c..3a2f919b 100644 --- a/src/diffpy/srfit/pdf/pdfgenerator.py +++ b/src/diffpy/srfit/pdf/pdfgenerator.py @@ -88,7 +88,7 @@ def __init__(self, name="pdf"): from diffpy.srreal.pdfcalculator import PDFCalculator BasePDFGenerator.__init__(self, name) - self._setCalculator(PDFCalculator()) + self._set_calculator(PDFCalculator()) return diff --git a/src/diffpy/srfit/sas/prcalculator.py b/src/diffpy/srfit/sas/prcalculator.py index 74fd811a..17c63de6 100644 --- a/src/diffpy/srfit/sas/prcalculator.py +++ b/src/diffpy/srfit/sas/prcalculator.py @@ -82,10 +82,10 @@ def __init__(self, name): self._invertor = Invertor() - self._newParameter("scale", 1) - self._newParameter("q", None) - self._newParameter("iq", None) - self._newParameter("diq", None) + self._new_parameter("scale", 1) + self._new_parameter("q", None) + self._new_parameter("iq", None) + self._new_parameter("diq", None) return def __call__(self, r): diff --git a/src/diffpy/srfit/structure/bvsrestraint.py b/src/diffpy/srfit/structure/bvsrestraint.py index da00b397..f8af1ebe 100644 --- a/src/diffpy/srfit/structure/bvsrestraint.py +++ b/src/diffpy/srfit/structure/bvsrestraint.py @@ -76,7 +76,7 @@ def penalty(self, w=1.0): penalty (float, default 1.0). """ # Get the bvms from the BVSCalculator - stru = self._parset._getSrRealStructure() + stru = self._parset._get_srreal_structure() self._calc.eval(stru) penalty = self._calc.bvmsdiff diff --git a/src/diffpy/srfit/structure/cctbxparset.py b/src/diffpy/srfit/structure/cctbxparset.py index fd56a2f3..2bb05c7d 100644 --- a/src/diffpy/srfit/structure/cctbxparset.py +++ b/src/diffpy/srfit/structure/cctbxparset.py @@ -120,10 +120,10 @@ def _setuiso(self, dummy, value): self.strups.stru.scatterers()[self.idx].u_iso = value return - def _getElem(self): + def _getelem(self): return self.stru.element_symbol() - element = property(_getElem) + element = property(_getelem) # End class CCTBXScattererParSet @@ -253,10 +253,10 @@ def __init__(self, name, stru): self.scatterers.append(scatterer) # Constrain the lattice - from diffpy.srfit.structure.sgconstraints import _constrainSpaceGroup + from diffpy.srfit.structure.sgconstraints import _constrain_space_group symbol = self.getSpaceGroup() - _constrainSpaceGroup(self, symbol) + _constrain_space_group(self, symbol) return diff --git a/src/diffpy/srfit/structure/diffpyparset.py b/src/diffpy/srfit/structure/diffpyparset.py index 7263e1f0..6ed3beef 100644 --- a/src/diffpy/srfit/structure/diffpyparset.py +++ b/src/diffpy/srfit/structure/diffpyparset.py @@ -151,13 +151,13 @@ def __init__(self, name, atom): def __repr__(self): return repr(self.atom) - def _getElem(self): + def _getelem(self): return self.atom.element - def _setElem(self, el): + def _setelem(self, el): self.atom.element = el - element = property(_getElem, _setElem, "type of atom") + element = property(_getelem, _setelem, "type of atom") # End class DiffpyAtomParSet @@ -326,7 +326,7 @@ def getScatterers(self): """ return self.atoms - def _getSrRealStructure(self): + def _get_srreal_structure(self): """Get the structure object for use with SrReal calculators. If this is periodic, then return the structure, otherwise, pass @@ -335,7 +335,7 @@ def _getSrRealStructure(self): """ from diffpy.srreal.structureadapter import nometa - stru = SrRealParSet._getSrRealStructure(self) + stru = SrRealParSet._get_srreal_structure(self) return nometa(stru) diff --git a/src/diffpy/srfit/structure/objcrystparset.py b/src/diffpy/srfit/structure/objcrystparset.py index dec7917f..19213b43 100644 --- a/src/diffpy/srfit/structure/objcrystparset.py +++ b/src/diffpy/srfit/structure/objcrystparset.py @@ -179,11 +179,11 @@ def __init__(self, name, atom, parent): self.Biso.value = 0.5 return - def _getElem(self): + def _getelem(self): """Getter for the element type.""" return self.scat.GetScatteringPower().GetSymbol() - element = property(_getElem) + element = property(_getelem) # End class ObjCrystAtomParSet @@ -282,7 +282,7 @@ def usingSymmetry(self): return False # Part of SrRealParSet interface - def _getSrRealStructure(self): + def _get_srreal_structure(self): """Get the structure object for use with SrReal calculators. Molecule objects are never periodic. Return the object and let @@ -809,7 +809,7 @@ def __init__(self, name, scat, parent): return - def _getElem(self): + def _getelem(self): """Getter for the element type.""" sp = self.scat.GetScatteringPower() if sp: @@ -817,7 +817,7 @@ def _getElem(self): else: return "dummy" - element = property(_getElem) + element = property(_getelem) def isDummy(self): """Indicate whether this atom is a dummy atom.""" @@ -1766,17 +1766,19 @@ def __init__(self, name, cryst): return - def _constrainSpaceGroup(self): + def _constrain_space_group(self): """Constrain the space group.""" if self._sgpars is not None: return self._sgpars - sg = self._createSpaceGroup(self.stru.GetSpaceGroup()) - from diffpy.srfit.structure.sgconstraints import _constrainAsSpaceGroup + sg = self._create_space_group(self.stru.GetSpaceGroup()) + from diffpy.srfit.structure.sgconstraints import ( + _constrain_as_space_group, + ) adpsymbols = ["B11", "B22", "B33", "B12", "B13", "B23"] isosymbol = "Biso" sgoffset = [0, 0, 0] - self._sgpars = _constrainAsSpaceGroup( + self._sgpars = _constrain_as_space_group( self, sg, self.scatterers, @@ -1786,10 +1788,10 @@ def _constrainSpaceGroup(self): ) return self._sgpars - sgpars = property(_constrainSpaceGroup) + sgpars = property(_constrain_space_group) @staticmethod - def _createSpaceGroup(sgobjcryst): + def _create_space_group(sgobjcryst): """Create a diffpy.structure SpaceGroup object from pyobjcryst. Attributes diff --git a/src/diffpy/srfit/structure/sgconstraints.py b/src/diffpy/srfit/structure/sgconstraints.py index ad3ba0eb..c9dbc5b9 100644 --- a/src/diffpy/srfit/structure/sgconstraints.py +++ b/src/diffpy/srfit/structure/sgconstraints.py @@ -108,7 +108,7 @@ def constrainAsSpaceGroup( sg = spacegroup if not isinstance(spacegroup, SpaceGroup): sg = GetSpaceGroup(spacegroup) - sgp = _constrainAsSpaceGroup( + sgp = _constrain_as_space_group( phase, sg, scatterers, @@ -122,7 +122,7 @@ def constrainAsSpaceGroup( return sgp -def _constrainAsSpaceGroup( +def _constrain_as_space_group( phase, sg, scatterers=None, @@ -201,7 +201,7 @@ def addParameter(self, par, check=True): Raises ValueError if the Parameter has no name. """ # Store the Parameter - RecipeContainer._addObject(self, par, self._parameters, check) + RecipeContainer._add_object(self, par, self._parameters, check) return @@ -317,49 +317,49 @@ def __iter__(self): or self._xyzpars is None or self._adppars is None ): - self._makeConstraints() + self._make_constraints() return RecipeContainer.__iter__(self) - latpars = property(lambda self: self._getLatPars()) + latpars = property(lambda self: self._get_lat_pars()) - def _getLatPars(self): + def _get_lat_pars(self): """Accessor for _latpars.""" if self._latpars is None: - self._constrainLattice() + self._constrain_lattice() return self._latpars - xyzpars = property(lambda self: self._getXYZPars()) + xyzpars = property(lambda self: self._get_xyz_pars()) - def _getXYZPars(self): + def _get_xyz_pars(self): """Accessor for _xyzpars.""" positions = [] for scatterer in self.scatterers: xyz = [scatterer.x, scatterer.y, scatterer.z] positions.append([p.value for p in xyz]) if self._xyzpars is None: - self._constrainXYZs(positions) + self._constrain_xyzs(positions) return self._xyzpars - adppars = property(lambda self: self._getADPPars()) + adppars = property(lambda self: self._get_adp_pars()) - def _getADPPars(self): + def _get_adp_pars(self): """Accessor for _adppars.""" positions = [] for scatterer in self.scatterers: xyz = [scatterer.x, scatterer.y, scatterer.z] positions.append([p.value for p in xyz]) if self._adppars is None: - self._constrainADPs(positions) + self._constrain_adps(positions) return self._adppars - def _makeConstraints(self): + def _make_constraints(self): """Constrain the structure to the space group. This works as described by the constrainAsSpaceGroup method. """ # Start by clearing the constraints - self._clearConstraints() + self._clear_constraints() scatterers = self.scatterers @@ -369,13 +369,13 @@ def _makeConstraints(self): xyz = [scatterer.x, scatterer.y, scatterer.z] positions.append([p.value for p in xyz]) - self._constrainLattice() - self._constrainXYZs(positions) - self._constrainADPs(positions) + self._constrain_lattice() + self._constrain_xyzs(positions) + self._constrain_adps(positions) return - def _clearConstraints(self): + def _clear_constraints(self): """Clear old constraints. This only clears constraints where new ones are going to be @@ -430,7 +430,7 @@ def _clearConstraints(self): return - def _constrainLattice(self): + def _constrain_lattice(self): """Constrain the lattice parameters.""" if not self.constrainlat: @@ -462,12 +462,12 @@ def _constrainLattice(self): for par in pars: # FIXME - the original parameter will still appear as # constrained. - newpar = self.__addPar(par.name, par) + newpar = self.__add_par(par.name, par) self._latpars.addParameter(newpar) return - def _constrainXYZs(self, positions): + def _constrain_xyzs(self, positions): """Constrain the positions. Attributes @@ -482,7 +482,7 @@ def _constrainXYZs(self, positions): sgoffset = self.sgoffset # We do this without ADPs here so we can skip much complication. See - # the _constrainADPs method for details. + # the _constrain_adps method for details. g = SymmetryConstraints(sg, positions, sgoffset=sgoffset) scatterers = self.scatterers @@ -494,7 +494,7 @@ def _constrainXYZs(self, positions): name, idx = pname.rsplit("_", 1) idx = int(idx) par = scatterers[idx].get(name) - newpar = self.__addPar(pname, par) + newpar = self.__add_par(pname, par) self._xyzpars.addParameter(newpar) # Constrain non-free xyz parameters @@ -510,7 +510,7 @@ def _constrainXYZs(self, positions): return - def _constrainADPs(self, positions): + def _constrain_adps(self, positions): """Constrain the ADPs. Attributes @@ -580,13 +580,13 @@ def _constrainADPs(self, positions): par = scatterer.get(isosymbol) if par is not None: parname = "%s_%i" % (isosymbol, idx) - newpar = self.__addPar(parname, par) + newpar = self.__add_par(parname, par) self._adppars.addParameter(newpar) isonames.append(newpar.name) else: par = scatterer.get(name) if par is not None: - newpar = self.__addPar(pname, par) + newpar = self.__add_par(pname, par) self._adppars.addParameter(newpar) # Constrain dependent isotropics @@ -613,7 +613,7 @@ def _constrainADPs(self, positions): pname, formula, scatterer, idx, self._parameters ) - def __addPar(self, parname, par): + def __add_par(self, parname, par): """Constrain a parameter via proxy with a specified name. Attributes @@ -635,12 +635,12 @@ def __addPar(self, parname, par): # New York (1969), p.60 -def _constrainTriclinic(lattice): +def _constrain_triclinic(lattice): """Make constraints for Triclinic systems.""" return -def _constrainMonoclinic(lattice): +def _constrain_monoclinic(lattice): """Make constraints for Monoclinic systems. alpha and beta are fixed to 90 unless alpha != beta and alpha == @@ -661,7 +661,7 @@ def _constrainMonoclinic(lattice): return -def _constrainOrthorhombic(lattice): +def _constrain_orthorhombic(lattice): """Make constraints for Orthorhombic systems. alpha, beta and gamma are constrained to 90 @@ -676,7 +676,7 @@ def _constrainOrthorhombic(lattice): return -def _constrainTetragonal(lattice): +def _constrain_tetragonal(lattice): """Make constraints for Tetragonal systems. b is constrained to a and alpha, beta and gamma are constrained to @@ -693,7 +693,7 @@ def _constrainTetragonal(lattice): return -def _constrainTrigonal(lattice): +def _constrain_trigonal(lattice): """Make constraints for Trigonal systems. If gamma == 120, then b is constrained to a, alpha and beta are @@ -718,7 +718,7 @@ def _constrainTrigonal(lattice): return -def _constrainHexagonal(lattice): +def _constrain_hexagonal(lattice): """Make constraints for Hexagonal systems. b is constrained to a, alpha and beta are constrained to 90 and @@ -736,7 +736,7 @@ def _constrainHexagonal(lattice): return -def _constrainCubic(lattice): +def _constrain_cubic(lattice): """Make constraints for Cubic systems. b and c are constrained to a, alpha, beta and gamma are constrained @@ -757,13 +757,13 @@ def _constrainCubic(lattice): # This is used to map the correct crystal system to the proper constraint # function. _constraintMap = { - "Triclinic": _constrainTriclinic, - "Monoclinic": _constrainMonoclinic, - "Orthorhombic": _constrainOrthorhombic, - "Tetragonal": _constrainTetragonal, - "Trigonal": _constrainTrigonal, - "Hexagonal": _constrainHexagonal, - "Cubic": _constrainCubic, + "Triclinic": _constrain_triclinic, + "Monoclinic": _constrain_monoclinic, + "Orthorhombic": _constrain_orthorhombic, + "Tetragonal": _constrain_tetragonal, + "Trigonal": _constrain_trigonal, + "Hexagonal": _constrain_hexagonal, + "Cubic": _constrain_cubic, } @@ -801,7 +801,7 @@ def _makeconstraint(parname, formula, scatterer, idx, ns={}): return par # Check to see if it is a constant - fval = _getFloat(formula) + fval = _get_float(formula) if fval is not None: par.setConst() return @@ -813,7 +813,7 @@ def _makeconstraint(parname, formula, scatterer, idx, ns={}): return -def _getFloat(formula): +def _get_float(formula): """Get a float from a formula string, or None if this is not possible.""" try: return eval(formula) diff --git a/src/diffpy/srfit/structure/srrealparset.py b/src/diffpy/srfit/structure/srrealparset.py index 4d7ddee3..5a5e5028 100644 --- a/src/diffpy/srfit/structure/srrealparset.py +++ b/src/diffpy/srfit/structure/srrealparset.py @@ -69,7 +69,7 @@ def restrainBVS(self, sig=1, scaled=False): # Add it to the _restraints set self._restraints.add(res) # Our configuration changed. Notify observers. - self._updateConfiguration() + self._update_configuration() # Return the Restraint object return res @@ -86,7 +86,7 @@ def usingSymmetry(self): """Check if symmetry is being used.""" return self._usesymmetry - def _getSrRealStructure(self): + def _get_srreal_structure(self): """Get the structure object for use with SrReal calculators. If this is periodic, then return the structure, otherwise, pass diff --git a/src/diffpy/srfit/util/observable.py b/src/diffpy/srfit/util/observable.py index ff71b7d5..08f2f33b 100644 --- a/src/diffpy/srfit/util/observable.py +++ b/src/diffpy/srfit/util/observable.py @@ -52,7 +52,7 @@ def notify(self, other=()): def addObserver(self, callable): """Add callable to the set of observers.""" - f = weak_ref(callable, fallback=_fbRemoveObserver) + f = weak_ref(callable, fallback=_fb_remove_observer) self._observers.add(f) return @@ -81,7 +81,7 @@ def __init__(self, **kwds): # Local helpers -------------------------------------------------------------- -def _fbRemoveObserver(fobs, semaphores): +def _fb_remove_observer(fobs, semaphores): # Remove WeakBoundMethod `fobs` from the observers of notifying object. # This is called from Observable.notify when the WeakBoundMethod # associated object dies. diff --git a/src/diffpy/srfit/util/tagmanager.py b/src/diffpy/srfit/util/tagmanager.py index 6e780427..9e981d64 100644 --- a/src/diffpy/srfit/util/tagmanager.py +++ b/src/diffpy/srfit/util/tagmanager.py @@ -87,7 +87,7 @@ def untag(self, obj, *tags): tags = self.tags(obj) for tag in tags: - oset = self.__getObjectSet(tag) + oset = self.__get_object_set(tag) if obj not in oset and not self.silent: raise KeyError("Tag '%s' does not apply" % tag) oset.discard(obj) @@ -107,7 +107,7 @@ def hasTags(self, obj, *tags): Returns bool """ - setgen = (self.__getObjectSet(t) for t in tags) + setgen = (self.__get_object_set(t) for t in tags) result = all(obj in s for s in setgen) return result @@ -118,7 +118,7 @@ def union(self, *tags): """ if not tags: return set() - setgen = (self.__getObjectSet(t) for t in tags) + setgen = (self.__get_object_set(t) for t in tags) objs = functools.reduce(set.union, setgen) return objs @@ -129,7 +129,7 @@ def intersection(self, *tags): """ if not tags: return set() - setgen = (self.__getObjectSet(t) for t in tags) + setgen = (self.__get_object_set(t) for t in tags) objs = functools.reduce(set.intersection, setgen) return objs @@ -145,7 +145,7 @@ def verifyTags(self, *tags): raise KeyError("Tag '%s' does not exist" % tag) return True - def __getObjectSet(self, tag): + def __get_object_set(self, tag): """Helper function for getting an object set with given tag. Raises KeyError if a passed tag does not exist and self.silent diff --git a/tests/conftest.py b/tests/conftest.py index b354f297..0bb50a2c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -110,7 +110,7 @@ def _makeArgs(num): @pytest.fixture(scope="session") def noObserversInGlobalBuilders(): - def _noObserversInGlobalBuilders(): + def _no_observers_in_global_builders(): """True if no observer function leaks to global builder objects. Ensure objects are not immortal due to a reference from static @@ -125,7 +125,7 @@ def _noObserversInGlobalBuilders(): break return rv - return _noObserversInGlobalBuilders() + return _no_observers_in_global_builders() @pytest.fixture(scope="session") diff --git a/tests/test_contribution.py b/tests/test_contribution.py index 4d3fc7e3..48863e4d 100644 --- a/tests/test_contribution.py +++ b/tests/test_contribution.py @@ -223,7 +223,7 @@ def testResidual(noObserversInGlobalBuilders): # Try to add a parameter c = Parameter("c", 2) - fc._addParameter(c) + fc._add_parameter(c) fc.setEquation("c*I") assert fc._eq._value is None assert fc._reseq._value is None diff --git a/tests/test_objcrystparset.py b/tests/test_objcrystparset.py index c21a6d28..5150ae54 100644 --- a/tests/test_objcrystparset.py +++ b/tests/test_objcrystparset.py @@ -632,7 +632,7 @@ def getObjCrystParSetSpaceGroup(sg): from pyobjcryst.spacegroup import SpaceGroup sgobjcryst = SpaceGroup(sg.short_name) - sgnew = ObjCrystCrystalParSet._createSpaceGroup(sgobjcryst) + sgnew = ObjCrystCrystalParSet._create_space_group(sgobjcryst) return sgnew @staticmethod diff --git a/tests/test_pdf.py b/tests/test_pdf.py index 1ee2ccec..b46fa2a6 100644 --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -242,7 +242,7 @@ def test_getQmax(diffpy_structure_available, diffpy_srreal_available): if not diffpy_srreal_available: pytest.skip("diffpy.srreal package not available") - # cover all code branches in PDFContribution._getMetaValue + # cover all code branches in PDFContribution._get_meta_value # (1) contribution metadata pc1 = PDFContribution("pdf") assert pc1.getQmax() is None diff --git a/tests/test_recipeorganizer.py b/tests/test_recipeorganizer.py index 88909b91..a5db1e1b 100644 --- a/tests/test_recipeorganizer.py +++ b/tests/test_recipeorganizer.py @@ -98,13 +98,13 @@ def testAccessors(self): """Test accessors.""" m1 = self.m p1 = Parameter("p1", 1) - m1._addObject(p1, m1._parameters) + m1._add_object(p1, m1._parameters) m2 = RecipeContainer("m2") p2 = Parameter("p2", 2) - m2._addObject(p2, m2._parameters) + m2._add_object(p2, m2._parameters) - m1._addObject(m2, m1._containers) + m1._add_object(m2, m1._containers) self.assertTrue(m1.m2 is m2) self.assertTrue(m1.p1 is p1) @@ -128,38 +128,38 @@ def testLocateManagedObject(self): """Test the locateManagedObject method.""" m1 = self.m p1 = Parameter("p1", 1) - m1._addObject(p1, m1._parameters) + m1._add_object(p1, m1._parameters) m2 = RecipeContainer("m2") p2 = Parameter("p2", 2) - m2._addObject(p2, m2._parameters) + m2._add_object(p2, m2._parameters) - m1._addObject(m2, m1._containers) + m1._add_object(m2, m1._containers) p3 = Parameter("p3", 3) # Locate m2 in m1 (m1.m2) - loc = m1._locateManagedObject(m2) + loc = m1._locate_managed_object(m2) self.assertEqual(loc, [m1, m2]) # Locate p1 (m1.p1) - loc = m1._locateManagedObject(p1) + loc = m1._locate_managed_object(p1) self.assertEqual(loc, [m1, p1]) # Locate p2 in m2 (m2.p2) - loc = m2._locateManagedObject(p2) + loc = m2._locate_managed_object(p2) self.assertEqual(loc, [m2, p2]) # Locate p2 in m1 (m1.m2.p2) - loc = m1._locateManagedObject(p2) + loc = m1._locate_managed_object(p2) self.assertEqual(loc, [m1, m2, p2]) # Locate p3 in m1 (not there) - loc = m1._locateManagedObject(p3) + loc = m1._locate_managed_object(p3) self.assertEqual(loc, []) # Locate p3 in m2 (not there) - loc = m2._locateManagedObject(p3) + loc = m2._locate_managed_object(p3) self.assertEqual(loc, []) return @@ -186,13 +186,13 @@ def testNewParameter(self): m = self.m p1 = Parameter("p1", 1) - m._addParameter(p1) + m._add_parameter(p1) # Test duplication of Parameters - self.assertRaises(ValueError, m._newParameter, "p1", 0) + self.assertRaises(ValueError, m._new_parameter, "p1", 0) # Add a new Parameter - p2 = m._newParameter("p2", 0) + p2 = m._new_parameter("p2", 0) self.assertTrue(p2 is m.p2) return @@ -205,28 +205,28 @@ def testAddParameter(self): p2 = Parameter("p1", 2) # Check normal insert - m._addParameter(p1) + m._add_parameter(p1) self.assertTrue(m.p1 is p1) self.assertTrue(p1.name in m._eqfactory.builders) # Try to insert another parameter with the same name - self.assertRaises(ValueError, m._addParameter, p2) + self.assertRaises(ValueError, m._add_parameter, p2) # Now allow this - m._addParameter(p2, check=False) + m._add_parameter(p2, check=False) self.assertTrue(m.p1 is p2) self.assertTrue(p1.name in m._eqfactory.builders) # Try to insert a Parameter when a RecipeContainer with the same name # is already inside. c = RecipeContainer("test") - m._addObject(c, m._containers) + m._add_object(c, m._containers) p3 = Parameter("test", 0) - self.assertRaises(ValueError, m._addParameter, p3) + self.assertRaises(ValueError, m._add_parameter, p3) p4 = Parameter("xyz", 0) - m._addParameter(p4) + m._add_parameter(p4) # Check order self.assertEqual(list(m._parameters.keys()), ["p1", "xyz"]) @@ -242,28 +242,28 @@ def testRemoveParameter(self): p1 = Parameter("p1", 1) p2 = Parameter("p1", 2) - m._addParameter(p1) + m._add_parameter(p1) # Check for bad remove - self.assertRaises(ValueError, m._removeParameter, p2) + self.assertRaises(ValueError, m._remove_parameter, p2) # Remove p1 - m._removeParameter(p1) + m._remove_parameter(p1) self.assertTrue(p1.name not in m._eqfactory.builders) # Try to remove it again - self.assertRaises(ValueError, m._removeParameter, p1) + self.assertRaises(ValueError, m._remove_parameter, p1) # Try to remove a RecipeContainer c = RecipeContainer("test") - self.assertRaises(ValueError, m._removeParameter, c) + self.assertRaises(ValueError, m._remove_parameter, c) return def testConstrain(self): """Test the constrain method.""" - p1 = self.m._newParameter("p1", 1) - p2 = self.m._newParameter("p2", 2) + p1 = self.m._new_parameter("p1", 1) + p2 = self.m._new_parameter("p2", 2) p3 = Parameter("p3", 3) self.assertFalse(p1.constrained) @@ -324,54 +324,54 @@ def testRestrain(self): return def testGetConstraints(self): - """Test the _getConstraints method.""" + """Test the _get_constraints method.""" m2 = RecipeOrganizer("m2") self.m._organizers = {} self.m._manage(self.m._organizers) - self.m._addObject(m2, self.m._organizers) + self.m._add_object(m2, self.m._organizers) p1 = Parameter("p1", 1) p2 = Parameter("p2", 2) p3 = Parameter("p3", 3) p4 = Parameter("p4", 4) - self.m._addParameter(p1) - self.m._addParameter(p2) + self.m._add_parameter(p1) + self.m._add_parameter(p2) - m2._addParameter(p3) - m2._addParameter(p4) + m2._add_parameter(p3) + m2._add_parameter(p4) self.m.constrain(p1, "p2") m2.constrain(p3, "p4") - cons = self.m._getConstraints() + cons = self.m._get_constraints() self.assertTrue(p1 in cons) self.assertTrue(p3 in cons) self.assertEqual(2, len(cons)) return def testGetRestraints(self): - """Test the _getRestraints method.""" + """Test the _get_restraints method.""" m2 = RecipeOrganizer("m2") self.m._organizers = {} self.m._manage(self.m._organizers) - self.m._addObject(m2, self.m._organizers) + self.m._add_object(m2, self.m._organizers) p1 = Parameter("p1", 1) p2 = Parameter("p2", 2) p3 = Parameter("p3", 3) p4 = Parameter("p4", 4) - self.m._addParameter(p1) - self.m._addParameter(p2) + self.m._add_parameter(p1) + self.m._add_parameter(p2) - m2._addParameter(p3) - m2._addParameter(p4) + m2._add_parameter(p3) + m2._add_parameter(p4) r1 = self.m.restrain("p1 + p2") r2 = m2.restrain("2*p3 + p4") - res = self.m._getRestraints() + res = self.m._get_restraints() self.assertTrue(r1 in res) self.assertTrue(r2 in res) self.assertEqual(2, len(res)) @@ -483,7 +483,7 @@ def testRegisterStringFunction(self): self.assertTrue(p in self.m._parameters.values()) # Add a parameter - self.m._newParameter("y", 3.0) + self.m._new_parameter("y", 3.0) # Make sure that x and y are in the organizer self.assertEqual(0, self.m.x.getValue()) @@ -512,7 +512,7 @@ def testRegisterStringFunction(self): def test_releaseOldEquations(self): """Verify EquationFactory does not hold temporary equations.""" - self.m._newParameter("x", 12) + self.m._new_parameter("x", 12) self.assertEqual(36, self.m.evaluateEquation("3 * x")) self.assertEqual(0, len(self.m._eqfactory.equations)) return @@ -530,15 +530,15 @@ def capture_show(*args, **kwargs): return rv assert "" == capture_show() - organizer._newParameter("x", 1) - organizer._newParameter("y", 2) + organizer._new_parameter("x", 1) + organizer._new_parameter("y", 2) out1 = capture_show() lines1 = out1.strip().split("\n") assert 4 == len(lines1) assert "Parameters" in lines1 assert "Constraints" not in lines1 assert "Restraints" not in lines1 - organizer._newParameter("z", 7) + organizer._new_parameter("z", 7) organizer.constrain("y", "3 * z") out2 = capture_show() lines2 = out2.strip().split("\n") @@ -559,8 +559,8 @@ def capture_show(*args, **kwargs): out5 = capture_show(pattern="^") assert out3 == out5 # check output with another level of hierarchy - organizer._addObject(RecipeOrganizer("foo"), organizer._containers) - organizer.foo._newParameter("bar", 13) + organizer._add_object(RecipeOrganizer("foo"), organizer._containers) + organizer.foo._new_parameter("bar", 13) out6 = capture_show() assert "foo.bar" in out6 # filter out foo.bar diff --git a/tests/test_sgconstraints.py b/tests/test_sgconstraints.py index f0696321..32d6afe4 100644 --- a/tests/test_sgconstraints.py +++ b/tests/test_sgconstraints.py @@ -22,7 +22,7 @@ # ---------------------------------------------------------------------------- -def test_ObjCryst_constrainSpaceGroup(pyobjcryst_available): +def test_ObjCryst_constrain_space_group(pyobjcryst_available): """Make sure that all Parameters are constrained properly. This tests constrainSpaceGroup from @@ -39,7 +39,7 @@ def test_ObjCryst_constrainSpaceGroup(pyobjcryst_available): occryst = makeLaMnO3() stru = ObjCrystCrystalParSet(occryst.GetName(), occryst) # Make sure we actually create the constraints - stru._constrainSpaceGroup() + stru._constrain_space_group() # Make the space group parameters individually stru.sgpars.latpars stru.sgpars.xyzpars @@ -105,7 +105,7 @@ def test_ObjCryst_constrainSpaceGroup(pyobjcryst_available): return -def test_DiffPy_constrainAsSpaceGroup(datafile, pyobjcryst_available): +def test_DiffPy_constrain_as_space_group(datafile, pyobjcryst_available): """Test the constrainAsSpaceGroup function.""" if not pyobjcryst_available: pytest.skip("pyobjcrysta package not available") @@ -178,7 +178,7 @@ def _alltests(par): return -def test_ConstrainAsSpaceGroup_args(pyobjcryst_available, datafile): +def test_constrain_as_space_group_args(pyobjcryst_available, datafile): """Test the arguments processing of constrainAsSpaceGroup function.""" if not pyobjcryst_available: pytest.skip("pyobjcrysta package not available")