Skip to content

Commit

Permalink
fix python2 to python3 to make pre-commit black hook work
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenhua0320 committed Jul 29, 2024
1 parent 75e5111 commit 84d79aa
Show file tree
Hide file tree
Showing 16 changed files with 978 additions and 701 deletions.
8 changes: 4 additions & 4 deletions devutils/makesdist
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ sys.path.insert(0, BASEDIR)
from setup import versiondata
timestamp = versiondata.getint('DEFAULT', 'timestamp')

print 'Run "setup.py sdist --formats=tar"',
print('Run "setup.py sdist --formats=tar"',)
cmd_sdist = [sys.executable] + 'setup.py sdist --formats=tar'.split()
ec = subprocess.call(cmd_sdist, cwd=BASEDIR, stdout=open(os.devnull, 'w'))
if ec: sys.exit(ec)
print "[done]"
print("[done]")

tarname = max(glob.glob(BASEDIR + '/dist/*.tar'), key=os.path.getmtime)

Expand All @@ -36,8 +36,8 @@ def fixtarinfo(tinfo):
return tinfo


print 'Filter %s --> %s.gz' % (2 * (os.path.basename(tarname),)),
print('Filter %s --> %s.gz' % (2 * (os.path.basename(tarname),)),)
for ti in tfin:
tfout.addfile(fixtarinfo(ti), tfin.extractfile(ti))
os.remove(tarname)
print "[done]"
print("[done]")
46 changes: 25 additions & 21 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 All @@ -18,20 +20,21 @@ def __init__(self):

def test(self, call, *args, **kwds):
m = sys.modules[call.__module__]
testname = m.__name__+'.'+call.__name__
testname = m.__name__ + "." + call.__name__
path = os.path.dirname(m.__file__)
os.chdir(path)
try:
call(*args, **kwds)
self.messages.append("%s: success" %testname)
except Exception, e:
self.messages.append("%s: error, details below.\n%s" %(testname, e))
self.messages.append("%s: success" % testname)
except Exception as e:
self.messages.append("%s: error, details below.\n%s" % (testname, e))
finally:
os.chdir(__basedir__)

def report(self):
print '==== Results of Tests ===='
print '\n'.join(self.messages)
print("==== Results of Tests ====")
print("\n".join(self.messages))


def scrubeol(directory, filerestr):
"""Use unix-style endlines for files in directory matched by regex string.
Expand All @@ -50,11 +53,11 @@ def scrubeol(directory, filerestr):
text = unicode(original.read())
original.close()

updated = io.open(f, 'w', newline='\n')
updated = io.open(f, "w", newline="\n")
updated.write(text)
updated.close()

print "Updated %s to unix-style endlines." %f
print("Updated %s to unix-style endlines." % f)


def rm(directory, filerestr):
Expand All @@ -72,14 +75,13 @@ def rm(directory, filerestr):
for f in files:
os.remove(f)

print "Deleted %s." %f

print("Deleted %s." % f)


if __name__ == "__main__":

# Temporarily add examples to path
lib_path = os.path.abspath(os.path.join('..','doc','examples'))
lib_path = os.path.abspath(os.path.join("..", "doc", "examples"))
sys.path.append(lib_path)

# Delete existing files that don't necessarily have a fixed name.
Expand All @@ -88,14 +90,16 @@ def rm(directory, filerestr):

### Testing examples
examples = Test()
test_names = ["extract_single_peak",
"parameter_summary",
"fit_initial",
"query_results",
"multimodel_known_dG1",
"multimodel_known_dG2",
"multimodel_unknown_dG1",
"multimodel_unknown_dG2"]
test_names = [
"extract_single_peak",
"parameter_summary",
"fit_initial",
"query_results",
"multimodel_known_dG1",
"multimodel_known_dG2",
"multimodel_unknown_dG1",
"multimodel_unknown_dG2",
]

test_modules = []
for test in test_names:
Expand All @@ -107,7 +111,7 @@ def rm(directory, filerestr):
examples.report()

### Convert output of example files to Unix-style endlines for sdist.
if os.linesep != '\n':
print "==== Scrubbing Endlines ===="
if os.linesep != "\n":
print("==== Scrubbing Endlines ====")
# All *.srmise and *.pwa files in examples directory.
scrubeol("../doc/examples/output", r".*(\.srmise|\.pwa)")
56 changes: 31 additions & 25 deletions diffpy/srmise/baselines/arbitrary.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@
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

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

class Arbitrary (BaselineFunction):

class Arbitrary(BaselineFunction):
"""Methods for evaluating a baseline from an arbitrary function.
Supports baseline calculations with arbitrary functions. These functions,
Expand Down Expand Up @@ -64,10 +66,10 @@ def __init__(self, npars, valuef, jacobianf=None, estimatef=None, Cache=None):
# Define parameterdict
# e.g. {"a_0":0, "a_1":1, "a_2":2, "a_3":3} if npars is 4.
parameterdict = {}
for d in range(self.testnpars+1):
parameterdict["a_"+str(d)] = d
formats = ['internal']
default_formats = {'default_input':'internal', 'default_output':'internal'}
for d in range(self.testnpars + 1):
parameterdict["a_" + str(d)] = d
formats = ["internal"]
default_formats = {"default_input": "internal", "default_output": "internal"}

# Check that the provided functions are at least callable
if valuef is None or callable(valuef):
Expand All @@ -93,7 +95,9 @@ 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 All @@ -114,9 +118,8 @@ def estimate_parameters(self, r, y):
# TODO: check that estimatef returns something proper?
try:
return self.estimatef(r, y)
except Exception, e:
emsg = "Error within estimation routine provided to Arbitrary:\n"+\
str(e)
except Exception as e:
emsg = "Error within estimation routine provided to Arbitrary:\n" + str(e)
raise SrMiseEstimationError(emsg)

def _jacobianraw(self, pars, r, free):
Expand All @@ -137,10 +140,10 @@ def _jacobianraw(self, pars, r, free):
emsg = "No jacobian routine provided to Arbitrary."
raise NotImplementedError(emsg)
if len(pars) != self.npars:
emsg = "Argument pars must have "+str(self.npars)+" elements."
emsg = "Argument pars must have " + str(self.npars) + " elements."
raise ValueError(emsg)
if len(free) != self.npars:
emsg = "Argument free must have "+str(self.npars)+" elements."
emsg = "Argument free must have " + str(self.npars) + " elements."
raise ValueError(emsg)

# Allow an arbitrary function without a Jacobian provided act as
Expand All @@ -149,7 +152,7 @@ def _jacobianraw(self, pars, r, free):
# large performance implications if all other functions used while
# fitting a function define a Jacobian.
if nfree == 0:
return [None for p in range(len(par))]
return [None for p in range(len(pars))]

# TODO: check that jacobianf returns something proper?
return self.jacobianf(pars, r, free)
Expand All @@ -170,15 +173,17 @@ 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 All @@ -192,7 +197,7 @@ def _valueraw(self, pars, r):
...
r: sequence or scalar over which pars is evaluated"""
if len(pars) != self.npars:
emsg = "Argument pars must have "+str(self.npars)+" elements."
emsg = "Argument pars must have " + str(self.npars) + " elements."
raise ValueError(emsg)

# TODO: check that valuef returns something proper?
Expand All @@ -201,21 +206,22 @@ def _valueraw(self, pars, r):
def getmodule(self):
return __name__

#end of class Polynomial

# end of class Polynomial

# simple test code
if __name__ == '__main__':
if __name__ == "__main__":

f = Polynomial(degree = 3)
f = Polynomial(degree=3)
r = np.arange(5)
pars = np.array([3, 0, 1, 2])
free = np.array([True, False, True, True])
print f._valueraw(pars, r)
print f._jacobianraw(pars, r, free)
print(f._valueraw(pars, r))
print(f._jacobianraw(pars, r, free))

f = Polynomial(degree = -1)
f = Polynomial(degree=-1)
r = np.arange(5)
pars = np.array([])
free = np.array([])
print f._valueraw(pars, r)
print f._jacobianraw(pars, r, free)
print(f._valueraw(pars, r))
print(f._jacobianraw(pars, r, free))
1 change: 1 addition & 0 deletions diffpy/srmise/baselines/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import diffpy.srmise.srmiselog
from diffpy.srmise.basefunction import BaseFunction
from diffpy.srmise.modelparts import ModelPart
from diffpy.srmise.peaks import Peaks
from diffpy.srmise.srmiseerrors import *

logger = logging.getLogger("diffpy.srmise")
Expand Down
Loading

0 comments on commit 84d79aa

Please sign in to comment.