diff --git a/diffpy/srmise/applications/extract.py b/diffpy/srmise/applications/extract.py index 5f54118..c070704 100755 --- a/diffpy/srmise/applications/extract.py +++ b/diffpy/srmise/applications/extract.py @@ -419,25 +419,19 @@ def main(): from diffpy.srmise.pdfpeakextraction import PDFPeakExtraction from diffpy.srmise.srmiseerrors import SrMiseDataFormatError, SrMiseFileError - if options.peakfunction is not None: - from diffpy.srmise import peaks - - try: - options.peakfunction = eval("peaks." + options.peakfunction) - except Exception as err: - print(err) - print("Could not create peak function '%s'. Exiting." % options.peakfunction) - return - - if options.modelevaluator is not None: - from diffpy.srmise import modelevaluators - - try: - options.modelevaluator = eval("modelevaluators." + options.modelevaluator) - except Exception as err: - print(err) - print("Could not find ModelEvaluator '%s'. Exiting." % options.modelevaluator) - return + try: + options.peakfunction = eval("peaks." + options.peakfunction) + except Exception as err: + print(err) + print("Could not create peak function '%s'. Exiting." % options.peakfunction) + return + + try: + options.modelevaluator = eval("modelevaluators." + options.modelevaluator) + except Exception as err: + print(err) + print("Could not find ModelEvaluator '%s'. Exiting." % options.modelevaluator) + return if options.bcrystal is not None: from diffpy.srmise.baselines import Polynomial @@ -475,8 +469,6 @@ def main(): bl = NanoSpherical() options.baseline = parsepars(bl, options.bspherical) - elif options.baseline is not None: - from diffpy.srmise import baselines try: options.baseline = eval("baselines." + options.baseline) diff --git a/diffpy/srmise/modelevaluators/aic.py b/diffpy/srmise/modelevaluators/aic.py index 7321d9f..a8d870b 100644 --- a/diffpy/srmise/modelevaluators/aic.py +++ b/diffpy/srmise/modelevaluators/aic.py @@ -16,7 +16,6 @@ import numpy as np -import diffpy.srmise.srmiselog from diffpy.srmise.modelevaluators.base import ModelEvaluator from diffpy.srmise.srmiseerrors import SrMiseModelEvaluatorError @@ -72,7 +71,7 @@ def evaluate(self, fit, count_fixed=False, kshift=0): logger.warn("AIC.evaluate(): too few data to evaluate quality reliably.") n = self.minpoints(k) - if self.chisq == None: + if self.chisq is None: self.chisq = self.chi_squared(fit.value(), fit.y_cluster, fit.error_cluster) self.stat = self.chisq + self.parpenalty(k, n) @@ -94,10 +93,12 @@ def parpenalty(self, k, n): 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. - 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 these parameters is less than the current chiSquared cost. The validity of this assumption (which - depends on an unknown chiSquared value) and the impact of the errors used should be examined more thoroughly in the future. + """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 + these parameters is less than the current chiSquared cost. + The validity of this assumption (which depends on an unknown chiSquared value) + and the impact of the errors used should be examined more thoroughly in the future. """ if self.chisq is None: diff --git a/diffpy/srmise/pdfpeakextraction.py b/diffpy/srmise/pdfpeakextraction.py index f68a7cf..ab5f03d 100644 --- a/diffpy/srmise/pdfpeakextraction.py +++ b/diffpy/srmise/pdfpeakextraction.py @@ -16,20 +16,24 @@ import os.path import re -import matplotlib.pyplot as plt import numpy as np +from diffpy.srmise import srmiselog from diffpy.srmise.modelcluster import ModelCluster, ModelCovariance # from diffpy.pdfgui.control.pdfdataset import PDFDataSet from diffpy.srmise.pdfdataset import PDFDataSet from diffpy.srmise.peakextraction import PeakExtraction -from diffpy.srmise.srmiseerrors import * +from diffpy.srmise.srmiseerrors import ( + SrMiseDataFormatError, + SrMiseError, + SrMiseQmaxError, + SrMiseStaticOwnerError, + SrMiseUndefinedCovarianceError, +) logger = logging.getLogger("diffpy.srmise") -from diffpy.srmise import srmiselog - class PDFPeakExtraction(PeakExtraction): """Class for peak extraction of peaks from the PDF. @@ -454,7 +458,7 @@ def extract(self, **kwds): try: logger.info(str(cov)) # logger.info("Correlations > .8:\n%s", "\n".join(str(c) for c in cov.correlationwarning(.8))) - except SrMiseUndefinedCovarianceError as e: + except SrMiseUndefinedCovarianceError: logger.warn("Covariance not defined for final model. Fit may not have converged.") logger.info(str(ext)) @@ -527,7 +531,7 @@ def fit(self, **kwds): logger.info(str(ext)) try: logger.info(str(cov)) - except SrMiseUndefinedCovarianceError as e: + except SrMiseUndefinedCovarianceError: logger.warn("Covariance not defined for final model. Fit may not have converged.") # Update calculated instance variables diff --git a/diffpy/srmise/peaks/__init__.py b/diffpy/srmise/peaks/__init__.py index dba8fb9..ea3cdfc 100644 --- a/diffpy/srmise/peaks/__init__.py +++ b/diffpy/srmise/peaks/__init__.py @@ -13,8 +13,3 @@ ############################################################################## __all__ = ["base", "gaussian", "gaussianoverr", "terminationripples"] - -from base import Peak, Peaks -from gaussian import Gaussian -from gaussianoverr import GaussianOverR -from terminationripples import TerminationRipples diff --git a/diffpy/srmise/peaks/base.py b/diffpy/srmise/peaks/base.py index ddd6095..47e7a78 100644 --- a/diffpy/srmise/peaks/base.py +++ b/diffpy/srmise/peaks/base.py @@ -16,10 +16,9 @@ import numpy as np -import diffpy.srmise.srmiselog from diffpy.srmise.basefunction import BaseFunction from diffpy.srmise.modelparts import ModelPart, ModelParts -from diffpy.srmise.srmiseerrors import * +from diffpy.srmise.srmiseerrors import SrMiseDataFormatError, SrMiseScalingError logger = logging.getLogger("diffpy.srmise") @@ -263,17 +262,16 @@ def factory(peakstr, ownerlist): peakstr: string representing peak ownerlist: List of BaseFunctions that owner is in """ - from numpy import array data = peakstr.strip().splitlines() # dictionary of parameters pdict = {} for d in data: - l = d.split("=", 1) - if len(l) == 2: + parse_value = d.split("=", 1) + if len(parse_value) == 2: try: - pdict[l[0]] = eval(l[1]) + pdict[parse_value[0]] = eval(parse_value[1]) except Exception: emsg = "Invalid parameter: %s" % d raise SrMiseDataFormatError(emsg) diff --git a/diffpy/srmise/peaks/terminationripples.py b/diffpy/srmise/peaks/terminationripples.py index 7c4785a..f916d3b 100644 --- a/diffpy/srmise/peaks/terminationripples.py +++ b/diffpy/srmise/peaks/terminationripples.py @@ -281,7 +281,6 @@ def extend_grid(self, r, dr): from diffpy.srmise.modelevaluators import AICc from diffpy.srmise.peaks import Peaks from diffpy.srmise.peaks.gaussianoverr import GaussianOverR - from diffpy.srmise.peaks.terminationripples import TerminationRipples res = 0.01 r = np.arange(2, 4, res) diff --git a/diffpy/srmise/srmiselog.py b/diffpy/srmise/srmiselog.py index bfc6002..361ea4b 100644 --- a/diffpy/srmise/srmiselog.py +++ b/diffpy/srmise/srmiselog.py @@ -41,11 +41,10 @@ import logging import os.path import re -import sys from diffpy.srmise.srmiseerrors import SrMiseDataFormatError, SrMiseFileError, SrMiseLogError -### Default settings ### +# Default settings ### defaultformat = "%(message)s" defaultlevel = logging.INFO @@ -57,7 +56,7 @@ "critical": logging.CRITICAL, } -### Set up logging to stdout ### +# Set up logging to stdout ### logger = logging.getLogger("diffpy.srmise") logger.setLevel(defaultlevel) ch = logging.StreamHandler() @@ -68,10 +67,10 @@ logger.addHandler(ch) -### Optional file logger ### +# Optional file logger ### fh = None -### Make updated plots as fitting progresses. ### +# Make updated plots as fitting progresses. ### liveplots = False wait = False @@ -144,7 +143,7 @@ def liveplotting(lp, w=False): raise ValueError(emsg) -### TracePeaks. Primary purpose is to enable creating movies. ### +# TracePeaks. Primary purpose is to enable creating movies. ### class TracePeaks(object): @@ -345,7 +344,7 @@ def getfilter(self): filter = property(getfilter, setfilter) -### End of class TracePeaks +# End of class TracePeaks def settracer(**kwds): diff --git a/doc/examples/extract_single_peak.py b/doc/examples/extract_single_peak.py index 99edd4c..b32b0be 100644 --- a/doc/examples/extract_single_peak.py +++ b/doc/examples/extract_single_peak.py @@ -27,26 +27,26 @@ import matplotlib.pyplot as plt -from diffpy.srmise import PDFPeakExtraction from diffpy.srmise.applications.plot import makeplot from diffpy.srmise.baselines import Polynomial +from diffpy.srmise.pdfpeakextraction import PDFPeakExtraction def run(plot=True): - ## Initialize peak extraction + # Initialize peak extraction # Create peak extraction object ppe = PDFPeakExtraction() # Load the PDF from a file ppe.loadpdf("data/Ag_nyquist_qmax30.gr") - ## Set up extraction parameters. - # For convenience we add all parameters to a dictionary before passing them + # Set up extraction parameters. + # For convenience, we add all parameters to a dictionary before passing them # to the extraction object. # # The "rng" (range) parameter defines the region over which peaks will be - # extracted and fit. For the well isolated nearest-neighbor silver peak, + # extracted and fit. For the well isolated nearest-neighbor silver peak, # which occurs near 2.9 angstroms, it is sufficient to perform extraction # between 2 and 3.5 angstroms. # @@ -61,24 +61,24 @@ def run(plot=True): # Apply peak extraction parameters. ppe.setvars(**kwds) - ## Perform peak extraction + # Perform peak extraction ppe.extract() - ## Save output + # Save output # The write() method saves a file which preserves all aspects of peak # extraction and its results, by convention using the .srmise extension, # and which can later be read by diffpy.srmise. # # The writepwa() method saves a file intended as a human-readable summary. # In particular, it reports the position, width (as full-width at - # half-maximum), and area of of extracted peaks. The reported values + # half-maximum), and area of extracted peaks. The reported values # are for Gaussians in the radial distribution function (RDF) corresponding # to this PDF. ppe.write("output/extract_single_peak.srmise") ppe.writepwa("output/extract_single_peak.pwa") - ## Plot results. - # Display plot of extracted peak. It is also possible to plot an existing + # Plot results. + # Display plot of extracted peak. It is also possible to plot an existing # .srmise file from the command line using # srmise output/Ag_singlepeak.srmise --no-extract --plot # For additional plotting options, run "srmiseplot --help".