Skip to content

Commit

Permalink
add pyproject.toml and pre-commit work
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenhua0320 committed Jul 29, 2024
1 parent 84d79aa commit 5d1dae4
Show file tree
Hide file tree
Showing 28 changed files with 270 additions and 605 deletions.
45 changes: 12 additions & 33 deletions diffpy/srmise/applications/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,7 @@ def main():
"--pf",
dest="peakfunction",
metavar="PF",
help="Fit peak function PF defined in "
"diffpy.srmise.peaks, e.g. "
"'GaussianOverR(maxwidth=0.7)'",
help="Fit peak function PF defined in " "diffpy.srmise.peaks, e.g. " "'GaussianOverR(maxwidth=0.7)'",
)
parser.add_option(
"--cres",
Expand Down Expand Up @@ -230,34 +228,30 @@ def main():
dest="bpoly0",
type="string",
metavar="a0[c]",
help="Use constant baseline given by y=a0. "
"Append 'c' to make parameter constant.",
help="Use constant baseline given by y=a0. " "Append 'c' to make parameter constant.",
)
group.add_option(
"--bpoly1",
dest="bpoly1",
type="string",
nargs=2,
metavar="a1[c] a0[c]",
help="Use baseline given by y=a1*x + a0. Append 'c' to "
"make parameter constant.",
help="Use baseline given by y=a1*x + a0. Append 'c' to " "make parameter constant.",
)
group.add_option(
"--bpoly2",
dest="bpoly2",
type="string",
nargs=3,
metavar="a2[c] a1[c] a0[c]",
help="Use baseline given by y=a2*x^2+a1*x + a0. Append "
"'c' to make parameter constant.",
help="Use baseline given by y=a2*x^2+a1*x + a0. Append " "'c' to make parameter constant.",
)
group.add_option(
"--bseq",
dest="bseq",
type="string",
metavar="FILE",
help="Use baseline interpolated from x,y values in FILE. "
"This baseline has no free parameters.",
help="Use baseline interpolated from x,y values in FILE. " "This baseline has no free parameters.",
)
group.add_option(
"--bspherical",
Expand Down Expand Up @@ -343,9 +337,7 @@ def main():
metavar="FILE",
help="Save result of extraction to FILE (.srmise " "format).",
)
group.add_option(
"--plot", "-p", action="store_true", dest="plot", help="Plot extracted peaks."
)
group.add_option("--plot", "-p", action="store_true", dest="plot", help="Plot extracted peaks.")
group.add_option(
"--liveplot",
"-l",
Expand All @@ -362,9 +354,7 @@ def main():
)
parser.add_option_group(group)

group = OptionGroup(
parser, "Verbosity Options", "Control detail printed to console."
)
group = OptionGroup(parser, "Verbosity Options", "Control detail printed to console.")
group.add_option(
"--informative",
"-i",
Expand Down Expand Up @@ -435,9 +425,7 @@ def main():
options.peakfunction = eval("peaks." + options.peakfunction)
except Exception as err:
print(err)
print(
"Could not create peak function '%s'. Exiting." % options.peakfunction
)
print("Could not create peak function '%s'. Exiting." % options.peakfunction)
return

if options.modelevaluator is not None:
Expand All @@ -447,9 +435,7 @@ def main():
options.modelevaluator = eval("modelevaluators." + options.modelevaluator)
except Exception as err:
print(err)
print(
"Could not find ModelEvaluator '%s'. Exiting." % options.modelevaluator
)
print("Could not find ModelEvaluator '%s'. Exiting." % options.modelevaluator)
return

if options.bcrystal is not None:
Expand Down Expand Up @@ -534,9 +520,7 @@ def main():
if options.rng is not None:
pdict["rng"] = list(options.rng)
if options.qmax is not None:
pdict["qmax"] = (
options.qmax if options.qmax == "automatic" else float(options.qmax)
)
pdict["qmax"] = options.qmax if options.qmax == "automatic" else float(options.qmax)
if options.nyquist is not None:
pdict["nyquist"] = options.nyquist
if options.supersample is not None:
Expand Down Expand Up @@ -624,10 +608,7 @@ def _format_text(self, text):
# the above is still the same
bits = text.split("\n")
formatted_bits = [
textwrap.fill(
bit, text_width, initial_indent=indent, subsequent_indent=indent
)
for bit in bits
textwrap.fill(bit, text_width, initial_indent=indent, subsequent_indent=indent) for bit in bits
]
result = "\n".join(formatted_bits) + "\n"
return result
Expand Down Expand Up @@ -665,9 +646,7 @@ def format_option(self, option):
help_lines.extend(textwrap.wrap(para, self.help_width))
# Everything is the same after here
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
result.extend(
["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]]
)
result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]])
elif opts[-1] != "\n":
result.append("\n")
return "".join(result)
Expand Down
55 changes: 11 additions & 44 deletions diffpy/srmise/applications/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,9 +194,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
x = ppe.x[rangeslice]
y = ppe.y[rangeslice]
dy = ppe.effective_dy[rangeslice]
mcluster = ModelCluster(
ppe.initial_peaks, ppe.baseline, x, y, dy, None, ppe.error_method, ppe.pf
)
mcluster = ModelCluster(ppe.initial_peaks, ppe.baseline, x, y, dy, None, ppe.error_method, ppe.pf)
ext = mcluster
else:
ext = ppe.extracted
Expand Down Expand Up @@ -255,9 +253,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
# Define the various data which will be plotted
r = ext.r_cluster
dr = (r[-1] - r[0]) / len(r)
rexpand = np.concatenate(
(np.arange(r[0] - dr, xlo, -dr)[::-1], r, np.arange(r[-1] + dr, xhi + dr, dr))
)
rexpand = np.concatenate((np.arange(r[0] - dr, xlo, -dr)[::-1], r, np.arange(r[-1] + dr, xhi + dr, dr)))
rfine = np.arange(r[0], r[-1], 0.1 * dr)
gr_obs = np.array(resample(ppe.x, ppe.y, rexpand)) * scale
# gr_fit = resample(r, ext.value(), rfine)
Expand Down Expand Up @@ -295,21 +291,10 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
max_res = 0.0

# Derive various y limits based on all the offsets
rel_height = (
100.0
- top_offset
- dg_height
- cmp_height
- datatop_offset
- databottom_offset
- bottom_offset
)
rel_height = 100.0 - top_offset - dg_height - cmp_height - datatop_offset - databottom_offset - bottom_offset
abs_height = 100 * ((max_gr - min_gr) + (max_res - min_res)) / rel_height

yhi = (
max_gr
+ (top_offset + dg_height + cmp_height + datatop_offset) * abs_height / 100
)
yhi = max_gr + (top_offset + dg_height + cmp_height + datatop_offset) * abs_height / 100
ylo = yhi - abs_height

yhi = kwds.get("yhi", yhi)
Expand Down Expand Up @@ -353,13 +338,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):

# Remove labels above where insets begin
# ax_data.yaxis.set_ticklabels([str(int(loc)) for loc in ax_data.yaxis.get_majorticklocs() if loc < datatop])
ax_data.yaxis.set_ticks(
[
loc
for loc in ax_data.yaxis.get_majorticklocs()
if (loc < datatop and loc >= ylo)
]
)
ax_data.yaxis.set_ticks([loc for loc in ax_data.yaxis.get_majorticklocs() if (loc < datatop and loc >= ylo)])

# Dataset label
if datalabel is not None:
Expand All @@ -378,9 +357,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):

# Create new x axis at bottom edge of compare inset
ax_data.axis["top"].set_visible(False)
ax_data.axis["newtop"] = ax_data.new_floating_axis(
0, datatop, axis_direction="bottom"
) # "top" bugged?
ax_data.axis["newtop"] = ax_data.new_floating_axis(0, datatop, axis_direction="bottom") # "top" bugged?
ax_data.axis["newtop"].toggle(all=False, ticks=True)
ax_data.axis["newtop"].major_ticks.set_tick_out(True)
ax_data.axis["newtop"].minor_ticks.set_tick_out(True)
Expand All @@ -399,9 +376,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
transform=ax_data.transAxes,
)
labeldict[fig] = newylabel # so we can find the correct text object
fig.canvas.mpl_connect(
"draw_event", on_draw
) # original label invisibility and updating
fig.canvas.mpl_connect("draw_event", on_draw) # original label invisibility and updating

# Compare extracted (and ideal, if provided) peak positions clearly.
if cmp_height > 0:
Expand Down Expand Up @@ -610,15 +585,9 @@ def main():
type="int",
help="Plot given model from set. Ignored if srmise_file is not a PeakStability file.",
)
parser.add_option(
"--show", action="store_true", help="execute pylab.show() blocking call"
)
parser.add_option(
"-o", "--output", type="string", help="save plot to the specified file"
)
parser.add_option(
"--format", type="string", default="eps", help="output format for plot saving"
)
parser.add_option("--show", action="store_true", help="execute pylab.show() blocking call")
parser.add_option("-o", "--output", type="string", help="save plot to the specified file")
parser.add_option("--format", type="string", default="eps", help="output format for plot saving")
parser.allow_interspersed_args = True
opts, args = parser.parse_args(sys.argv[1:])

Expand All @@ -636,9 +605,7 @@ def main():
try:
toplot.load(filename)
except Exception:
print(
"File '%s' is not a .srmise or PeakStability data file." % filename
)
print("File '%s' is not a .srmise or PeakStability data file." % filename)
return

if opts.model is not None:
Expand Down
49 changes: 11 additions & 38 deletions diffpy/srmise/basefunction.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,21 +116,12 @@ def __init__(

# Check validity of default_formats
self.default_formats = default_formats
if not (
"default_input" in self.default_formats
and "default_output" in self.default_formats
):
emsg = (
"Argument default_formats must specify 'default_input' "
+ "and 'default_output' as keys."
)
if not ("default_input" in self.default_formats and "default_output" in self.default_formats):
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:
emsg = (
"Keys of argument default_formats must map to a "
+ "value within argument parformats."
)
emsg = "Keys of argument default_formats must map to a " + "value within argument parformats."
raise ValueError()

# Set metadictionary
Expand Down Expand Up @@ -195,10 +186,7 @@ def jacobian(self, p, r, rng=None):
previously calculated values instead.
"""
if self is not p._owner:
emsg = (
"Argument 'p' must be evaluated by the BaseFunction "
+ "subclass which owns it."
)
emsg = "Argument 'p' must be evaluated by the BaseFunction " + "subclass which owns it."
raise ValueError(emsg)

# normally r will be a sequence, but also allow single numeric values
Expand Down Expand Up @@ -241,18 +229,12 @@ def transform_derivatives(self, pars, in_format=None, out_format=None):
out_format = self.default_formats["default_input"]

if not in_format in self.parformats:
raise ValueError(
"Argument 'in_format' must be one of %s." % self.parformats
)
raise ValueError("Argument 'in_format' must be one of %s." % self.parformats)
if not out_format in self.parformats:
raise ValueError(
"Argument 'out_format' must be one of %s." % self.parformats
)
raise ValueError("Argument 'out_format' must be one of %s." % self.parformats)
if in_format == out_format:
return np.identity(self.npars)
return self._transform_derivativesraw(
pars, in_format=in_format, out_format=out_format
)
return self._transform_derivativesraw(pars, in_format=in_format, out_format=out_format)

def transform_parameters(self, pars, in_format=None, out_format=None):
"""Return new sequence with pars converted from in_format to out_format.
Expand Down Expand Up @@ -282,18 +264,12 @@ def transform_parameters(self, pars, in_format=None, out_format=None):
out_format = self.default_formats["default_input"]

if not in_format in self.parformats:
raise ValueError(
"Argument 'in_format' must be one of %s." % self.parformats
)
raise ValueError("Argument 'in_format' must be one of %s." % self.parformats)
if not out_format in self.parformats:
raise ValueError(
"Argument 'out_format' must be one of %s." % self.parformats
)
raise ValueError("Argument 'out_format' must be one of %s." % self.parformats)
# if in_format == out_format:
# return pars
return self._transform_parametersraw(
pars, in_format=in_format, out_format=out_format
)
return self._transform_parametersraw(pars, in_format=in_format, out_format=out_format)

def value(self, p, r, rng=None):
"""Calculate value of ModelPart over r, possibly restricted by range.
Expand All @@ -307,10 +283,7 @@ def value(self, p, r, rng=None):
previously calculated values instead.
"""
if self is not p._owner:
emsg = (
"Argument 'p' must be evaluated by the BaseFunction "
+ "subclass which owns it."
)
emsg = "Argument 'p' must be evaluated by the BaseFunction " + "subclass which owns it."
raise ValueError(emsg)

# normally r will be a sequence, but also allow single numeric values
Expand Down
12 changes: 3 additions & 9 deletions diffpy/srmise/baselines/arbitrary.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,7 @@ def __init__(self, npars, valuef, jacobianf=None, estimatef=None, Cache=None):
metadict["valuef"] = (valuef, repr)
metadict["jacobianf"] = (jacobianf, repr)
metadict["estimatef"] = (estimatef, repr)
BaselineFunction.__init__(
self, parameterdict, formats, default_formats, metadict, None, Cache
)
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache)

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

Expand Down Expand Up @@ -173,17 +171,13 @@ def _transform_parametersraw(self, pars, in_format, out_format):
if in_format == "internal":
pass
else:
raise ValueError(
"Argument 'in_format' must be one of %s." % self.parformats
)
raise ValueError("Argument 'in_format' must be one of %s." % self.parformats)

# Convert to specified output format from "internal" format.
if out_format == "internal":
pass
else:
raise ValueError(
"Argument 'out_format' must be one of %s." % self.parformats
)
raise ValueError("Argument 'out_format' must be one of %s." % self.parformats)
return temp

def _valueraw(self, pars, r):
Expand Down
4 changes: 1 addition & 3 deletions diffpy/srmise/baselines/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,7 @@ def __init__(
additional functionality.
Cache: A class (not instance) which implements caching of BaseFunction
evaluations."""
BaseFunction.__init__(
self, parameterdict, parformats, default_formats, metadict, base, Cache
)
BaseFunction.__init__(self, parameterdict, parformats, default_formats, metadict, base, Cache)

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

Expand Down
Loading

0 comments on commit 5d1dae4

Please sign in to comment.