From d51e1b035af1dc8bf19e682bd78b32f180261173 Mon Sep 17 00:00:00 2001 From: Kai Wagoner-Oshima Date: Fri, 13 Jun 2025 15:45:52 -0400 Subject: [PATCH 1/4] fix: changed line length to 115 --- .flake8 | 2 ++ .isort.cfg | 1 + pyproject.toml | 14 ++++---------- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/.flake8 b/.flake8 index 2d2cb16..04d2d0b 100644 --- a/.flake8 +++ b/.flake8 @@ -1,3 +1,5 @@ +# As of now, flake8 does not natively support configuration via pyproject.toml +# https://github.com/microsoft/vscode-flake8/issues/135 [flake8] exclude = .git, diff --git a/.isort.cfg b/.isort.cfg index e0926f4..7ce0fb1 100644 --- a/.isort.cfg +++ b/.isort.cfg @@ -1,4 +1,5 @@ [settings] +# Keep import statement below line_length character limit line_length = 115 multi_line_output = 3 include_trailing_comma = True diff --git a/pyproject.toml b/pyproject.toml index ce2f2b1..e111356 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,22 +6,20 @@ build-backend = "setuptools.build_meta" name = "diffpy.srmise" dynamic=['version', 'dependencies'] authors = [ - { name="Simon J.L. Billinge group", email="simon.billinge@gmail.com" }, - {name="Luke Granlund", email="granlund@pa.msu.edu"}, + { name="Simon Billinge", email="sb2896@columbia.edu" }, ] maintainers = [ - { name="Simon J.L. Billinge group", email="simon.billinge@gmail.com" }, + { name="Simon Billinge", email="sb2896@columbia.edu" }, ] description = "Peak extraction and peak fitting tool for atomic pair distribution functions." -keywords = ['peak extraction fitting PDF AIC multimodeling'] +keywords = ['peak extraction', 'fitting', 'PDF', 'AIC', 'multimodeling'] readme = "README.rst" requires-python = ">=3.11, <3.14" classifiers = [ - 'Development Status :: 3 - Alpha', + 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', - 'Intended Audience :: Education', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', @@ -32,7 +30,6 @@ classifiers = [ 'Programming Language :: Python :: 3.13', 'Topic :: Scientific/Engineering :: Physics', 'Topic :: Scientific/Engineering :: Chemistry', - 'Topic :: Software Development :: Libraries', ] [project.urls] @@ -45,9 +42,6 @@ template = "{tag}" dev_template = "{tag}" dirty_template = "{tag}" -[project.scripts] -srmise = "diffpy.srmise.applications.extract:main" - [tool.setuptools.packages.find] where = ["src"] # list of folders that contain the packages (["."] by default) include = ["*"] # package names should match these glob patterns (["*"] by default) From 0f6d7e00533be73c5904d7886092c13d24255a0b Mon Sep 17 00:00:00 2001 From: Kai Wagoner-Oshima Date: Fri, 13 Jun 2025 15:58:21 -0400 Subject: [PATCH 2/4] chore: move LICENSE files over to scaffold --- LICENSE_PDFgui.rst => LICENSE-PDFgui.rst | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LICENSE_PDFgui.rst => LICENSE-PDFgui.rst (100%) diff --git a/LICENSE_PDFgui.rst b/LICENSE-PDFgui.rst similarity index 100% rename from LICENSE_PDFgui.rst rename to LICENSE-PDFgui.rst From 2b647c99f1926bc9560a17ec359f8843b3239ced Mon Sep 17 00:00:00 2001 From: Kai Wagoner-Oshima Date: Fri, 13 Jun 2025 17:35:27 -0400 Subject: [PATCH 3/4] fix: line length in docformatter --- .pre-commit-config.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9cf0556..a215c36 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -50,3 +50,9 @@ repos: - id: codespell additional_dependencies: - tomli + - repo: https://github.com/s-weigand/docformatter + rev: 5757c5190d95e5449f102ace83df92e7d3b06c6c + hooks: + - id: docformatter + additional_dependencies: [tomli] + args: [--in-place, --wrap-summaries, "115", --wrap-descriptions, "115"] #--config, ./pyproject.toml] From 18a1002ad6f73cc54eafbba6ffd56b95e736c87a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 13 Jun 2025 21:35:50 +0000 Subject: [PATCH 4/4] [pre-commit.ci] auto fixes from pre-commit hooks --- doc/examples/fit_initial.py | 11 +- doc/examples/multimodel_known_dG1.py | 4 +- doc/examples/multimodel_unknown_dG1.py | 4 +- doc/examples/multimodel_unknown_dG2.py | 3 +- doc/examples/parameter_summary.py | 3 +- src/diffpy/__init__.py | 1 - src/diffpy/srmise/__init__.py | 1 - src/diffpy/srmise/applications/plot.py | 4 +- src/diffpy/srmise/basefunction.py | 37 +++-- src/diffpy/srmise/baselines/arbitrary.py | 20 +-- src/diffpy/srmise/baselines/base.py | 5 +- src/diffpy/srmise/baselines/fromsequence.py | 8 +- src/diffpy/srmise/baselines/nanospherical.py | 2 +- src/diffpy/srmise/dataclusters.py | 14 +- src/diffpy/srmise/modelcluster.py | 28 ++-- src/diffpy/srmise/modelevaluators/aic.py | 16 +- src/diffpy/srmise/modelevaluators/aicc.py | 16 +- src/diffpy/srmise/modelevaluators/base.py | 25 +-- src/diffpy/srmise/modelparts.py | 13 +- src/diffpy/srmise/multimodelselection.py | 33 ++-- src/diffpy/srmise/pdfdataset.py | 28 ++-- src/diffpy/srmise/pdfpeakextraction.py | 23 +-- src/diffpy/srmise/peakextraction.py | 17 +- src/diffpy/srmise/peaks/base.py | 5 +- src/diffpy/srmise/peaks/gaussian.py | 11 +- src/diffpy/srmise/peaks/gaussianoverr.py | 10 +- src/diffpy/srmise/peaks/terminationripples.py | 12 +- src/diffpy/srmise/peakstability.py | 11 +- src/diffpy/srmise/srmiseerrors.py | 153 ++++++++++++------ src/diffpy/srmise/srmiselog.py | 19 ++- src/diffpy/srmise/version.py | 1 - tests/test_version.py | 3 +- 32 files changed, 323 insertions(+), 218 deletions(-) diff --git a/doc/examples/fit_initial.py b/doc/examples/fit_initial.py index fa9961c..9d2d95d 100644 --- a/doc/examples/fit_initial.py +++ b/doc/examples/fit_initial.py @@ -12,12 +12,11 @@ ############################################################################## """Example of peak fitting C60 PDF (unnormalized) with unreliable uncertainties. -Peak fitting in SrMise means fitting a model of initial peaks, which may be -specified manually or estimated with a clustering-based convenience function, -just as with specifying initial peaks for peak extraction. Unlike peak -extraction, it does not attempt to add or remove peaks, apply termination -ripples, or otherwise do anything beyond chi-square fitting using the specified -grid.""" +Peak fitting in SrMise means fitting a model of initial peaks, which may be specified manually or estimated with a +clustering-based convenience function, just as with specifying initial peaks for peak extraction. Unlike peak +extraction, it does not attempt to add or remove peaks, apply termination ripples, or otherwise do anything beyond +chi-square fitting using the specified grid. +""" import matplotlib.pyplot as plt diff --git a/doc/examples/multimodel_known_dG1.py b/doc/examples/multimodel_known_dG1.py index f1fe508..f872e04 100644 --- a/doc/examples/multimodel_known_dG1.py +++ b/doc/examples/multimodel_known_dG1.py @@ -10,8 +10,8 @@ # See LICENSE.txt for license information. # ############################################################################## -"""Extract multiple models from crystalline PDF with known uncertainties for -use in later AIC-driven multimodeling analysis. +"""Extract multiple models from crystalline PDF with known uncertainties for use in later AIC-driven multimodeling +analysis. The multimodel approach generates many models of varying complexity by assuming a range of experimental uncertainties are physically plausible. This example diff --git a/doc/examples/multimodel_unknown_dG1.py b/doc/examples/multimodel_unknown_dG1.py index 4570f78..f0af3f9 100644 --- a/doc/examples/multimodel_unknown_dG1.py +++ b/doc/examples/multimodel_unknown_dG1.py @@ -10,8 +10,8 @@ # See LICENSE.txt for license information. # ############################################################################## -"""Extract multiple models from nanoparticle PDF with unknown uncertainties for -use in later AIC-driven multimodeling analysis. +"""Extract multiple models from nanoparticle PDF with unknown uncertainties for use in later AIC-driven +multimodeling analysis. The multimodel approach generates many models of varying complexity by assuming a range of experimental uncertainties are physically plausible. This example diff --git a/doc/examples/multimodel_unknown_dG2.py b/doc/examples/multimodel_unknown_dG2.py index c4bbef4..cb47f28 100644 --- a/doc/examples/multimodel_unknown_dG2.py +++ b/doc/examples/multimodel_unknown_dG2.py @@ -10,8 +10,7 @@ # See LICENSE.txt for license information. # ############################################################################## -"""AIC-driven multimodel analysis of nanoparticle PDF with unknown -uncertainties. +"""AIC-driven multimodel analysis of nanoparticle PDF with unknown uncertainties. The multimodel approach generates many models of varying complexity by assuming a range of experimental uncertainties are physically plausible. This example diff --git a/doc/examples/parameter_summary.py b/doc/examples/parameter_summary.py index 1d4095c..b135d82 100644 --- a/doc/examples/parameter_summary.py +++ b/doc/examples/parameter_summary.py @@ -25,7 +25,8 @@ nyquist (whether to use Nyquist sampling) supersample (minimum amount to oversample during initial stages) cres (clustering resolution) -initial_peaks (peaks already assumed to exist during extraction)""" +initial_peaks (peaks already assumed to exist during extraction) +""" import matplotlib.pyplot as plt diff --git a/src/diffpy/__init__.py b/src/diffpy/__init__.py index 377a0f9..1fd9c20 100644 --- a/src/diffpy/__init__.py +++ b/src/diffpy/__init__.py @@ -12,7 +12,6 @@ # See LICENSE.rst for license information. # ############################################################################## - """Blank namespace package for module diffpy.""" diff --git a/src/diffpy/srmise/__init__.py b/src/diffpy/srmise/__init__.py index 65eb42b..28273d0 100644 --- a/src/diffpy/srmise/__init__.py +++ b/src/diffpy/srmise/__init__.py @@ -12,7 +12,6 @@ # See LICENSE.rst for license information. # ############################################################################## - """Peak extraction and peak fitting tool for atomic pair distribution functions.""" # package version diff --git a/src/diffpy/srmise/applications/plot.py b/src/diffpy/srmise/applications/plot.py index 0399565..25fea0b 100755 --- a/src/diffpy/srmise/applications/plot.py +++ b/src/diffpy/srmise/applications/plot.py @@ -11,7 +11,7 @@ # See LICENSE.txt for license information. # ############################################################################## -"""plot extracted peaks and comparison to ideal distances (if given)""" +"""Plot extracted peaks and comparison to ideal distances (if given)""" import optparse import sys @@ -175,7 +175,7 @@ def labelallsubplots(): def makeplot(ppe_or_stability, ip=None, **kwds): - """Plot stuff""" + """Plot stuff.""" if isinstance(ppe_or_stability, PeakStability): stability = ppe_or_stability ppe = stability.ppe diff --git a/src/diffpy/srmise/basefunction.py b/src/diffpy/srmise/basefunction.py index 7a955f0..d99551f 100644 --- a/src/diffpy/srmise/basefunction.py +++ b/src/diffpy/srmise/basefunction.py @@ -76,7 +76,7 @@ def __init__( base=None, Cache=None, ): - """Set parameterdict defined by subclass + """Set parameterdict defined by subclass. Parameters ---------- @@ -159,32 +159,50 @@ def __init__( # "Virtual" class methods #### def actualize(self, *args, **kwds): - """Create ModelPart instance of self with given parameters. ("Virtual" method)""" + """Create ModelPart instance of self with given parameters. + + ("Virtual" method) + """ emsg = "actualize() must be implemented in a BaseFunction subclass." raise NotImplementedError(emsg) def estimate_parameters(self, *args, **kwds): - """Estimate BaseFunction parameters from supplied data. ("Virtual" method)""" + """Estimate BaseFunction parameters from supplied data. + + ("Virtual" method) + """ emsg = "estimate_parameters() must be implemented in a BaseFunction subclass." raise NotImplementedError(emsg) def _jacobianraw(self, *args, **kwds): - """Calculate the jacobian. ("Virtual" method)""" + """Calculate the jacobian. + + ("Virtual" method) + """ emsg = "_jacobianraw() must be implemented in a BaseFunction subclass." raise NotImplementedError(emsg) def _transform_derivativesraw(self, *args, **kwds): - """Convert BaseFunction parameters to another form. ("Virtual" method)""" + """Convert BaseFunction parameters to another form. + + ("Virtual" method) + """ emsg = "transform_parameters() must be implemented in a BaseFunction subclass." raise NotImplementedError(emsg) def _transform_parametersraw(self, *args, **kwds): - """Convert BaseFunction parameters to another form. ("Virtual" method)""" + """Convert BaseFunction parameters to another form. + + ("Virtual" method) + """ emsg = "transform_parameters() must be implemented in a BaseFunction subclass." raise NotImplementedError(emsg) def _valueraw(self, *args, **kwds): - """Calculate value of function. ("Virtual" method)""" + """Calculate value of function. + + ("Virtual" method) + """ emsg = "_valueraw must() be implemented in a BaseFunction subclass." raise NotImplementedError(emsg) @@ -373,7 +391,7 @@ def pgradient(self, p, format): return def getmodule(self): - """Return 'diffpy.srmise.basefunction'""" + """Return 'diffpy.srmise.basefunction'.""" return "diffpy.srmise.basefunction" def writestr(self, baselist): @@ -480,7 +498,8 @@ def safefunctionlist(fs): is guaranteed to be safe for saving/reinstantiating peak functions. Parameters - fs: List of BaseFunction instances.""" + fs: List of BaseFunction instances. + """ fsafe = [] for f in fs: BaseFunction.safefunction(f, fsafe) diff --git a/src/diffpy/srmise/baselines/arbitrary.py b/src/diffpy/srmise/baselines/arbitrary.py index 80c1055..0659aac 100644 --- a/src/diffpy/srmise/baselines/arbitrary.py +++ b/src/diffpy/srmise/baselines/arbitrary.py @@ -26,17 +26,12 @@ class Arbitrary(BaselineFunction): """Methods for evaluating a baseline from an arbitrary function. - Supports baseline calculations with arbitrary functions. These functions, - if implemented, must have the following signatures and return values: - valuef(pars, x) ==> numpy.array of length x if x is a sequence - ==> number if x is a number - jacobianf(pars, x, free) ==> list, each element a numpy.array of length x if - x is a sequence or None if value of free for - that parameter is False. - ==> list, each element a number if x is a number - or None if value of free for that parameter is - False - estimatef(x, y) ==> numpy.array of length npars + Supports baseline calculations with arbitrary functions. These functions, if implemented, must have the + following signatures and return values: valuef(pars, x) ==> numpy.array of length x if x is a sequence + ==> number if x is a number jacobianf(pars, x, free) ==> list, each element a numpy.array of length x if + x is a sequence or None if value of free for that parameter is False. + ==> list, each element a number if x is a number or None if value of free for that + parameter is False estimatef(x, y) ==> numpy.array of length npars """ def __init__(self, npars, valuef, jacobianf=None, estimatef=None, Cache=None): @@ -117,7 +112,8 @@ def estimate_parameters(self, r, y): The numpy array of parameters in the default internal format. we raise NotImplementedError if no estimation routine is defined, and - SrMiseEstimationError if parameters cannot be estimated for any other.""" + SrMiseEstimationError if parameters cannot be estimated for any other. + """ if self.estimatef is None: emsg = "No estimation routine provided to Arbitrary." raise NotImplementedError(emsg) diff --git a/src/diffpy/srmise/baselines/base.py b/src/diffpy/srmise/baselines/base.py index c1ecf0e..b49e54d 100644 --- a/src/diffpy/srmise/baselines/base.py +++ b/src/diffpy/srmise/baselines/base.py @@ -71,7 +71,7 @@ def __init__( base=None, Cache=None, ): - """Set parameterdict defined by subclass + """Set parameterdict defined by subclass. parameterdict : dict The dictionary mapping string keys to their index in a @@ -91,7 +91,8 @@ def __init__( additional functionality. Cache : class The class (not instance) which implements caching of BaseFunction - evaluations.""" + evaluations. + """ BaseFunction.__init__(self, parameterdict, parformats, default_formats, metadict, base, Cache) # "Virtual" class methods #### diff --git a/src/diffpy/srmise/baselines/fromsequence.py b/src/diffpy/srmise/baselines/fromsequence.py index 1866441..24accdb 100644 --- a/src/diffpy/srmise/baselines/fromsequence.py +++ b/src/diffpy/srmise/baselines/fromsequence.py @@ -25,9 +25,9 @@ class FromSequence(BaselineFunction): """Methods for evaluation of a baseline from discrete data via interpolation. - FromSequence uses cubic spline interpolation (no smoothing) on discrete - points to approximate the baseline at arbitrary points within the - interpolation domain. This baseline function permits no free parameters.""" + FromSequence uses cubic spline interpolation (no smoothing) on discrete points to approximate the baseline at + arbitrary points within the interpolation domain. This baseline function permits no free parameters. + """ def __init__(self, *args, **kwds): """Initialize a baseline object based on input sequences `x` and `y`. @@ -233,7 +233,7 @@ def xyrepr(self, var): return "[%s]" % ", ".join([repr(v) for v in var]) def readxy(self, filename): - """ """ + """""" from diffpy.srmise.srmiseerrors import SrMiseDataFormatError # TODO: Make this safer diff --git a/src/diffpy/srmise/baselines/nanospherical.py b/src/diffpy/srmise/baselines/nanospherical.py index a76719f..90d464c 100644 --- a/src/diffpy/srmise/baselines/nanospherical.py +++ b/src/diffpy/srmise/baselines/nanospherical.py @@ -267,7 +267,7 @@ def _valueraw2(self, pars, r): return -s * r * (1 - (3.0 / 4.0) * rdivR + (1.0 / 16.0) * rdivR**3) def _getdomain(self, pars, r): - """Return slice object for which r > 0 and r < twice the radius + """Return slice object for which r > 0 and r < twice the radius. Parameters ---------- diff --git a/src/diffpy/srmise/dataclusters.py b/src/diffpy/srmise/dataclusters.py index 4a057c3..b992bfb 100644 --- a/src/diffpy/srmise/dataclusters.py +++ b/src/diffpy/srmise/dataclusters.py @@ -53,7 +53,7 @@ class DataClusters: """ def __init__(self, x, y, res): - """Constructor + """Constructor. Parameters ---------- @@ -102,8 +102,7 @@ def __eq__(self, other): ) def _clear(self): - """ - Clear all data and reset the cluster object to a transient initial state. + """Clear all data and reset the cluster object to a transient initial state. The purpose of this method is to provide a clean state before creating new clustering operations. The object is updated in-place and no new instance is returned. @@ -175,8 +174,8 @@ def _setdata(self, x, y, res): def __next__(self): """Cluster point with largest y-coordinate left, returning self. - next() always adds at least one additional point to the existing - cluster, or raises an exception if all points have been clustered. + next() always adds at least one additional point to the existing cluster, or raises an exception if all + points have been clustered. """ if self.status == self.INIT: raise Exception("Cannot cluster next point while status is INIT.") @@ -465,7 +464,10 @@ def plot(self, *args, **kwds): return def animate(self): - """Animate clustering. Restores state when complete.""" + """Animate clustering. + + Restores state when complete. + """ clusters = self.clusters current_idx = self.current_idx lastcluster_idx = self.lastcluster_idx diff --git a/src/diffpy/srmise/modelcluster.py b/src/diffpy/srmise/modelcluster.py index 1525ddc..916c5be 100644 --- a/src/diffpy/srmise/modelcluster.py +++ b/src/diffpy/srmise/modelcluster.py @@ -262,8 +262,8 @@ def getcorrelation(self, i, j): def getvalue(self, i): """Return value of parameter i. - The variable may be specified as an integer, or as a two-component tuple of integers (l, m) - which indicate the mth parameter of modelpart l. + The variable may be specified as an integer, or as a two-component tuple of integers (l, m) which indicate + the mth parameter of modelpart l. """ (l, m) = i if i in self.pmap else self.ipmap[i] return self.model[l][m] @@ -426,7 +426,6 @@ class ModelCluster(object): value: Return value of the model plus baseline valuebl: Return value of the baseline writestr: Return string representation of self. - """ def __init__(self, model, *args, **kwds): @@ -501,7 +500,8 @@ def __init__(self, model, *args, **kwds): def copy(self): """Return copy of this ModelCluster. - Equivalent to ModelCluster(self)""" + Equivalent to ModelCluster(self) + """ return ModelCluster(self) def addexternalpeaks(self, peaks): @@ -1149,7 +1149,10 @@ def contingent_fit(self, minpoints, growth_threshold): return None def cleanfit(self): - """Remove poor-quality peaks in the fit. Return number removed.""" + """Remove poor-quality peaks in the fit. + + Return number removed. + """ # Find peaks located outside the cluster pos = np.array([p["position"] for p in self.model]) left_idx = pos.searchsorted(self.r_cluster[0]) @@ -1219,7 +1222,8 @@ def reduce_to(self, x, y): Returns ------- ModelEvaluator or None - Return ModelEvaluator instance if fit changed, otherwise None.""" + Return ModelEvaluator instance if fit changed, otherwise None. + """ # No reduction necessary if self.model.value(x) < y: logger.debug("reduce_to: No reduction necessary.") @@ -1427,14 +1431,12 @@ def __str__(self): def prune(self): """Remove peaks until model quality no longer improves. - Peaks are removed in a greedy fashion, and the best possible model is - by no means guaranteed. + Peaks are removed in a greedy fashion, and the best possible model is by no means guaranteed. - Due to the somewhat exploratory nature of prune many non-convergent - fits will generally be performed, but it severely restricts the number - of function evaluations permitted during fitting, and so fits that do - not converge rapidly are abandoned. Nevertheless, occasionally this - method will take an unusually long time to complete. + Due to the somewhat exploratory nature of prune many non-convergent fits will generally be performed, but + it severely restricts the number of function evaluations permitted during fitting, and so fits that do not + converge rapidly are abandoned. Nevertheless, occasionally this method will take an unusually long time to + complete. """ if len(self.model) == 0: return diff --git a/src/diffpy/srmise/modelevaluators/aic.py b/src/diffpy/srmise/modelevaluators/aic.py index 1a1973b..4bc3815 100644 --- a/src/diffpy/srmise/modelevaluators/aic.py +++ b/src/diffpy/srmise/modelevaluators/aic.py @@ -46,7 +46,7 @@ class AIC(ModelEvaluator): """ def __init__(self): - """ """ + """""" ModelEvaluator.__init__(self, "AIC", False) return @@ -66,7 +66,8 @@ def evaluate(self, fit, count_fixed=False, kshift=0): Returns ------- quality : float - The quality of fit for given ModelCluster.""" + The quality of fit for given ModelCluster. + """ # Number of parameters. By default, fixed parameters are ignored. k = fit.model.npars(count_fixed=count_fixed) + kshift if k < 0: @@ -124,8 +125,8 @@ def parpenalty(self, k): return (2 * k) * fudgefactor def growth_justified(self, fit, k_prime): - """Returns whether adding k_prime parameters to the given model (ModelCluster) is justified - given the current quality of the fit. + """Returns whether adding k_prime parameters to the given model (ModelCluster) is justified given the + current quality of the fit. The assumption is that adding k_prime parameters will result in "effectively 0" chiSquared cost, and so adding it is justified if the cost of adding @@ -170,7 +171,7 @@ def growth_justified(self, fit, k_prime): @staticmethod def akaikeweights(aics): - """Return sequence of Akaike weights for sequence of AICs + """Return sequence of Akaike weights for sequence of AICs. Parameters ---------- @@ -189,7 +190,7 @@ def akaikeweights(aics): @staticmethod def akaikeprobs(aics): - """Return sequence of Akaike probabilities for sequence of AICs + """Return sequence of Akaike probabilities for sequence of AICs. Parameters ---------- @@ -199,7 +200,8 @@ def akaikeprobs(aics): Returns ------- array-like - The sequence of Akaike probabilities""" + The sequence of Akaike probabilities + """ aic_weights = AIC.akaikeweights(aics) return aic_weights / np.sum(aic_weights) diff --git a/src/diffpy/srmise/modelevaluators/aicc.py b/src/diffpy/srmise/modelevaluators/aicc.py index b2a9286..32ee8ee 100644 --- a/src/diffpy/srmise/modelevaluators/aicc.py +++ b/src/diffpy/srmise/modelevaluators/aicc.py @@ -45,13 +45,13 @@ class AICc(ModelEvaluator): """ def __init__(self): - """ """ + """""" ModelEvaluator.__init__(self, "AICc", False) return def evaluate(self, fit, count_fixed=False, kshift=0): - """Return quality of fit for given ModelCluster using AICc (Akaike's Information Criterion - with 2nd order correction for small sample size). + """Return quality of fit for given ModelCluster using AICc (Akaike's Information Criterion with 2nd order + correction for small sample size). Parameters fit: A ModelCluster @@ -65,7 +65,8 @@ def evaluate(self, fit, count_fixed=False, kshift=0): Returns ------- float - Quality of AICc""" + Quality of AICc + """ # Number of parameters. By default, fixed parameters are ignored. k = fit.model.npars(count_fixed=count_fixed) + kshift if k < 0: @@ -171,7 +172,7 @@ def growth_justified(self, fit, k_prime): @staticmethod def akaikeweights(aics): - """Return sequence of Akaike weights for sequence of AICs + """Return sequence of Akaike weights for sequence of AICs. Parameters ---------- @@ -190,7 +191,7 @@ def akaikeweights(aics): @staticmethod def akaikeprobs(aics): - """Return sequence of Akaike probabilities for sequence of AICs + """Return sequence of Akaike probabilities for sequence of AICs. Parameters ---------- @@ -200,7 +201,8 @@ def akaikeprobs(aics): Returns ------- array-like - The sequence of Akaike probabilities""" + The sequence of Akaike probabilities + """ aic_weights = AICc.akaikeweights(aics) return aic_weights / np.sum(aic_weights) diff --git a/src/diffpy/srmise/modelevaluators/base.py b/src/diffpy/srmise/modelevaluators/base.py index 179e082..d93865c 100644 --- a/src/diffpy/srmise/modelevaluators/base.py +++ b/src/diffpy/srmise/modelevaluators/base.py @@ -48,12 +48,14 @@ class ModelEvaluator: - """Class for evaluating the quality of a fit. Comparison between different - models of the same type is defined so that better models are 'greater than' - worse models.""" + """Class for evaluating the quality of a fit. + + Comparison between different models of the same type is defined so that better models are 'greater than' worse + models. + """ def __init__(self, method, higher_is_better): - """Constructor of ModelEvaluator + """Constructor of ModelEvaluator. Parameters ---------- @@ -69,7 +71,7 @@ def __init__(self, method, higher_is_better): return def __lt__(self, other): - """ """ + """""" assert self.method == other.method # Comparison between same types required assert self.stat is not None and other.stat is not None # The statistic must already be calculated @@ -80,7 +82,7 @@ def __lt__(self, other): return other.stat < self.stat def __le__(self, other): - """ """ + """""" assert self.method == other.method # Comparison between same types required assert self.stat is not None and other.stat is not None # The statistic must already be calculated @@ -91,7 +93,7 @@ def __le__(self, other): return other.stat <= self.stat def __eq__(self, other): - """ """ + """""" assert self.method == other.method # Comparison between same types required assert self.stat is not None and other.stat is not None # The statistic must already be calculated @@ -99,7 +101,7 @@ def __eq__(self, other): return self.stat == other.stat def __ne__(self, other): - """ """ + """""" assert self.method == other.method # Comparison between same types required assert self.stat is not None and other.stat is not None # The statistic must already be calculated @@ -107,7 +109,7 @@ def __ne__(self, other): return self.stat != other.stat def __gt__(self, other): - """ """ + """""" assert self.method == other.method # Comparison between same types required assert self.stat is not None and other.stat is not None # The statistic must already be calculated @@ -118,7 +120,7 @@ def __gt__(self, other): return other.stat > self.stat def __ge__(self, other): - """ """ + """""" assert self.method == other.method # Comparison between same types required assert self.stat is not None and other.stat is not None # The statistic must already be calculated @@ -138,7 +140,8 @@ def chi_squared(self, expected, observed, error): observed : float The observed value. error : float - The error statistic.""" + The error statistic. + """ self.chisq = np.sum((expected - observed) ** 2 / error**2) return self.chisq diff --git a/src/diffpy/srmise/modelparts.py b/src/diffpy/srmise/modelparts.py index 43a2141..652d9ea 100644 --- a/src/diffpy/srmise/modelparts.py +++ b/src/diffpy/srmise/modelparts.py @@ -569,7 +569,8 @@ def compress(self): Returns ------- pars : array-like - The compressed parameters of the model part.""" + The compressed parameters of the model part. + """ return self.pars[self.free] def jacobian(self, r, range=None): @@ -596,7 +597,8 @@ def owner(self): Returns ------- BaseFunction subclass - The BaseFunction subclass which owns this part.""" + The BaseFunction subclass which owns this part. + """ return self._owner def update(self, freepars): @@ -727,7 +729,8 @@ def npars(self, count_fixed=True): Returns ------- int - The number of parameters in all parts.""" + The number of parameters in all parts. + """ if count_fixed: return self._owner.npars else: @@ -738,7 +741,7 @@ def __str__(self): return str(self._owner.transform_parameters(self.pars, in_format="internal", out_format="default_output")) def __eq__(self, other): - """ """ + """""" if hasattr(other, "_owner"): return ( (self._owner is other._owner) @@ -750,7 +753,7 @@ def __eq__(self, other): return False def __ne__(self, other): - """ """ + """""" return not self == other def writestr(self, ownerlist): diff --git a/src/diffpy/srmise/multimodelselection.py b/src/diffpy/srmise/multimodelselection.py index c4c7b74..8998254 100644 --- a/src/diffpy/srmise/multimodelselection.py +++ b/src/diffpy/srmise/multimodelselection.py @@ -36,7 +36,7 @@ class MultimodelSelection(PeakStability): """Quick and dirty multimodel selection using AIC and its offspring.""" def __init__(self): - """ """ + """""" self.dgs = np.array([]) self.dgs_idx = {} @@ -203,7 +203,8 @@ def animate_probs(self, step=False, duration=0.0, **kwds): duration : float Minimum time in seconds to complete animation. Default is 0. - Keywords passed to pyplot.plot()""" + Keywords passed to pyplot.plot() + """ if duration > 0: import time @@ -248,7 +249,8 @@ def animate_classprobs(self, step=False, duration=0.0, **kwds): duration : float Minimum time in seconds to complete animation. Default is 0. - Keywords passed to pyplot.plot()""" + Keywords passed to pyplot.plot() + """ if duration > 0: import time @@ -461,7 +463,8 @@ def dg_key(self, dg_in): Returns ------- float - The dg value usable as a key nearest to dg_in.""" + The dg value usable as a key nearest to dg_in. + """ idx = (np.abs(self.dgs - dg_in)).argmin() return self.dgs[idx] @@ -476,7 +479,8 @@ def bestclasses(self, dgs=None): Returns ------- array-like - The best classes for all models.""" + The best classes for all models. + """ if dgs is None: dgs = self.dgs best = [] @@ -518,7 +522,8 @@ def classbestdgs(self, cls, dgs=None): Returns ------- array-like - Sequence of best uncertainties for the models.""" + Sequence of best uncertainties for the models. + """ if dgs is None: dgs = self.dgs bestdgs = [] @@ -587,7 +592,8 @@ def plot3dclassprobs(self, **kwds): "fig" - The figure "axis" - The image axis "cbaxis" - The colorbar axis, if it exists. - "cb" - The colorbar, if it exists.""" + "cb" - The colorbar, if it exists. + """ from matplotlib import cm, colorbar, colors from matplotlib.collections import PolyCollection @@ -911,8 +917,8 @@ def maxprobdG_byclass(self, model): return self.dgs[prob_idx] def maxprobdG_bymodel(self, model): - """Return the post-hoc dG for which the given model's Akaike probability is maximized. - Classes are not considered. + """Return the post-hoc dG for which the given model's Akaike probability is maximized. Classes are not + considered. Parameters ---------- @@ -941,14 +947,14 @@ def maxprobmodel_byclass(self, dG): Returns ------- float - The model mapped by class which maximizes probability at given dG.""" + The model mapped by class which maximizes probability at given dG. + """ cls = self.sortedclassprobs[dG][-1] m = self.sortedclasses[dG][cls][-1] return m def maxprobmodel_bymodel(self, dG): - """Return the model which maximizes probability at given dG. - Classes are not considered. + """Return the model which maximizes probability at given dG. Classes are not considered. Parameters ---------- @@ -958,6 +964,7 @@ def maxprobmodel_bymodel(self, dG): Returns ------- model : array-like - The model which maximizes probability at given dG.""" + The model which maximizes probability at given dG. + """ # Note that if there are identical models this returns the one of greatest dg. return self.sortedprobs[dG][-1] diff --git a/src/diffpy/srmise/pdfdataset.py b/src/diffpy/srmise/pdfdataset.py index 6f41d30..8e8108e 100644 --- a/src/diffpy/srmise/pdfdataset.py +++ b/src/diffpy/srmise/pdfdataset.py @@ -14,10 +14,7 @@ # LICENSE_PDFgui.txt for the full PDFgui license. # ############################################################################## - - -"""class PDFDataSet for experimental PDF data. -""" +"""Class PDFDataSet for experimental PDF data.""" import os.path @@ -32,7 +29,7 @@ class PDFComponent(object): """Common base class.""" def __init__(self, name): - """initialize the object + """Initialize the object. Parameter --------- @@ -42,7 +39,7 @@ def __init__(self, name): self.name = name def close(self, force=False): - """close myself + """Close myself. Parameter --------- @@ -122,9 +119,10 @@ def __init__(self, name): return def clear(self): - """reset all data members to initial empty values + """Reset all data members to initial empty values. - The purpose of this method is to set the PDF dataset to initial empty values.""" + The purpose of this method is to set the PDF dataset to initial empty values. + """ self.robs = [] self.Gobs = [] self.drobs = [] @@ -143,8 +141,8 @@ def clear(self): return def setvar(self, var, value): - """Assign a data member using PdfFit-style variable notation. - This method is typically utilized by the `applyParameters()` function. + """Assign a data member using PdfFit-style variable notation. This method is typically utilized by the + `applyParameters()` function. Parameters ---------- @@ -169,8 +167,7 @@ def setvar(self, var, value): return def getvar(self, var): - """Obtain value corresponding to PdfFit dataset variable. - Used by findParameters(). + """Obtain value corresponding to PdfFit dataset variable. Used by findParameters(). Parameters ---------- @@ -192,7 +189,7 @@ def getvar(self, var): return value def read(self, filename): - """load data from PDFGetX2 or PDFGetN gr file + """Load data from PDFGetX2 or PDFGetN gr file. filename : str file to read from @@ -217,7 +214,7 @@ def read(self, filename): return self def readStr(self, datastring): - """read experimental PDF data from a string + """Read experimental PDF data from a string. Parameter --------- @@ -364,7 +361,6 @@ def write(self, filename): def writeStr(self): """String representation of experimental PDF data. - Returns ------- str @@ -411,7 +407,7 @@ def writeStr(self): return datastring def copy(self, other=None): - """copy self to other. if other is None, create new instance + """Copy self to other. if other is None, create new instance. Parameters ---------- diff --git a/src/diffpy/srmise/pdfpeakextraction.py b/src/diffpy/srmise/pdfpeakextraction.py index 6142e68..15d69db 100644 --- a/src/diffpy/srmise/pdfpeakextraction.py +++ b/src/diffpy/srmise/pdfpeakextraction.py @@ -36,8 +36,8 @@ class PDFPeakExtraction(PeakExtraction): - """PDFPeakExtraction extends the PeakExtraction class to specialize in extracting - peaks from PDF (Probability Density Function) data. + """PDFPeakExtraction extends the PeakExtraction class to specialize in extracting peaks from PDF (Probability + Density Function) data. Parameters ---------- @@ -77,7 +77,6 @@ def loadpdf(self, pdf): ---------- pdf: PDFDataSet instance or str The PDFDataSet instance or a PDF file name. - """ self.clear() if isinstance(pdf, PDFDataSet): @@ -98,7 +97,8 @@ def setdata(self, x, y, dx=None, dy=None): x : array-like The x-coordinates of the data. y : array-like - The y-coordinates of the data.""" + The y-coordinates of the data. + """ PeakExtraction.setdata(self, x, y, dx, dy) try: self.qmax_fromdata = find_qmax(self.x, self.y)[0] @@ -108,7 +108,8 @@ def setdata(self, x, y, dx=None, dy=None): def clear(self): """Clear all members. - The purpose of the method is to ensure the object is in a clean state.""" + The purpose of the method is to ensure the object is in a clean state. + """ # TODO: Clear additional members self.filename = None self.nyquist = None @@ -190,7 +191,8 @@ def defaultvars(self, *args): Parameters ---------- *args : argparse.Namespace - Arguments passed to PeakExtraction.setdata().""" + Arguments passed to PeakExtraction.setdata(). + """ nargs = list(args) # qmax preference: reported, then fromdata, then 0. @@ -276,7 +278,8 @@ def resampledata(self, dr, **kwds): Returns ------- tuple of ndarray - A tuple containing the resampled (x, y, error in x, effective error in y).""" + A tuple containing the resampled (x, y, error in x, effective error in y). + """ self.defaultvars() # Find correct range if necessary. eps = kwds.get("eps", 10**-6) @@ -318,7 +321,8 @@ def errorscale(self, dr): Returns ------- float - The uncertainties scaled.""" + The uncertainties scaled. + """ if self.qmax > 0 and self.nyquist and self.scale: dr_nyquist = np.pi / self.qmax return np.max([np.sqrt(dr_nyquist / dr), 1.0]) @@ -1047,7 +1051,8 @@ def stdratio(data): ------- array-like an array of length floor(len(data)/2)-1. The ith element is - equivalent to std(data[:i+2])/std(data[i+2:2i+4]).""" + equivalent to std(data[:i+2])/std(data[i+2:2i+4]). + """ limit = int(np.floor(len(data) / 2)) std_left = np.zeros(limit) diff --git a/src/diffpy/srmise/peakextraction.py b/src/diffpy/srmise/peakextraction.py index dd0b0cd..2f334bd 100644 --- a/src/diffpy/srmise/peakextraction.py +++ b/src/diffpy/srmise/peakextraction.py @@ -70,7 +70,8 @@ def __init__(self, newvars=[]): Parameters newvars : array-like - Sequence of strings that represent additional extraction parameters.""" + Sequence of strings that represent additional extraction parameters. + """ self.clear() self.extractvars = dict.fromkeys( ( @@ -94,7 +95,8 @@ def __init__(self, newvars=[]): def clear(self): """Clear all members. - The purpose of the method is to ensure the object is in initialized state.""" + The purpose of the method is to ensure the object is in initialized state. + """ self.x = None self.y = None self.dx = None @@ -299,7 +301,7 @@ def plot(self, **kwds): plt.plot(*mcluster.plottable(kwds)) def read(self, filename): - """load PeakExtraction object from file + """Load PeakExtraction object from file. Parameters ---------- @@ -808,7 +810,8 @@ def extract_single(self, recursion_depth=1): specified by error_method. Parameters - recursion_depth: (1) Tracks recursion with extract_single.""" + recursion_depth: (1) Tracks recursion with extract_single. + """ self.clearcalc() tracer = srmiselog.tracer tracer.pushc() @@ -1319,8 +1322,10 @@ def extract_single(self, recursion_depth=1): return cov def fit_single(self): - """Fit peaks in initial_peaks with baseline. Return ModelCovariance - instance summarizing results.""" + """Fit peaks in initial_peaks with baseline. + + Return ModelCovariance instance summarizing results. + """ self.clearcalc() diff --git a/src/diffpy/srmise/peaks/base.py b/src/diffpy/srmise/peaks/base.py index 44c7963..67cf40c 100644 --- a/src/diffpy/srmise/peaks/base.py +++ b/src/diffpy/srmise/peaks/base.py @@ -70,7 +70,7 @@ def __init__( base=None, Cache=None, ): - """Set parameterdict defined by subclass + """Set parameterdict defined by subclass. parameterdict: A dictionary mapping string keys to their index in a sequence of parameters for this PeakFunction subclass. @@ -85,7 +85,8 @@ def __init__( base: A basefunction subclass instance which this one decorates with additional functionality. Cache: A class (not instance) which implements caching of BaseFunction - evaluations.""" + evaluations. + """ if "position" not in parameterdict: emsg = "Argument parameterdict missing required key 'position'." raise ValueError(emsg) diff --git a/src/diffpy/srmise/peaks/gaussian.py b/src/diffpy/srmise/peaks/gaussian.py index c23358e..94a6d6a 100644 --- a/src/diffpy/srmise/peaks/gaussian.py +++ b/src/diffpy/srmise/peaks/gaussian.py @@ -44,8 +44,8 @@ class Gaussian(PeakFunction): # which the function is considered 0. By default this distance is # equivalent to 3 standard deviations. def __init__(self, maxwidth, Cache=None): - """maxwidth defined as full width at half maximum for the - corresponding Gaussian, which is physically relevant.""" + """Maxwidth defined as full width at half maximum for the corresponding Gaussian, which is physically + relevant.""" parameterdict = {"position": 0, "width": 1, "area": 2} formats = ["internal", "pwa", "mu_sigma_area"] default_formats = {"default_input": "internal", "default_output": "pwa"} @@ -172,7 +172,8 @@ def scale_at(self, pars, x, scale): Returns ------- tuple - mu, area, and sigma that are scaled.""" + mu, area, and sigma that are scaled. + """ if scale <= 0: emsg = "".join(["Cannot scale by ", str(scale), "."]) raise SrMiseScalingError(emsg) @@ -383,6 +384,7 @@ def getmodule(self): def max(self, pars): """Return position and height of the peak maximum. + Parameters ---------- pars : array_like @@ -391,7 +393,8 @@ def max(self, pars): Returns ------- array_like - The position and height of the peak maximum.""" + The position and height of the peak maximum. + """ # TODO: Reconsider this behavior if len(pars) == 0: return None diff --git a/src/diffpy/srmise/peaks/gaussianoverr.py b/src/diffpy/srmise/peaks/gaussianoverr.py index 6e108e6..d6000f3 100644 --- a/src/diffpy/srmise/peaks/gaussianoverr.py +++ b/src/diffpy/srmise/peaks/gaussianoverr.py @@ -44,8 +44,8 @@ class GaussianOverR(PeakFunction): # which the function is considered 0. By default this distance is # equivalent to 3 standard deviations. def __init__(self, maxwidth, Cache=None): - """maxwidth defined as full width at half maximum for the - corresponding Gaussian, which is physically relevant.""" + """Maxwidth defined as full width at half maximum for the corresponding Gaussian, which is physically + relevant.""" parameterdict = {"position": 0, "width": 1, "area": 2} formats = ["internal", "pwa", "mu_sigma_area"] default_formats = {"default_input": "internal", "default_output": "pwa"} @@ -221,8 +221,7 @@ def scale_at(self, pars, x, scale): return tpars def _jacobianraw(self, pars, r, free): - """ - Compute the Jacobian of a width-limited Gaussian/r function. + """Compute the Jacobian of a width-limited Gaussian/r function. This method calculates the partial derivatives of a Gaussian/r function with respect to its parameters, considering a limiting width. The Gaussian/r's @@ -456,7 +455,8 @@ def max(self, pars): Returns ------- array-like - The sequence of position and height of the peak maximum.""" + The sequence of position and height of the peak maximum. + """ # TODO: Reconsider this behavior if len(pars) == 0: return None diff --git a/src/diffpy/srmise/peaks/terminationripples.py b/src/diffpy/srmise/peaks/terminationripples.py index c516c96..845de5f 100644 --- a/src/diffpy/srmise/peaks/terminationripples.py +++ b/src/diffpy/srmise/peaks/terminationripples.py @@ -46,7 +46,8 @@ def __init__(self, base, qmax, extension=4.0, supersample=5.0, Cache=None): cannot be determined while extending calculations. Default is 5.0. Cache : class The class (not instance) which implements caching of PeakFunction - evaluations.""" + evaluations. + """ parameterdict = base.parameterdict formats = base.parformats default_formats = base.default_formats @@ -179,7 +180,8 @@ def _valueraw(self, pars, r): Returns ------- float - The value of base peak function for the given parameters and r.""" + The value of base peak function for the given parameters and r. + """ return self.base._valueraw(pars, r) # Overridden PeakFunction functions #### @@ -205,7 +207,8 @@ def jacobian(self, peak, r, rng=None): Returns ------- jac : array-like - The Jacobian of base function with termination ripples.""" + The Jacobian of base function with termination ripples. + """ if self is not peak._owner: raise ValueError( "Argument 'peak' must be evaluated by the " @@ -361,7 +364,8 @@ def extend_grid(self, r, dr): Returns ------- tuple - The extended r, slice giving original range.""" + The extended r, slice giving original range. + """ ext = self.extension * 2 * np.pi / self.qmax left_ext = np.arange(r[0] - dr, max(0.0, r[0] - ext - dr), -dr)[::-1] right_ext = np.arange(r[-1] + dr, r[-1] + ext + dr, dr) diff --git a/src/diffpy/srmise/peakstability.py b/src/diffpy/srmise/peakstability.py index 28c9517..f95774b 100644 --- a/src/diffpy/srmise/peakstability.py +++ b/src/diffpy/srmise/peakstability.py @@ -29,7 +29,8 @@ class PeakStability: """Utility to test robustness of peaks. results: [error scalar, model, bl, dr] - ppe: a PDFPeakExtraction instance""" + ppe: a PDFPeakExtraction instance + """ def __init__(self): self.results = [] @@ -106,7 +107,10 @@ def plotseries(self, style="o", **kwds): plt.draw() def plot(self, **kwds): - """Plot the current model. Keywords passed to pyplot.plot()""" + """Plot the current model. + + Keywords passed to pyplot.plot() + """ plt.clf() plt.plot(*self.ppe.extracted.plottable(), **kwds) q = self.ppe.extracted.quality() @@ -187,7 +191,8 @@ def run(self, err, savecovs=False): The sequence of uncertainties to run at. savecovs : bool boolean to determine to save covariance matrix. Default is False. - If savecovs is True, return the covariance matrix for each final fit.""" + If savecovs is True, return the covariance matrix for each final fit. + """ self.results = [] covs = [] diff --git a/src/diffpy/srmise/srmiseerrors.py b/src/diffpy/srmise/srmiseerrors.py index 62953d5..22e8948 100644 --- a/src/diffpy/srmise/srmiseerrors.py +++ b/src/diffpy/srmise/srmiseerrors.py @@ -13,20 +13,20 @@ ############################################################################## """Defines all custom exceptions used by diffpy.srmise. - Classes - ------- - SrMiseError: Subclass of Exception, and superclass of all diffpy.srmise exceptions. - SrMiseDataFormatError: Error in format of diffpy.srmise data. - SrMiseEstimationError: Parameter estimation error. - SrMiseFileError: Error while reading/writing files. - SrMiseFitError: Error while fitting. - SrMiseLogError: Error while logging. - SrMiseModelEvaluatorError: Error while computing or comparing model quality. - SrMisePDFKeyError: Error in key referencing component of PDF dataset. - SrMiseQmaxError: Error in value of Qmax. - SrMiseScalingError: Error while scaling a peak function. - SrMiseStaticOwnerError: Error when changing ModelPart instance owner. - """ +Classes +------- +SrMiseError: Subclass of Exception, and superclass of all diffpy.srmise exceptions. +SrMiseDataFormatError: Error in format of diffpy.srmise data. +SrMiseEstimationError: Parameter estimation error. +SrMiseFileError: Error while reading/writing files. +SrMiseFitError: Error while fitting. +SrMiseLogError: Error while logging. +SrMiseModelEvaluatorError: Error while computing or comparing model quality. +SrMisePDFKeyError: Error in key referencing component of PDF dataset. +SrMiseQmaxError: Error in value of Qmax. +SrMiseScalingError: Error while scaling a peak function. +SrMiseStaticOwnerError: Error when changing ModelPart instance owner. +""" # Superclass class for diffpy.srmise.mise @@ -34,9 +34,10 @@ class SrMiseError(Exception): """Superclass of all diffpy.srmise exceptions.""" def __init__(self, info): - """initialize + """initialize. - info: description string""" + info: description string + """ Exception.__init__(self) self.info = info @@ -48,120 +49,168 @@ def __str__(self): class SrMiseDataFormatError(SrMiseError): - """diffpy.srmise exception class. Error in formatted data.""" + """diffpy.srmise exception class. + + Error in formatted data. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseEstimationError(SrMiseError): - """diffpy.srmise.modelevaluator exception class. Parameter estimation error.""" + """diffpy.srmise.modelevaluator exception class. + + Parameter estimation error. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseFileError(SrMiseError): - """diffpy.srmise exception class. Error while reading/writing files.""" + """diffpy.srmise exception class. + + Error while reading/writing files. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseFitError(SrMiseError): - """diffpy.srmise exception class. Error occurred during fitting.""" + """diffpy.srmise exception class. + + Error occurred during fitting. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseLogError(SrMiseError): - """diffpy.srmise exception class. Error while handling logging capabilities.""" + """diffpy.srmise exception class. + + Error while handling logging capabilities. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseModelEvaluatorError(SrMiseError): - """diffpy.srmise.modelevaluator exception class. Error when comparing models.""" + """diffpy.srmise.modelevaluator exception class. + + Error when comparing models. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseQmaxError(SrMiseError): - """diffpy.srmise.modelevaluator exception class. Error when setting qmax.""" + """diffpy.srmise.modelevaluator exception class. + + Error when setting qmax. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseScalingError(SrMiseError): - """diffpy.srmise.peaks exception class. Error when scaling a peak function.""" + """diffpy.srmise.peaks exception class. + + Error when scaling a peak function. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseStaticOwnerError(SrMiseError): - """diffpy.srmise exception class. Attempt to change owner of static model part.""" + """diffpy.srmise exception class. + + Attempt to change owner of static model part. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseTransformationError(SrMiseError): - """diffpy.srmise exception class. Error transforming model/covariance parameters.""" + """diffpy.srmise exception class. + + Error transforming model/covariance parameters. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMiseUndefinedCovarianceError(SrMiseError): - """diffpy.srmise exception class. Attempted to perform on undefined covariance.""" + """diffpy.srmise exception class. + + Attempted to perform on undefined covariance. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) class SrMisePDFKeyError(SrMiseError): - """diffpy.srmise exception class. Requested PDF key can't be found.""" + """diffpy.srmise exception class. + + Requested PDF key can't be found. + """ def __init__(self, info): - """initialize + """initialize. - info -- description string""" + info -- description string + """ SrMiseError.__init__(self, info) diff --git a/src/diffpy/srmise/srmiselog.py b/src/diffpy/srmise/srmiselog.py index e4311a0..5393475 100644 --- a/src/diffpy/srmise/srmiselog.py +++ b/src/diffpy/srmise/srmiselog.py @@ -95,7 +95,8 @@ def setfilelevel(level): """Set level of file logger. Parameters - level: The logging level.""" + level: The logging level. + """ global fh if fh is not None: level = LEVELS.get(level, level) @@ -111,7 +112,8 @@ def setlevel(level): """Set level of default (stdout) logger. Parameters - level: The logging level.""" + level: The logging level. + """ global ch level = LEVELS.get(level, level) ch.setLevel(level) @@ -127,7 +129,8 @@ def liveplotting(lp, w=False): Parameters lp: Use live plotting (True) or not (False). - w: (False) Whether to wait for user after plotting.""" + w: (False) Whether to wait for user after plotting. + """ global liveplots global wait if lp is True or lp is False: @@ -172,8 +175,8 @@ def __init__(self, **kwds): def emit(self, *args, **kwds): """Write current trace to file. - Parameters - Any number of ModelCluster instances""" + Parameters Any number of ModelCluster instances + """ if not eval(self.filter): return else: @@ -236,7 +239,8 @@ def read(self, filename): "clusters" - List of cluster regions [[r0,r1],[r2,r3],...] "counter" - The count when object was created "mc" - A ModelCluster instance - "recursion" - The recursion level of mc""" + "recursion" - The recursion level of mc + """ try: return self.readstr(open(filename, "rb").read()) except SrMiseDataFormatError as err: @@ -258,7 +262,8 @@ def readstr(self, datastring): "clusters" - List of cluster regions [[r0,r1],[r2,r3],...] "counter" - The count when object was created "mc" - A ModelCluster instance - "recursion" - The recursion level of mc""" + "recursion" - The recursion level of mc + """ # find where the ModelCluster section starts res = re.search(r"^#+ ModelCluster\s*(?:#.*\s+)*", datastring, re.M) diff --git a/src/diffpy/srmise/version.py b/src/diffpy/srmise/version.py index 304027c..129ef83 100644 --- a/src/diffpy/srmise/version.py +++ b/src/diffpy/srmise/version.py @@ -12,7 +12,6 @@ # See LICENSE.rst for license information. # ############################################################################## - """Definition of __version__.""" # We do not use the other three variables, but can be added back if needed. diff --git a/tests/test_version.py b/tests/test_version.py index 1bc10c2..cdf83c8 100644 --- a/tests/test_version.py +++ b/tests/test_version.py @@ -1,5 +1,4 @@ -"""Unit tests for __version__.py -""" +"""Unit tests for __version__.py.""" import diffpy.srmise