Skip to content

Commit

Permalink
lint check, fix break import modules, remove unused import modules, r…
Browse files Browse the repository at this point in the history
…emove some # (diffpy#33)
  • Loading branch information
stevenhua0320 authored Jul 30, 2024
1 parent 30d0909 commit 7dd69bc
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 62 deletions.
34 changes: 13 additions & 21 deletions diffpy/srmise/applications/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 7 additions & 6 deletions diffpy/srmise/modelevaluators/aic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
16 changes: 10 additions & 6 deletions diffpy/srmise/pdfpeakextraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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
Expand Down
5 changes: 0 additions & 5 deletions diffpy/srmise/peaks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 4 additions & 6 deletions diffpy/srmise/peaks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion diffpy/srmise/peaks/terminationripples.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 6 additions & 7 deletions diffpy/srmise/srmiselog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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()
Expand All @@ -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

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -345,7 +344,7 @@ def getfilter(self):
filter = property(getfilter, setfilter)


### End of class TracePeaks
# End of class TracePeaks


def settracer(**kwds):
Expand Down
20 changes: 10 additions & 10 deletions doc/examples/extract_single_peak.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand All @@ -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".
Expand Down

0 comments on commit 7dd69bc

Please sign in to comment.