Skip to content

Commit

Permalink
Merge branch 'Cookie' of github.com:diffpy/diffpy.srmise into Cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
sbillinge committed Jul 30, 2024
2 parents 73b25a8 + edaa35d commit 166e726
Show file tree
Hide file tree
Showing 20 changed files with 121 additions and 146 deletions.
6 changes: 4 additions & 2 deletions devutils/prep.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

__basedir__ = os.getcwdu()

from numpy.compat import unicode

# Example imports


Expand Down Expand Up @@ -86,7 +88,7 @@ def rm(directory, filerestr):
rm("../doc/examples/output", r"known_dG.*\.pwa")
rm("../doc/examples/output", r"unknown_dG.*\.pwa")

### Testing examples
# Testing examples
examples = Test()
test_names = [
"extract_single_peak",
Expand All @@ -108,7 +110,7 @@ def rm(directory, filerestr):

examples.report()

### Convert output of example files to Unix-style endlines for sdist.
# Convert output of example files to Unix-style endlines for sdist.
if os.linesep != "\n":
print("==== Scrubbing Endlines ====")
# All *.srmise and *.pwa files in examples directory.
Expand Down
11 changes: 4 additions & 7 deletions diffpy/srmise/applications/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
#
##############################################################################

from optparse import OptionGroup, OptionParser
import textwrap
from optparse import IndentedHelpFormatter, OptionGroup, OptionParser

import matplotlib.pyplot as plt
import numpy as np
Expand Down Expand Up @@ -539,7 +540,6 @@ def main():
cov = None
if options.performextraction:
cov = ext.extract()
out = ext.extracted

if options.savefile is not None:
try:
Expand Down Expand Up @@ -591,13 +591,10 @@ def parsepars(mp, parseq):
return mp.actualize(pars, "internal", free=free)


### Class to preserve newlines in optparse
# Class to preserve newlines in optparse
# Borrowed, with minor changes, from
# http://groups.google.com/group/comp.lang.python/browse_frm/thread/6df6e6b541a15bc2/09f28e26af0699b1

import textwrap
from optparse import IndentedHelpFormatter


class IndentedHelpFormatterWithNL(IndentedHelpFormatter):
def _format_text(self, text):
Expand Down Expand Up @@ -652,7 +649,7 @@ def format_option(self, option):
return "".join(result)


### End class
# End class

if __name__ == "__main__":
main()
13 changes: 5 additions & 8 deletions diffpy/srmise/applications/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import mpl_toolkits.axisartist as AA
import numpy as np
from matplotlib.ticker import MultipleLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

from diffpy.srmise import PDFPeakExtraction, PeakStability
Expand Down Expand Up @@ -107,7 +106,6 @@ def comparepositions(ppe, ip=None, **kwds):
plt.plot(xe, ye, "g", lw=1.5, **ep_style)

if ip is not None:
yb = (base, base)
plt.axhline(base, linestyle=":", color="k")
ax.yaxis.set_ticks([base + 0.5 * yideal, base + 0.5 * yext])
ax.yaxis.set_ticklabels([yideal_label, yext_label])
Expand All @@ -134,7 +132,7 @@ def comparepositions(ppe, ip=None, **kwds):


def dgseries(stability, **kwds):
ax = kwds.get("ax", plt.gca())
kwds.get("ax", plt.gca())
dg_style = kwds.get("dg_style", default_dg_style)

scale = kwds.get("scale", 1.0)
Expand Down Expand Up @@ -222,7 +220,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
bottom_offset = kwds.get("bottom_offset", 3.0)

# Style options
dg_style = kwds.get("dg_style", default_dg_style)
kwds.get("dg_style", default_dg_style)
gobs_style = kwds.get("gobs_style", default_gobs_style)
gfit_style = kwds.get("gfit_style", default_gfit_style)
gind_style = kwds.get("gind_style", default_gind_style)
Expand All @@ -240,7 +238,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
# Other options
datalabel = kwds.get("datalabel", None)
dgformatstr = kwds.get("dgformatstr", r"$\delta$g=%f")
dgformatpost = kwds.get("dgformatpost", None) # ->userfunction(string)
kwds.get("dgformatpost", None) # ->userfunction(string)
show_fit = kwds.get("show_fit", True)
show_individual = kwds.get("show_individual", True)
fill_individual = kwds.get("fill_individual", True)
Expand Down Expand Up @@ -532,7 +530,6 @@ def on_draw(event):

def readcompare(filename):
"""Returns a list of distances read from filename, otherwise None."""
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError, SrMiseFileError

# TODO: Make this safer
try:
Expand All @@ -551,7 +548,7 @@ def readcompare(filename):
try:
for line in datastring.split("\n"):
distances.append(float(line))
except (ValueError, IndexError) as err:
except (ValueError, IndexError):
print("Could not read distances from '%s'. Ignoring file." % filename)

if len(distances) == 0:
Expand Down Expand Up @@ -620,7 +617,7 @@ def main():
distances = readcompare(opts.compare)

setfigformat(figsize=(6.0, 4.0))
figdict = makeplot(toplot, distances)
makeplot(toplot, distances)
if opts.output:
plt.savefig(opts.output, format=opts.format, dpi=600)
if opts.show:
Expand Down
19 changes: 9 additions & 10 deletions diffpy/srmise/basefunction.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@
import numpy as np
from numpy.compat import unicode

from diffpy.srmise.modelparts import ModelPart, ModelParts
from diffpy.srmise.srmiseerrors import *
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError

logger = logging.getLogger("diffpy.srmise")

Expand Down Expand Up @@ -120,7 +119,7 @@ def __init__(
emsg = "Argument default_formats must specify 'default_input' " + "and 'default_output' as keys."
raise ValueError(emsg)
for f in self.default_formats.values():
if not f in self.parformats:
if f not in self.parformats:
emsg = "Keys of argument default_formats must map to a " + "value within argument parformats."
raise ValueError()

Expand All @@ -140,7 +139,7 @@ def __init__(
pass
return

#### "Virtual" class methods ####
# "Virtual" class methods ####

def actualize(self, *args, **kwds):
"""Create ModelPart instance of self with given parameters. ("Virtual" method)"""
Expand Down Expand Up @@ -172,7 +171,7 @@ def _valueraw(self, *args, **kwds):
emsg = "_valueraw must() be implemented in a BaseFunction subclass."
raise NotImplementedError(emsg)

#### Class methods ####
# Class methods ####

def jacobian(self, p, r, rng=None):
"""Calculate jacobian of p, possibly restricted by range.
Expand Down Expand Up @@ -228,9 +227,9 @@ def transform_derivatives(self, pars, in_format=None, out_format=None):
elif out_format == "default_input":
out_format = self.default_formats["default_input"]

if not in_format in self.parformats:
if in_format not in self.parformats:
raise ValueError("Argument 'in_format' must be one of %s." % self.parformats)
if not out_format in self.parformats:
if out_format not in self.parformats:
raise ValueError("Argument 'out_format' must be one of %s." % self.parformats)
if in_format == out_format:
return np.identity(self.npars)
Expand Down Expand Up @@ -263,9 +262,9 @@ def transform_parameters(self, pars, in_format=None, out_format=None):
elif out_format == "default_input":
out_format = self.default_formats["default_input"]

if not in_format in self.parformats:
if in_format not in self.parformats:
raise ValueError("Argument 'in_format' must be one of %s." % self.parformats)
if not out_format in self.parformats:
if out_format not in self.parformats:
raise ValueError("Argument 'out_format' must be one of %s." % self.parformats)
# if in_format == out_format:
# return pars
Expand Down Expand Up @@ -335,7 +334,7 @@ def writestr(self, baselist):
"""
if self.base is not None and self.base not in baselist:
emsg = "baselist does not include this BaseFunction's base function."
raise ValueError("emsg")
raise ValueError(emsg)
lines = []
# Write function type
lines.append("function=%s" % repr(self.__class__.__name__))
Expand Down
6 changes: 2 additions & 4 deletions diffpy/srmise/baselines/arbitrary.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@

import logging

import matplotlib.pyplot as plt
import numpy as np

import diffpy.srmise.srmiselog
from diffpy.srmise.baselines import Polynomial
from diffpy.srmise.baselines.base import BaselineFunction
from diffpy.srmise.srmiseerrors import SrMiseEstimationError
Expand Down Expand Up @@ -97,7 +95,7 @@ def __init__(self, npars, valuef, jacobianf=None, estimatef=None, Cache=None):
metadict["estimatef"] = (estimatef, repr)
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache)

#### Methods required by BaselineFunction ####
# Methods required by BaselineFunction ####

def estimate_parameters(self, r, y):
"""Estimate parameters for data baseline.
Expand Down Expand Up @@ -133,7 +131,7 @@ def _jacobianraw(self, pars, r, free):
needed. True for evaluation, False for no evaluation."""
nfree = None
if self.jacobianf is None:
nfree = (pars == True).sum()
nfree = (pars is True).sum()
if nfree != 0:
emsg = "No jacobian routine provided to Arbitrary."
raise NotImplementedError(emsg)
Expand Down
16 changes: 6 additions & 10 deletions diffpy/srmise/baselines/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@

import numpy as np

import diffpy.srmise.srmiselog
from diffpy.srmise.basefunction import BaseFunction
from diffpy.srmise.modelparts import ModelPart
from diffpy.srmise.srmiseerrors import *
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError

logger = logging.getLogger("diffpy.srmise")

Expand Down Expand Up @@ -85,9 +84,9 @@ def __init__(
evaluations."""
BaseFunction.__init__(self, parameterdict, parformats, default_formats, metadict, base, Cache)

#### "Virtual" class methods ####
# "Virtual" class methods ####

#### Methods required by BaseFunction ####
# Methods required by BaseFunction ####

def actualize(
self,
Expand Down Expand Up @@ -136,17 +135,16 @@ def factory(baselinestr, ownerlist):
baselinestr: string representing Baseline
ownerlist: List of BaseFunctions that owner is in
"""
from numpy import array

data = baselinestr.strip().splitlines()

# dictionary of parameters
pdict = {}
for d in data:
l = d.split("=", 1)
if len(l) == 2:
result = d.split("=", 1)
if len(result) == 2:
try:
pdict[l[0]] = eval(l[1])
pdict[result[0]] = eval(result[1])
except Exception:
emsg = "Invalid parameter: %s" % d
raise SrMiseDataFormatError(emsg)
Expand All @@ -169,10 +167,8 @@ def factory(baselinestr, ownerlist):
# simple test code
if __name__ == "__main__":

import matplotlib.pyplot as plt
from numpy.random import randn

from diffpy.srmise.modelcluster import ModelCluster
from diffpy.srmise.modelevaluators import AICc
from diffpy.srmise.peaks import GaussianOverR, Peaks

Expand Down
8 changes: 3 additions & 5 deletions diffpy/srmise/baselines/fromsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@

import logging

import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate as spi

import diffpy.srmise.srmiselog
from diffpy.srmise.baselines.base import BaselineFunction

logger = logging.getLogger("diffpy.srmise")
Expand Down Expand Up @@ -80,7 +78,7 @@ def __init__(self, *args, **kwds):
metadict["y"] = (y, self.xyrepr)
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache=None)

#### Methods required by BaselineFunction ####
# Methods required by BaselineFunction ####

def estimate_parameters(self, r, y):
"""Return empty numpy array.
Expand Down Expand Up @@ -151,7 +149,7 @@ def _valueraw(self, pars, r):
[r[0], r[-1]],
[self.minx, self.maxx],
)
except (IndexError, TypeError) as e:
except (IndexError, TypeError):
if r < self.minx or r > self.maxx:
logger.warn(
"Warning: Evaluating interpolating function at %s, outside safe range of %s.",
Expand All @@ -169,7 +167,7 @@ def xyrepr(self, var):

def readxy(self, filename):
""" """
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError, SrMiseFileError
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError

# TODO: Make this safer
try:
Expand Down
9 changes: 3 additions & 6 deletions diffpy/srmise/baselines/nanospherical.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,9 @@

import logging

import matplotlib.pyplot as plt
import numpy as np

import diffpy.srmise.srmiselog
from diffpy.srmise.baselines.base import BaselineFunction
from diffpy.srmise.srmiseerrors import SrMiseEstimationError

logger = logging.getLogger("diffpy.srmise")

Expand Down Expand Up @@ -54,7 +51,7 @@ def __init__(self, Cache=None):
metadict = {}
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache)

#### Methods required by BaselineFunction ####
# Methods required by BaselineFunction ####

# def estimate_parameters(self, r, y):
# """Estimate parameters for spherical baseline. (Not implemented!)
Expand Down Expand Up @@ -90,7 +87,7 @@ def _jacobianraw(self, pars, r, free):
emsg = "Argument free must have " + str(self.npars) + " elements."
raise ValueError(emsg)
jacobian = [None for p in range(self.npars)]
if (free == False).sum() == self.npars:
if (free is False).sum() == self.npars:
return jacobian

if np.isscalar(r):
Expand Down Expand Up @@ -123,7 +120,7 @@ def _jacobianrawscale(self, pars, r):
pars[1] = radius
r - sequence or scalar over which pars is evaluated.
"""
s = np.abs(pars[0])
np.abs(pars[0])
R = np.abs(pars[1])
rdivR = r / R
# From abs'(s) in derivative, which is equivalent to sign(s) except at 0 where it
Expand Down
Loading

0 comments on commit 166e726

Please sign in to comment.