diff --git a/conda-recipe/run_test.py b/conda-recipe/run_test.py index d39487ff..0edfe0c3 100644 --- a/conda-recipe/run_test.py +++ b/conda-recipe/run_test.py @@ -1,4 +1,5 @@ #!/usr/bin/env python import diffpy.srreal.tests + assert diffpy.srreal.tests.test().wasSuccessful() diff --git a/devutils/tunePeakPrecision.py b/devutils/tunePeakPrecision.py index 60c76f45..e46c9616 100755 --- a/devutils/tunePeakPrecision.py +++ b/devutils/tunePeakPrecision.py @@ -30,11 +30,12 @@ from diffpy.structure import Structure from diffpy.srreal.pdf_ext import PDFCalculator import diffpy.pdffit2 + # make PdfFit silent -diffpy.pdffit2.redirect_stdout(open('/dev/null', 'w')) +diffpy.pdffit2.redirect_stdout(open("/dev/null", "w")) # define nickel structure data -nickel_discus_data = ''' +nickel_discus_data = """ title Ni spcgr P1 cell 3.523870, 3.523870, 3.523870, 90.000000, 90.000000, 90.000000 @@ -44,10 +45,10 @@ NI 0.00000000 0.50000000 0.50000000 0.1000 NI 0.50000000 0.00000000 0.50000000 0.1000 NI 0.50000000 0.50000000 0.00000000 0.1000 -''' +""" nickel = Structure() -nickel.readStr(nickel_discus_data, format='discus') +nickel.readStr(nickel_discus_data, format="discus") def Gpdffit2(qmax): @@ -59,7 +60,7 @@ def Gpdffit2(qmax): """ # calculate reference data using pdffit2 pf2 = diffpy.pdffit2.PdfFit() - pf2.alloc('X', qmax, 0.0, rmin, rmax, int((rmax - rmin) / rstep + 1)) + pf2.alloc("X", qmax, 0.0, rmin, rmax, int((rmax - rmin) / rstep + 1)) pf2.add_structure(nickel) pf2.calc() rg = numpy.array((pf2.getR(), pf2.getpdf_fit())) @@ -81,7 +82,7 @@ def Gsrreal(qmax, peakprecision=None): pdfcalc._setDoubleAttr("rmax", rmax + rstep * 1e-4) pdfcalc._setDoubleAttr("rstep", rstep) if peakprecision is not None: - pdfcalc._setDoubleAttr('peakprecision', peakprecision) + pdfcalc._setDoubleAttr("peakprecision", peakprecision) pdfcalc.eval(nickel) rg = numpy.array([pdfcalc.rgrid, pdfcalc.pdf]) return rg @@ -105,30 +106,31 @@ def comparePDFCalculators(qmax, peakprecision=None): t0, t1 -- CPU times used by pdffit2 and PDFCalculator calls """ rv = {} - rv['qmax'] = qmax - rv['peakprecision'] = (peakprecision is None and - PDFCalculator()._getDoubleAttr('peakprecision') or peakprecision) + rv["qmax"] = qmax + rv["peakprecision"] = ( + peakprecision is None and PDFCalculator()._getDoubleAttr("peakprecision") or peakprecision + ) ttic = time.clock() rg0 = Gpdffit2(qmax) ttoc = time.clock() - rv['r'] = rg0[0] - rv['g0'] = rg0[1] - rv['t0'] = ttoc - ttic + rv["r"] = rg0[0] + rv["g0"] = rg0[1] + rv["t0"] = ttoc - ttic ttic = time.clock() rg1 = Gsrreal(qmax, peakprecision) ttoc = time.clock() - assert numpy.all(rv['r'] == rg1[0]) - rv['g1'] = rg1[1] - rv['t1'] = ttoc - ttic - rv['gdiff'] = rv['g0'] - rv['g1'] - rv['grmsd'] = numpy.sqrt(numpy.mean(rv['gdiff']**2)) + assert numpy.all(rv["r"] == rg1[0]) + rv["g1"] = rg1[1] + rv["t1"] = ttoc - ttic + rv["gdiff"] = rv["g0"] - rv["g1"] + rv["grmsd"] = numpy.sqrt(numpy.mean(rv["gdiff"] ** 2)) return rv def processCommandLineArguments(): global qmax, peakprecision, createplot argc = len(sys.argv) - if set(['-h', '--help']).intersection(sys.argv): + if set(["-h", "--help"]).intersection(sys.argv): print(__doc__) sys.exit() if argc > 1: @@ -136,7 +138,7 @@ def processCommandLineArguments(): if argc > 2: peakprecision = float(sys.argv[2]) if argc > 3: - createplot = sys.argv[3].lower() in ('y', 'yes', '1', 'true') + createplot = sys.argv[3].lower() in ("y", "yes", "1", "true") return @@ -148,22 +150,23 @@ def plotComparison(cmpdata): No return value. """ import pylab + pylab.clf() pylab.subplot(211) - pylab.title('qmax=%(qmax)g peakprecision=%(peakprecision)g' % cmpdata) - pylab.ylabel('G') - r = cmpdata['r'] - g0 = cmpdata['g0'] - g1 = cmpdata['g1'] - gdiff = cmpdata['gdiff'] + pylab.title("qmax=%(qmax)g peakprecision=%(peakprecision)g" % cmpdata) + pylab.ylabel("G") + r = cmpdata["r"] + g0 = cmpdata["g0"] + g1 = cmpdata["g1"] + gdiff = cmpdata["gdiff"] pylab.plot(r, g0, r, g1) pylab.subplot(212) - pylab.plot(r, gdiff, 'r') + pylab.plot(r, gdiff, "r") slope = numpy.sum(r * gdiff) / numpy.sum(r**2) - pylab.plot(r, slope * r, '--') - pylab.xlabel('r') - pylab.ylabel('Gdiff') - pylab.title('slope = %g' % slope) + pylab.plot(r, slope * r, "--") + pylab.xlabel("r") + pylab.ylabel("Gdiff") + pylab.title("slope = %g" % slope) pylab.draw() return @@ -171,14 +174,17 @@ def plotComparison(cmpdata): def main(): processCommandLineArguments() cmpdata = comparePDFCalculators(qmax, peakprecision) - print(("qmax = %(qmax)g pkprec = %(peakprecision)g " + - "grmsd = %(grmsd)g t0 = %(t0).3f t1 = %(t1).3f") % cmpdata) + print( + ("qmax = %(qmax)g pkprec = %(peakprecision)g " + "grmsd = %(grmsd)g t0 = %(t0).3f t1 = %(t1).3f") + % cmpdata + ) if createplot: plotComparison(cmpdata) import pylab + pylab.show() return -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/doc/manual/source/conf.py b/doc/manual/source/conf.py index 5d2c4878..307ec098 100644 --- a/doc/manual/source/conf.py +++ b/doc/manual/source/conf.py @@ -19,11 +19,11 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) -sys.path.insert(0, os.path.abspath('../../..')) +# sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath("../../..")) # abbreviations -ab_authors = u'Pavol Juhás, Christopher L. Farrow, Simon J.L. Billinge group' +ab_authors = "Pavol Juhás, Christopher L. Farrow, Simon J.L. Billinge group" # -- General configuration ----------------------------------------------------- @@ -33,38 +33,39 @@ # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.coverage', - 'sphinx.ext.napoleon', - 'sphinx.ext.intersphinx', - 'm2r', + "sphinx.ext.autodoc", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.intersphinx", + "m2r", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # -source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'diffpy.srreal' -copyright = '%Y, Brookhaven National Laboratory' +project = "diffpy.srreal" +copyright = "%Y, Brookhaven National Laboratory" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. from setup import versiondata -fullversion = versiondata.get('DEFAULT', 'version') + +fullversion = versiondata.get("DEFAULT", "version") # The short X.Y version. -version = ''.join(fullversion.split('.post')[:1]) +version = "".join(fullversion.split(".post")[:1]) # The full version, including alpha/beta/rc tags. release = fullversion @@ -75,13 +76,13 @@ # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' -today_seconds = versiondata.getint('DEFAULT', 'timestamp') -today = time.strftime('%B %d, %Y', time.localtime(today_seconds)) +today_seconds = versiondata.getint("DEFAULT", "timestamp") +today = time.strftime("%B %d, %Y", time.localtime(today_seconds)) year = today.split()[-1] # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # substitute YEAR in the copyright string -copyright = copyright.replace('%Y', year) +copyright = copyright.replace("%Y", year) # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -102,10 +103,10 @@ # show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -modindex_common_prefix = ['diffpy.srreal'] +modindex_common_prefix = ["diffpy.srreal"] # Display all warnings for missing links. nitpicky = True @@ -114,14 +115,14 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'sphinx_py3doc_enhanced_theme' +html_theme = "sphinx_py3doc_enhanced_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { - 'collapsiblesidebar' : 'true', - 'navigation_with_keys' : 'true', + "collapsiblesidebar": "true", + "navigation_with_keys": "true", } # Add any paths that contain custom themes here, relative to this directory. @@ -190,27 +191,24 @@ # html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'srrealdoc' +htmlhelp_basename = "srrealdoc" # -- Options for LaTeX output -------------------------------------------------- latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -# 'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -# 'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -# 'preamble': '', + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'diffpy.srreal.tex', 'diffpy.srreal Documentation', - ab_authors, 'manual'), + ("index", "diffpy.srreal.tex", "diffpy.srreal Documentation", ab_authors, "manual"), ] # The name of an image file (relative to this directory) to place at the top of @@ -238,10 +236,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'diffpy.srreal', 'diffpy.srreal Documentation', - ab_authors, 1) -] +man_pages = [("index", "diffpy.srreal", "diffpy.srreal Documentation", ab_authors, 1)] # If true, show URL addresses after external links. # man_show_urls = False @@ -253,9 +248,15 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'diffpy.srreal', 'diffpy.srreal Documentation', - ab_authors, 'diffpy.srreal', 'One line description of project.', - 'Miscellaneous'), + ( + "index", + "diffpy.srreal", + "diffpy.srreal Documentation", + ab_authors, + "diffpy.srreal", + "One line description of project.", + "Miscellaneous", + ), ] # Documents to append as an appendix to all manuals. @@ -270,6 +271,6 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - 'numpy': ('https://docs.scipy.org/doc/numpy', None), - 'python' : ('https://docs.python.org/3.7', None), + "numpy": ("https://docs.scipy.org/doc/numpy", None), + "python": ("https://docs.python.org/3.7", None), } diff --git a/examples/compareC60PDFs.py b/examples/compareC60PDFs.py index 622c350c..03311ec1 100755 --- a/examples/compareC60PDFs.py +++ b/examples/compareC60PDFs.py @@ -11,13 +11,14 @@ from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator mydir = os.path.dirname(os.path.abspath(sys.argv[0])) -buckyfile = os.path.join(mydir, 'datafiles', 'C60bucky.stru') +buckyfile = os.path.join(mydir, "datafiles", "C60bucky.stru") # load C60 molecule as a diffpy.structure object bucky = Structure(filename=buckyfile) -cfg = { 'qmax' : 25, - 'rmin' : 0, - 'rmax' : 10.001, +cfg = { + "qmax": 25, + "rmin": 0, + "rmax": 10.001, } # calculate PDF by real-space summation diff --git a/examples/compareC60PDFs_objcryst.py b/examples/compareC60PDFs_objcryst.py index 35f3a293..69c9143a 100755 --- a/examples/compareC60PDFs_objcryst.py +++ b/examples/compareC60PDFs_objcryst.py @@ -12,10 +12,10 @@ from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator # load C60 molecule as a diffpy.structure object -bucky_diffpy = Structure(filename='datafiles/C60bucky.stru') +bucky_diffpy = Structure(filename="datafiles/C60bucky.stru") # convert to an ObjCryst molecule -c60 = Crystal(1, 1, 1, 'P1') +c60 = Crystal(1, 1, 1, "P1") mc60 = Molecule(c60, "C60") c60.AddScatterer(mc60) # Create the scattering power object for the carbon atoms @@ -26,10 +26,11 @@ mc60.AddAtom(a.xyz_cartn[0], a.xyz_cartn[1], a.xyz_cartn[2], sp, cname) # PDF configuration -cfg = { 'qmax' : 25, - 'rmin' : 0, - 'rmax' : 10.001, - 'rstep' : 0.05, +cfg = { + "qmax": 25, + "rmin": 0, + "rmax": 10.001, + "rstep": 0.05, } # calculate PDF by real-space summation diff --git a/examples/distanceprinter.py b/examples/distanceprinter.py index 45ae0e65..c28409b0 100755 --- a/examples/distanceprinter.py +++ b/examples/distanceprinter.py @@ -7,25 +7,25 @@ from diffpy.srreal.pairquantity import PairQuantity from diffpy.structure import Structure -class DistancePrinter(PairQuantity): - '''This PairQuantity class simply prints the visited pair distances +class DistancePrinter(PairQuantity): + """This PairQuantity class simply prints the visited pair distances and the indices of the contributing atoms. - ''' + """ def _resetValue(self): self.count = 0 def _addPairContribution(self, bnds, sumscale): self.count += bnds.multiplicity() * sumscale / 2.0 - print("%i %g %i %i" % ( - self.count, bnds.distance(), bnds.site0(), bnds.site1())) + print("%i %g %i %i" % (self.count, bnds.distance(), bnds.site0(), bnds.site1())) return + # class DistancePrinter # define nickel structure data -nickel_discus_data = ''' +nickel_discus_data = """ title Ni spcgr P1 cell 3.523870, 3.523870, 3.523870, 90.000000, 90.000000, 90.000000 @@ -35,47 +35,53 @@ def _addPairContribution(self, bnds, sumscale): NI 0.00000000 0.50000000 0.50000000 0.1000 NI 0.50000000 0.00000000 0.50000000 0.1000 NI 0.50000000 0.50000000 0.00000000 0.1000 -''' +""" nickel = Structure() -nickel.readStr(nickel_discus_data, format='discus') +nickel.readStr(nickel_discus_data, format="discus") -bucky = Structure(filename='datafiles/C60bucky.stru', format='discus') +bucky = Structure(filename="datafiles/C60bucky.stru", format="discus") distprint = DistancePrinter() -distprint._setDoubleAttr('rmax', 10) +distprint._setDoubleAttr("rmax", 10) + def get_pyobjcryst_sphalerite(): from pyobjcryst import loadCrystal - crst = loadCrystal('datafiles/sphalerite.cif') + + crst = loadCrystal("datafiles/sphalerite.cif") return crst + def main(): - s = input('Enter rmin: ') - if s.strip(): distprint.rmin = float(s) + s = input("Enter rmin: ") + if s.strip(): + distprint.rmin = float(s) print("rmin = %g" % distprint.rmin) - s = input('Enter rmax: ') - if s.strip(): distprint.rmax = float(s) + s = input("Enter rmax: ") + if s.strip(): + distprint.rmax = float(s) print("rmax = %g" % distprint.rmax) print() - linesep = 78 * '-' + linesep = 78 * "-" # C60bucky print(linesep) - input('Press enter for distances in C60 molecule.') + input("Press enter for distances in C60 molecule.") distprint.eval(bucky) # nickel print(linesep) - input('Press enter for distances in a nickel crystal.') + input("Press enter for distances in a nickel crystal.") distprint.eval(nickel) # objcryst sphalerite print(linesep) - input('Press enter for distances in objcryst loaded sphalerite.cif.') + input("Press enter for distances in objcryst loaded sphalerite.cif.") crst = get_pyobjcryst_sphalerite() distprint.eval(crst) print(linesep) - input('Press enter for distances in diffpy.structure sphalerite.cif.') - crst = Structure(filename='datafiles/sphalerite.cif') + input("Press enter for distances in diffpy.structure sphalerite.cif.") + crst = Structure(filename="datafiles/sphalerite.cif") distprint.eval(crst) return -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/examples/lennardjones/ljcalculator.py b/examples/lennardjones/ljcalculator.py index eebd7740..e4a43f29 100755 --- a/examples/lennardjones/ljcalculator.py +++ b/examples/lennardjones/ljcalculator.py @@ -10,6 +10,7 @@ from diffpy.srreal.pairquantity import PairQuantity from diffpy.structure import Structure + class LennardJonesCalculator(PairQuantity): # Initialization. The size of the result array is always 1. @@ -18,16 +19,13 @@ def __init__(self): self._resizeValue(1) return - def __call__(self, structure): - '''Return LJ potential for a specified structure - ''' + """Return LJ potential for a specified structure""" values = self.eval(structure) return values[0] - def _addPairContribution(self, bnds, sumscale): - '''Add Lennard-Jones contribution from a single pair of atoms. + """Add Lennard-Jones contribution from a single pair of atoms. bnds -- a BaseBondGenerator instance that contains information about the current pair of atom sites. @@ -35,12 +33,13 @@ def _addPairContribution(self, bnds, sumscale): be negative in case of fast value updates. No return value. Updates _value, the internal results array. - ''' + """ rij = bnds.distance() - ljij = 4 * (rij ** -12 - rij ** -6) + ljij = 4 * (rij**-12 - rij**-6) self._value[0] += sumscale * ljij / 2.0 return + # class LennardJonesCalculator @@ -55,5 +54,5 @@ def main(): print("LJ potential of %s is %g" % (filename, ljcalc(stru))) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/examples/parallelPDF.py b/examples/parallelPDF.py index 9040b28d..89a62f37 100755 --- a/examples/parallelPDF.py +++ b/examples/parallelPDF.py @@ -16,14 +16,12 @@ from diffpy.srreal.parallel import createParallelCalculator mydir = os.path.dirname(os.path.abspath(__file__)) -mentholcif = os.path.join(mydir, 'datafiles', 'menthol.cif') +mentholcif = os.path.join(mydir, "datafiles", "menthol.cif") Uisodefault = 0.005 # configure options parsing -parser = optparse.OptionParser("%prog [options]\n" + - __doc__) -parser.add_option("--pyobjcryst", action="store_true", - help="Use pyobjcryst to load the CIF file.") +parser = optparse.OptionParser("%prog [options]\n" + __doc__) +parser.add_option("--pyobjcryst", action="store_true", help="Use pyobjcryst to load the CIF file.") parser.allow_interspersed_args = True opts, args = parser.parse_args(sys.argv[1:]) @@ -32,6 +30,7 @@ # use pyobjcryst if requested by the user from pyobjcryst import loadCrystal from numpy import pi + menthol = loadCrystal(mentholcif) for sc in menthol.GetScatteringComponentList(): sp = sc.mpScattPow @@ -43,9 +42,10 @@ a.Uisoequiv = a.Uisoequiv or Uisodefault # configuration of a PDF calculator -cfg = { 'qmax' : 25, - 'rmin' : 0, - 'rmax' : 30, +cfg = { + "qmax": 25, + "rmin": 0, + "rmax": 30, } # number of CPUs for parallel calculation @@ -72,6 +72,7 @@ # plot both results and the difference curve from matplotlib.pyplot import plot, show, clf + clf() gd = g0 - g1 plot(r0, g0, r1, g1, r0, gd - 3) diff --git a/setup.py b/setup.py index 6bb68e4e..5611ed7f 100644 --- a/setup.py +++ b/setup.py @@ -26,27 +26,25 @@ def get_boost_libraries(): ext_kws = { - 'libraries' : ["diffpy"] + get_boost_libraries(), - 'extra_compile_args' : ["-std=c++11"], - 'extra_link_args' : [], - 'include_dirs' : [numpy.get_include()], + "libraries": ["diffpy"] + get_boost_libraries(), + "extra_compile_args": ["-std=c++11"], + "extra_link_args": [], + "include_dirs": [numpy.get_include()], } def create_extensions(): "Initialize Extension objects for the setup function." - ext = Extension('diffpy.srreal.srreal_ext', - glob.glob('src/extensions/*.cpp'), - **ext_kws) + ext = Extension("diffpy.srreal.srreal_ext", glob.glob("src/extensions/*.cpp"), **ext_kws) return [ext] # Extensions not included in pyproject.toml setup_args = dict( - ext_modules = [], + ext_modules=[], ) -if __name__ == '__main__': - setup_args['ext_modules'] = create_extensions() +if __name__ == "__main__": + setup_args["ext_modules"] = create_extensions() setup(**setup_args) diff --git a/src/diffpy/__init__.py b/src/diffpy/__init__.py index 93b57f65..bb399140 100644 --- a/src/diffpy/__init__.py +++ b/src/diffpy/__init__.py @@ -20,6 +20,7 @@ from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) diff --git a/src/diffpy/srreal/_cleanup.py b/src/diffpy/srreal/_cleanup.py index dbb41b13..1e7cc517 100644 --- a/src/diffpy/srreal/_cleanup.py +++ b/src/diffpy/srreal/_cleanup.py @@ -33,6 +33,7 @@ class prototypes is implemented in libdiffpy. Any Python-extended classes # Routine to be used from srreal_ext module ---------------------------------- + def registerForCleanUp(obj): """Remember to clean up the specified prototype at Python exit. @@ -48,21 +49,21 @@ def registerForCleanUp(obj): _cleanup_handler.add(obj) return + # ---------------------------------------------------------------------------- + class _DerivedClassesCleanUpHandler(object): def __init__(self): self._references = set() return - def add(self, obj): wr = weakref.ref(obj) self._references.add(wr) return - def clean(self): while self._references: wr = self._references.pop() @@ -71,6 +72,7 @@ def clean(self): obj._deregisterType(obj.type()) return + # end of class _DerivedClassesCleanUpHandler diff --git a/src/diffpy/srreal/_docstrings.py b/src/diffpy/srreal/_docstrings.py index cbb1a6d6..fee8ab07 100644 --- a/src/diffpy/srreal/_docstrings.py +++ b/src/diffpy/srreal/_docstrings.py @@ -19,6 +19,7 @@ # Shared docstrings for classes derived from HasClassRegistry ---------------- + def get_registry_docstrings(cls): """Build a dictionary of docstrings per each HasClassRegistry method. @@ -31,18 +32,21 @@ def get_registry_docstrings(cls): Returns a dictionary mapping Python method names to their docstrins. """ n = cls.__name__ - rv = {k : v.replace('@NAME@', n) for k, v in ( - ("create", doc_HasClassRegistry_create), - ("clone", doc_HasClassRegistry_clone), - ("type", doc_HasClassRegistry_type), - ("_registerThisType", doc_HasClassRegistry__registerThisType), - ("_aliasType", doc_HasClassRegistry__aliasType), - ("_deregisterType", doc_HasClassRegistry__deregisterType), - ("createByType", doc_HasClassRegistry_createByType), - ("isRegisteredType", doc_HasClassRegistry_isRegisteredType), - ("getAliasedTypes", doc_HasClassRegistry_getAliasedTypes), - ("getRegisteredTypes", doc_HasClassRegistry_getRegisteredTypes), - )} + rv = { + k: v.replace("@NAME@", n) + for k, v in ( + ("create", doc_HasClassRegistry_create), + ("clone", doc_HasClassRegistry_clone), + ("type", doc_HasClassRegistry_type), + ("_registerThisType", doc_HasClassRegistry__registerThisType), + ("_aliasType", doc_HasClassRegistry__aliasType), + ("_deregisterType", doc_HasClassRegistry__deregisterType), + ("createByType", doc_HasClassRegistry_createByType), + ("isRegisteredType", doc_HasClassRegistry_isRegisteredType), + ("getAliasedTypes", doc_HasClassRegistry_getAliasedTypes), + ("getRegisteredTypes", doc_HasClassRegistry_getRegisteredTypes), + ) + } return rv diff --git a/src/diffpy/srreal/_final_imports.py b/src/diffpy/srreal/_final_imports.py index 9e75dfae..236eaf57 100644 --- a/src/diffpy/srreal/_final_imports.py +++ b/src/diffpy/srreal/_final_imports.py @@ -27,26 +27,28 @@ def import_now(): - ''' + """ Import all Python modules that tweak extension-defined classes. - ''' + """ global _import_now_called if _import_now_called: return _import_now_called = True from importlib import import_module - import_module('diffpy.srreal.attributes') - import_module('diffpy.srreal.atomradiitable') - import_module('diffpy.srreal.bondcalculator') - import_module('diffpy.srreal.bvscalculator') - import_module('diffpy.srreal.overlapcalculator') - import_module('diffpy.srreal.pdfbaseline') - import_module('diffpy.srreal.pdfenvelope') - import_module('diffpy.srreal.peakprofile') - import_module('diffpy.srreal.peakwidthmodel') - import_module('diffpy.srreal.scatteringfactortable') - import_module('diffpy.srreal.pdfcalculator') - import_module('diffpy.srreal.structureconverters') + + import_module("diffpy.srreal.attributes") + import_module("diffpy.srreal.atomradiitable") + import_module("diffpy.srreal.bondcalculator") + import_module("diffpy.srreal.bvscalculator") + import_module("diffpy.srreal.overlapcalculator") + import_module("diffpy.srreal.pdfbaseline") + import_module("diffpy.srreal.pdfenvelope") + import_module("diffpy.srreal.peakprofile") + import_module("diffpy.srreal.peakwidthmodel") + import_module("diffpy.srreal.scatteringfactortable") + import_module("diffpy.srreal.pdfcalculator") + import_module("diffpy.srreal.structureconverters") return + _import_now_called = False diff --git a/src/diffpy/srreal/_version_data.py b/src/diffpy/srreal/_version_data.py index a0e532b6..8c1a4f46 100644 --- a/src/diffpy/srreal/_version_data.py +++ b/src/diffpy/srreal/_version_data.py @@ -19,7 +19,7 @@ Does not import any extension module unlike the `version` module. """ -__all__ = ['__date__', '__git_commit__', '__timestamp__', '__version__'] +__all__ = ["__date__", "__git_commit__", "__timestamp__", "__version__"] import os.path @@ -27,22 +27,22 @@ # obtain version information from the version.cfg file -cp = dict(version='', date='', commit='', timestamp='0') -fcfg = resource_filename(__name__, 'version.cfg') -if not os.path.isfile(fcfg): # pragma: no cover +cp = dict(version="", date="", commit="", timestamp="0") +fcfg = resource_filename(__name__, "version.cfg") +if not os.path.isfile(fcfg): # pragma: no cover from warnings import warn + warn('Package metadata not found, execute "./setup.py egg_info".') fcfg = os.devnull with open(fcfg) as fp: - kwords = [[w.strip() for w in line.split(' = ', 1)] - for line in fp if line[:1].isalpha() and ' = ' in line] + kwords = [[w.strip() for w in line.split(" = ", 1)] for line in fp if line[:1].isalpha() and " = " in line] assert all(w[0] in cp for w in kwords), "received unrecognized keyword" cp.update(kwords) -__version__ = cp['version'] -__date__ = cp['date'] -__git_commit__ = cp['commit'] -__timestamp__ = int(cp['timestamp']) +__version__ = cp["version"] +__date__ = cp["date"] +__git_commit__ = cp["commit"] +__timestamp__ = int(cp["timestamp"]) # TODO remove deprecated __gitsha__ in version 1.4. __gitsha__ = __git_commit__ diff --git a/src/diffpy/srreal/atomradiitable.py b/src/diffpy/srreal/atomradiitable.py index 4a141961..fe5016aa 100644 --- a/src/diffpy/srreal/atomradiitable.py +++ b/src/diffpy/srreal/atomradiitable.py @@ -18,29 +18,31 @@ # exported items, these also makes them show in pydoc. -__all__ = ['AtomRadiiTable', 'ConstantRadiiTable', 'CovalentRadiiTable'] +__all__ = ["AtomRadiiTable", "ConstantRadiiTable", "CovalentRadiiTable"] from diffpy.srreal.srreal_ext import AtomRadiiTable, ConstantRadiiTable # class CovalentRadiiTable --------------------------------------------------- + class CovalentRadiiTable(AtomRadiiTable): - '''Covalent radii from Cordero et al., 2008, doi:10.1039/b801115j. + """Covalent radii from Cordero et al., 2008, doi:10.1039/b801115j. Instantiation of this class requires the periodictable module. - ''' + """ # class variable that holds the periodictable.elements object _elements = None def _standardLookup(self, smbl): - '''Return covalent atom radius in Angstroms. + """Return covalent atom radius in Angstroms. smbl -- string symbol of an element Return float. Raise ValueError for unknown element symbol. - ''' + """ if CovalentRadiiTable._elements is None: from periodictable import elements + CovalentRadiiTable._elements = elements e = self._elements.isotope(smbl) rv = e.covalent_radius @@ -52,27 +54,25 @@ def _standardLookup(self, smbl): # HasClassRegistry overloads: def create(self): - '''Create new instance of the CovalentRadiiTable. - ''' + """Create new instance of the CovalentRadiiTable.""" return CovalentRadiiTable() - def clone(self): - '''Return a new duplicate instance of self. - ''' + """Return a new duplicate instance of self.""" import copy - return copy.copy(self) + return copy.copy(self) def type(self): - '''Unique string identifier of the CovalentRadiiTable type. + """Unique string identifier of the CovalentRadiiTable type. This is used for class registration and as an argument for the createByType function. Return string. - ''' + """ return "covalent" + # End of class CovalentRadiiTable CovalentRadiiTable()._registerThisType() diff --git a/src/diffpy/srreal/attributes.py b/src/diffpy/srreal/attributes.py index cb843738..ad0452d6 100644 --- a/src/diffpy/srreal/attributes.py +++ b/src/diffpy/srreal/attributes.py @@ -17,26 +17,27 @@ A base to PairQuantity and quite a few other classes. """ -__all__ = ['Attributes'] +__all__ = ["Attributes"] from diffpy.srreal.srreal_ext import Attributes # Inject the __getattr__ and __setattr__ methods to the Attributes class + def _getattr(self, name): - '''Lookup a C++ double attribute if standard Python lookup fails. + """Lookup a C++ double attribute if standard Python lookup fails. Raise AttributeError if C++ double attribute does not exist. - ''' + """ rv = self._getDoubleAttr(name) return rv + Attributes.__getattr__ = _getattr def _setattr(self, name, value): - '''Assign to C++ double attribute if Python attribute does not exist. - ''' + """Assign to C++ double attribute if Python attribute does not exist.""" try: object.__getattribute__(self, name) except AttributeError: @@ -46,16 +47,20 @@ def _setattr(self, name, value): object.__setattr__(self, name, value) return + Attributes.__setattr__ = _setattr # Helper accessor functions used by the _registerDoubleAttribute method + def _pyattrgetter(name): f = lambda obj: object.__getattribute__(obj, name) return f + def _pyattrsetter(name): f = lambda obj, value: object.__setattr__(obj, name, value) return f + # End of file diff --git a/src/diffpy/srreal/bondcalculator.py b/src/diffpy/srreal/bondcalculator.py index ac89ebee..d7f410cd 100644 --- a/src/diffpy/srreal/bondcalculator.py +++ b/src/diffpy/srreal/bondcalculator.py @@ -18,7 +18,7 @@ # exported items, these also makes them show in pydoc. -__all__ = ['BondCalculator'] +__all__ = ["BondCalculator"] from diffpy.srreal.wraputils import propertyFromExtDoubleAttr from diffpy.srreal.wraputils import setattrFromKeywordArguments @@ -26,40 +26,45 @@ # property wrappers to C++ double attributes -BondCalculator.rmin = propertyFromExtDoubleAttr('rmin', - '''Lower bound for the bond distances. - [0 A]''') +BondCalculator.rmin = propertyFromExtDoubleAttr( + "rmin", + """Lower bound for the bond distances. + [0 A]""", +) -BondCalculator.rmax = propertyFromExtDoubleAttr('rmax', - '''Upper bound for the bond distances. - [5 A]''') +BondCalculator.rmax = propertyFromExtDoubleAttr( + "rmax", + """Upper bound for the bond distances. + [5 A]""", +) # method overrides that support keyword arguments + def _init_kwargs(self, **kwargs): - '''Create a new instance of BondCalculator. + """Create a new instance of BondCalculator. Keyword arguments can be used to configure calculator properties, for example: bdc = BondCalculator(rmin=1.5, rmax=2.5) Raise ValueError for invalid keyword argument. - ''' + """ BondCalculator.__boostpython__init(self) setattrFromKeywordArguments(self, **kwargs) return def _call_kwargs(self, structure=None, **kwargs): - '''Return sorted bond distances in the specified structure. + """Return sorted bond distances in the specified structure. structure -- structure to be evaluated, an instance of diffpy Structure or pyobjcryst Crystal. Reuse the last structure when None. kwargs -- optional parameter settings for this calculator Return a sorted numpy array. - ''' + """ setattrFromKeywordArguments(self, **kwargs) self.eval(structure) return self.distances diff --git a/src/diffpy/srreal/bvparameterstable.py b/src/diffpy/srreal/bvparameterstable.py index 1363226e..9d963fca 100644 --- a/src/diffpy/srreal/bvparameterstable.py +++ b/src/diffpy/srreal/bvparameterstable.py @@ -19,7 +19,7 @@ class BVParam -- bond valence data associated with specific cation-anion pair # exported items, these also makes them show in pydoc. -__all__ = ['BVParam', 'BVParametersTable'] +__all__ = ["BVParam", "BVParametersTable"] from diffpy.srreal.srreal_ext import BVParam, BVParametersTable diff --git a/src/diffpy/srreal/bvscalculator.py b/src/diffpy/srreal/bvscalculator.py index 47cb2cef..2e1cb1c1 100644 --- a/src/diffpy/srreal/bvscalculator.py +++ b/src/diffpy/srreal/bvscalculator.py @@ -18,7 +18,7 @@ # exported items -__all__ = ['BVSCalculator'] +__all__ = ["BVSCalculator"] from diffpy.srreal.srreal_ext import BVSCalculator from diffpy.srreal.wraputils import propertyFromExtDoubleAttr @@ -26,45 +26,54 @@ # Property wrappers to C++ double attributes -BVSCalculator.valenceprecision = propertyFromExtDoubleAttr('valenceprecision', - '''Cutoff value for valence contributions at long distances. - [1e-5]''') +BVSCalculator.valenceprecision = propertyFromExtDoubleAttr( + "valenceprecision", + """Cutoff value for valence contributions at long distances. + [1e-5]""", +) -BVSCalculator.rmaxused = propertyFromExtDoubleAttr('rmaxused', - '''Effective bound for bond lengths, where valence contributions +BVSCalculator.rmaxused = propertyFromExtDoubleAttr( + "rmaxused", + """Effective bound for bond lengths, where valence contributions become smaller than valenceprecission, read-only. Always smaller or equal to rmax. The value depends on ions present in the structure. - ''') - -BVSCalculator.rmin = propertyFromExtDoubleAttr('rmin', - '''Lower bound for the summed bond lengths. - [0 A]''') - -BVSCalculator.rmax = propertyFromExtDoubleAttr('rmax', - '''Upper bound for the summed bond lengths. The calculation is + """, +) + +BVSCalculator.rmin = propertyFromExtDoubleAttr( + "rmin", + """Lower bound for the summed bond lengths. + [0 A]""", +) + +BVSCalculator.rmax = propertyFromExtDoubleAttr( + "rmax", + """Upper bound for the summed bond lengths. The calculation is actually cut off much earlier when valence contributions get below valenceprecission. See also rmaxused and valenceprecission. - [1e6 A]''') + [1e6 A]""", +) # method overrides that support keyword arguments + def _init_kwargs(self, **kwargs): - '''Create a new instance of BVSCalculator. + """Create a new instance of BVSCalculator. Keyword arguments can be used to configure the calculator properties, for example: bvscalc = BVSCalculator(valenceprecision=0.001) Raise ValueError for invalid keyword argument. - ''' + """ BVSCalculator.__boostpython__init(self) setattrFromKeywordArguments(self, **kwargs) return def _call_kwargs(self, structure=None, **kwargs): - '''Return bond valence sums at each atom site in the structure. + """Return bond valence sums at each atom site in the structure. structure -- structure to be evaluated, an instance of diffpy Structure or pyobjcryst Crystal. Reuse the last structure when None. @@ -72,7 +81,7 @@ def _call_kwargs(self, structure=None, **kwargs): Return an array of calculated valence sums. See valences for the expected values. - ''' + """ setattrFromKeywordArguments(self, **kwargs) rv = self.eval(structure) return rv diff --git a/src/diffpy/srreal/eventticker.py b/src/diffpy/srreal/eventticker.py index 3a3d5795..ecec69ac 100644 --- a/src/diffpy/srreal/eventticker.py +++ b/src/diffpy/srreal/eventticker.py @@ -19,7 +19,7 @@ class EventTicker -- storage of modification times of dependent objects # exported items -__all__ = ['EventTicker'] +__all__ = ["EventTicker"] from diffpy.srreal.srreal_ext import EventTicker diff --git a/src/diffpy/srreal/overlapcalculator.py b/src/diffpy/srreal/overlapcalculator.py index e0813597..c99aed61 100644 --- a/src/diffpy/srreal/overlapcalculator.py +++ b/src/diffpy/srreal/overlapcalculator.py @@ -18,7 +18,7 @@ # exported items, these also makes them show in pydoc. -__all__ = ['OverlapCalculator'] +__all__ = ["OverlapCalculator"] from diffpy.srreal.wraputils import propertyFromExtDoubleAttr from diffpy.srreal.wraputils import setattrFromKeywordArguments @@ -26,45 +26,52 @@ # property wrappers to C++ double attributes -OverlapCalculator.rmin = propertyFromExtDoubleAttr('rmin', - '''Lower bound for the bond distances. - [0 A]''') - -OverlapCalculator.rmax = propertyFromExtDoubleAttr('rmax', - '''Upper bound for the bond distances. - [5 A]''') - -OverlapCalculator.rmaxused = propertyFromExtDoubleAttr('rmaxused', - '''Effective upper bound for the bond distances. +OverlapCalculator.rmin = propertyFromExtDoubleAttr( + "rmin", + """Lower bound for the bond distances. + [0 A]""", +) + +OverlapCalculator.rmax = propertyFromExtDoubleAttr( + "rmax", + """Upper bound for the bond distances. + [5 A]""", +) + +OverlapCalculator.rmaxused = propertyFromExtDoubleAttr( + "rmaxused", + """Effective upper bound for the bond distances. rmaxused equals either a double of the maximum atom radius in the structure or rmax. - ''') + """, +) # method overrides that support keyword arguments + def _init_kwargs(self, **kwargs): - '''Create a new instance of OverlapCalculator. + """Create a new instance of OverlapCalculator. Keyword arguments can be used to configure calculator properties, for example: olc = OverlapCalculator(rmax=2.5) Raise ValueError for invalid keyword argument. - ''' + """ OverlapCalculator.__boostpython__init(self) setattrFromKeywordArguments(self, **kwargs) return def _call_kwargs(self, structure=None, **kwargs): - '''Return siteSquareOverlaps per each site of the structure. + """Return siteSquareOverlaps per each site of the structure. structure -- structure to be evaluated, an instance of diffpy Structure or pyobjcryst Crystal. Reuse the last structure when None. kwargs -- optional parameter settings for this calculator Return a numpy array. - ''' + """ setattrFromKeywordArguments(self, **kwargs) self.eval(structure) return self.sitesquareoverlaps diff --git a/src/diffpy/srreal/pairquantity.py b/src/diffpy/srreal/pairquantity.py index f6a537b9..bba56c6b 100644 --- a/src/diffpy/srreal/pairquantity.py +++ b/src/diffpy/srreal/pairquantity.py @@ -19,7 +19,7 @@ class PairQuantity -- base class for Python defined calculators. # exported items -__all__ = ['PairQuantity'] +__all__ = ["PairQuantity"] from diffpy.srreal.srreal_ext import PairQuantity diff --git a/src/diffpy/srreal/parallel.py b/src/diffpy/srreal/parallel.py index c5a3d75b..413836a0 100644 --- a/src/diffpy/srreal/parallel.py +++ b/src/diffpy/srreal/parallel.py @@ -19,7 +19,7 @@ # exported items -__all__ = ['createParallelCalculator'] +__all__ = ["createParallelCalculator"] import copy import inspect @@ -27,8 +27,9 @@ # ---------------------------------------------------------------------------- + def createParallelCalculator(pqobj, ncpu, pmap): - '''Create a proxy parallel calculator to a PairQuantity instance. + """Create a proxy parallel calculator to a PairQuantity instance. pqobj -- instance of PairQuantity calculator to be run in parallel ncpu -- number of parallel jobs @@ -39,11 +40,10 @@ def createParallelCalculator(pqobj, ncpu, pmap): Return a proxy calculator instance that has the same interface, but executes the calculation in parallel split among ncpu jobs. - ''' + """ class ParallelPairQuantity(Attributes): - - '''Class for running parallel calculations. This is a proxy class + """Class for running parallel calculations. This is a proxy class to the wrapper PairQuantity type with the same interface. Instance data: @@ -51,68 +51,71 @@ class ParallelPairQuantity(Attributes): pqobj -- the master PairQuantity object to be evaluated in parallel ncpu -- number of parallel jobs pmap -- a parallel map function used to submit job to workers - ''' + """ def __init__(self, pqobj, ncpu, pmap): - '''Initialize a parallel proxy to the PairQuantity instance. + """Initialize a parallel proxy to the PairQuantity instance. pqobj -- instance of PairQuantity calculator to be run in parallel ncpu -- number of parallel jobs pmap -- a parallel map function used to submit job to workers - ''' + """ # use explicit assignment to avoid setattr forwarding to the pqobj - object.__setattr__(self, 'pqobj', pqobj) - object.__setattr__(self, 'ncpu', ncpu) - object.__setattr__(self, 'pmap', pmap) + object.__setattr__(self, "pqobj", pqobj) + object.__setattr__(self, "ncpu", ncpu) + object.__setattr__(self, "pmap", pmap) # parallel calculations support only the BASIC evaluation - self.pqobj.evaluatortype = 'BASIC' + self.pqobj.evaluatortype = "BASIC" return - def eval(self, stru=None): - '''Perform parallel calculation and return internal value array. + """Perform parallel calculation and return internal value array. stru -- object that can be converted to StructureAdapter, e.g., example diffpy Structure or pyobjcryst Crystal. Use the last structure when None. Return numpy array. - ''' + """ # use StructureAdapter for faster pickles from diffpy.srreal.structureadapter import createStructureAdapter + if stru is None: struadpt = self.pqobj.getStructure() else: struadpt = createStructureAdapter(stru) self.pqobj.setStructure(struadpt) - kwd = { 'cpuindex' : None, - 'ncpu' : self.ncpu, - 'pqobj' : copy.copy(self.pqobj), - } + kwd = { + "cpuindex": None, + "ncpu": self.ncpu, + "pqobj": copy.copy(self.pqobj), + } # shallow copies of kwd dictionary each with a unique cpuindex - arglist = [kwd.copy() for kwd['cpuindex'] in range(self.ncpu)] + arglist = [kwd.copy() for kwd["cpuindex"] in range(self.ncpu)] for pdata in self.pmap(_parallelData, arglist): self.pqobj._mergeParallelData(pdata, self.ncpu) return self.pqobj.value - def __call__(self, *args, **kwargs): - '''Call the wrapped calculator using parallel evaluation. + """Call the wrapped calculator using parallel evaluation. The arguments and return value are the same as for the wrapped PairQuantity calculator. - ''' - savedeval = self.pqobj.__dict__.get('eval') + """ + savedeval = self.pqobj.__dict__.get("eval") + def restore_eval(): if savedeval: self.pqobj.eval = savedeval else: - self.pqobj.__dict__.pop('eval', None) + self.pqobj.__dict__.pop("eval", None) + def parallel_eval(stru): assert self.pqobj.eval is parallel_eval restore_eval() return self.eval(stru) + self.pqobj.eval = parallel_eval try: rv = self.pqobj(*args, **kwargs) @@ -120,7 +123,6 @@ def parallel_eval(stru): restore_eval() return rv - @property def evaluatortype(self): """str : Type of evaluation procedure. @@ -145,22 +147,25 @@ def evaluatortype(self, value): # create proxy methods to all public methods and some protected methods - proxy_forced = set('''_getDoubleAttr _setDoubleAttr _hasDoubleAttr + proxy_forced = set( + """_getDoubleAttr _setDoubleAttr _hasDoubleAttr _namesOfDoubleAttributes _namesOfWritableDoubleAttributes - '''.split()) + """.split() + ) def _make_proxymethod(name, f): def proxymethod(self, *args, **kwargs): - pqobj = object.__getattribute__(self, 'pqobj') + pqobj = object.__getattribute__(self, "pqobj") return f(pqobj, *args, **kwargs) + proxymethod.__name__ = name proxymethod.__doc__ = f.__doc__ return proxymethod for n, f in inspect.getmembers(pqtype, inspect.isroutine): - ignore = n not in proxy_forced and (n.startswith('_') or - hasattr(ParallelPairQuantity, n)) - if ignore: continue + ignore = n not in proxy_forced and (n.startswith("_") or hasattr(ParallelPairQuantity, n)) + if ignore: + continue setattr(ParallelPairQuantity, n, _make_proxymethod(n, f)) # create proxy properties to all properties that do not conflict with @@ -169,15 +174,25 @@ def proxymethod(self, *args, **kwargs): def _make_proxyproperty(prop): fget = fset = fdel = None if prop.fget: - def fget(self): return prop.fget(self.pqobj) + + def fget(self): + return prop.fget(self.pqobj) + if prop.fset: - def fset(self, value): return prop.fset(self.pqobj, value) + + def fset(self, value): + return prop.fset(self.pqobj, value) + if prop.fdel: - def fdel(self): return prop.fdel(self.pqobj) + + def fdel(self): + return prop.fdel(self.pqobj) + return property(fget, fset, fdel, prop.__doc__) for n, p in inspect.getmembers(pqtype, lambda x: type(x) is property): - if hasattr(ParallelPairQuantity, n): continue + if hasattr(ParallelPairQuantity, n): + continue setattr(ParallelPairQuantity, n, _make_proxyproperty(p)) # finally create an instance of this very custom class @@ -185,11 +200,11 @@ def fdel(self): return prop.fdel(self.pqobj) def _parallelData(kwd): - '''Helper for calculating and fetching raw results from a worker node. - ''' - pqobj = kwd['pqobj'] - pqobj._setupParallelRun(kwd['cpuindex'], kwd['ncpu']) + """Helper for calculating and fetching raw results from a worker node.""" + pqobj = kwd["pqobj"] + pqobj._setupParallelRun(kwd["cpuindex"], kwd["ncpu"]) pqobj.eval() return pqobj._getParallelData() + # End of file diff --git a/src/diffpy/srreal/pdfbaseline.py b/src/diffpy/srreal/pdfbaseline.py index 5f5af2ba..dc8581cc 100644 --- a/src/diffpy/srreal/pdfbaseline.py +++ b/src/diffpy/srreal/pdfbaseline.py @@ -20,11 +20,11 @@ # exported items -__all__ = ''' +__all__ = """ PDFBaseline makePDFBaseline ZeroBaseline LinearBaseline - '''.split() + """.split() from diffpy.srreal import _final_imports from diffpy.srreal.srreal_ext import PDFBaseline @@ -40,14 +40,17 @@ # attribute wrapper -LinearBaseline.slope = propertyFromExtDoubleAttr('slope', - '''Slope of an unscaled linear baseline. For crystal structures it - is preset to (-4 * pi * rho0).''') +LinearBaseline.slope = propertyFromExtDoubleAttr( + "slope", + """Slope of an unscaled linear baseline. For crystal structures it + is preset to (-4 * pi * rho0).""", +) # Python functions wrapper + def makePDFBaseline(name, fnc, replace=False, **dbattrs): - '''Helper function for registering Python function as a PDFBaseline. + """Helper function for registering Python function as a PDFBaseline. This is required for using Python function as PDFCalculator.baseline. name -- unique string name for registering Python function in the @@ -81,12 +84,13 @@ def fshiftedline(x, aline, bline): pdfc = PDFCalculator() pdfc.baseline = baseline # or pdfc.baseline = "shiftedline" - ''' + """ from diffpy.srreal.wraputils import _wrapAsRegisteredUnaryFunction - rv = _wrapAsRegisteredUnaryFunction(PDFBaseline, name, fnc, - replace=replace, **dbattrs) + + rv = _wrapAsRegisteredUnaryFunction(PDFBaseline, name, fnc, replace=replace, **dbattrs) return rv + # Import delayed tweaks of the extension classes. _final_imports.import_now() diff --git a/src/diffpy/srreal/pdfcalculator.py b/src/diffpy/srreal/pdfcalculator.py index f34b25d7..5c30cf16 100644 --- a/src/diffpy/srreal/pdfcalculator.py +++ b/src/diffpy/srreal/pdfcalculator.py @@ -21,10 +21,10 @@ # exported items -__all__ = ''' +__all__ = """ DebyePDFCalculator PDFCalculator fftftog fftgtof - '''.split() + """.split() from diffpy.srreal.srreal_ext import DebyePDFCalculator from diffpy.srreal.srreal_ext import PDFCalculator @@ -36,81 +36,119 @@ assert all((fftftog, fftgtof)) # imports for backward compatibility -from diffpy.srreal.pdfbaseline import (PDFBaseline, makePDFBaseline, - ZeroBaseline, LinearBaseline) -from diffpy.srreal.pdfenvelope import (PDFEnvelope, makePDFEnvelope, - QResolutionEnvelope, ScaleEnvelope, - SphericalShapeEnvelope, StepCutEnvelope) +from diffpy.srreal.pdfbaseline import PDFBaseline, makePDFBaseline, ZeroBaseline, LinearBaseline +from diffpy.srreal.pdfenvelope import ( + PDFEnvelope, + makePDFEnvelope, + QResolutionEnvelope, + ScaleEnvelope, + SphericalShapeEnvelope, + StepCutEnvelope, +) from diffpy.srreal.peakprofile import PeakProfile -from diffpy.srreal.peakwidthmodel import (PeakWidthModel, - ConstantPeakWidth, DebyeWallerPeakWidth, JeongPeakWidth) +from diffpy.srreal.peakwidthmodel import PeakWidthModel, ConstantPeakWidth, DebyeWallerPeakWidth, JeongPeakWidth # silence the pyflakes syntax checker -assert all((PDFBaseline, makePDFBaseline, ZeroBaseline, LinearBaseline, - PDFEnvelope, makePDFEnvelope, QResolutionEnvelope, ScaleEnvelope, - SphericalShapeEnvelope, StepCutEnvelope, PeakProfile, - PeakWidthModel, ConstantPeakWidth, DebyeWallerPeakWidth, - JeongPeakWidth)) +assert all( + ( + PDFBaseline, + makePDFBaseline, + ZeroBaseline, + LinearBaseline, + PDFEnvelope, + makePDFEnvelope, + QResolutionEnvelope, + ScaleEnvelope, + SphericalShapeEnvelope, + StepCutEnvelope, + PeakProfile, + PeakWidthModel, + ConstantPeakWidth, + DebyeWallerPeakWidth, + JeongPeakWidth, + ) +) # ---------------------------------------------------------------------------- -def _defineCommonInterface(cls): - '''This function defines shared properties of PDF calculator classes. - ''' +def _defineCommonInterface(cls): + """This function defines shared properties of PDF calculator classes.""" - cls.scale = propertyFromExtDoubleAttr('scale', - '''Scale factor of the calculated PDF. Active for ScaleEnvelope. - [1.0 unitless]''') + cls.scale = propertyFromExtDoubleAttr( + "scale", + """Scale factor of the calculated PDF. Active for ScaleEnvelope. + [1.0 unitless]""", + ) - cls.delta1 = propertyFromExtDoubleAttr('delta1', - '''Coefficient for (1/r) contribution to the peak sharpening. + cls.delta1 = propertyFromExtDoubleAttr( + "delta1", + """Coefficient for (1/r) contribution to the peak sharpening. Active for JeongPeakWidth model. - [0 A]''') + [0 A]""", + ) - cls.delta2 = propertyFromExtDoubleAttr('delta2', - '''Coefficient for (1/r**2) contribution to the peak sharpening. + cls.delta2 = propertyFromExtDoubleAttr( + "delta2", + """Coefficient for (1/r**2) contribution to the peak sharpening. Active for JeongPeakWidth model. - [0 A**2]''') + [0 A**2]""", + ) - cls.qdamp = propertyFromExtDoubleAttr('qdamp', - '''PDF Gaussian dampening factor due to limited Q-resolution. + cls.qdamp = propertyFromExtDoubleAttr( + "qdamp", + """PDF Gaussian dampening factor due to limited Q-resolution. Not applied when equal to zero. Active for QResolutionEnvelope. - [0 1/A]''') + [0 1/A]""", + ) - cls.qbroad = propertyFromExtDoubleAttr('qbroad', - '''PDF peak broadening from increased intensity noise at high Q. + cls.qbroad = propertyFromExtDoubleAttr( + "qbroad", + """PDF peak broadening from increased intensity noise at high Q. Not applied when equal zero. Active for JeongPeakWidth model. - [0 1/A]''') - - cls.extendedrmin = propertyFromExtDoubleAttr('extendedrmin', - '''Low boundary of the extended r-range, read-only. - [A]''') - - cls.extendedrmax = propertyFromExtDoubleAttr('extendedrmax', - '''Upper boundary of the extended r-range, read-only. - [A]''') - - cls.maxextension = propertyFromExtDoubleAttr('maxextension', - '''Maximum extension of the r-range that accounts for contributions + [0 1/A]""", + ) + + cls.extendedrmin = propertyFromExtDoubleAttr( + "extendedrmin", + """Low boundary of the extended r-range, read-only. + [A]""", + ) + + cls.extendedrmax = propertyFromExtDoubleAttr( + "extendedrmax", + """Upper boundary of the extended r-range, read-only. + [A]""", + ) + + cls.maxextension = propertyFromExtDoubleAttr( + "maxextension", + """Maximum extension of the r-range that accounts for contributions from the out of range peaks. - [10 A]''') - - cls.rmin = propertyFromExtDoubleAttr('rmin', - '''Lower bound of the r-grid for PDF calculation. - [0 A]''') - - cls.rmax = propertyFromExtDoubleAttr('rmax', - '''Upper bound of the r-grid for PDF calculation. - [10 A]''') - - cls.rstep = propertyFromExtDoubleAttr('rstep', - '''Spacing in the calculated r-grid. r-values are at the + [10 A]""", + ) + + cls.rmin = propertyFromExtDoubleAttr( + "rmin", + """Lower bound of the r-grid for PDF calculation. + [0 A]""", + ) + + cls.rmax = propertyFromExtDoubleAttr( + "rmax", + """Upper bound of the r-grid for PDF calculation. + [10 A]""", + ) + + cls.rstep = propertyFromExtDoubleAttr( + "rstep", + """Spacing in the calculated r-grid. r-values are at the multiples of rstep. - [0.01 A]''') + [0.01 A]""", + ) def _call_kwargs(self, structure=None, **kwargs): - '''Calculate PDF for the given structure as an (r, G) tuple. + """Calculate PDF for the given structure as an (r, G) tuple. Keyword arguments can be used to configure calculator attributes, these override any properties that may be passed from the structure, such as spdiameter. @@ -122,7 +160,7 @@ def _call_kwargs(self, structure=None, **kwargs): Example: pdfcalc(structure, qmax=20, spdiameter=15) Return a tuple of (r, G) numpy arrays. - ''' + """ setattrFromKeywordArguments(self, **kwargs) self.eval(structure) # apply kwargs again if structure contained any attribute @@ -130,8 +168,10 @@ def _call_kwargs(self, structure=None, **kwargs): setattrFromKeywordArguments(self, **kwargs) rv = (self.rgrid, self.pdf) return rv + cls.__call__ = _call_kwargs + # _defineCommonInterface # class DebyePDFCalculator --------------------------------------------------- @@ -142,42 +182,52 @@ def _call_kwargs(self, structure=None, **kwargs): # Property wrappers to double attributes of the C++ DebyePDFCalculator -DebyePDFCalculator.debyeprecision = propertyFromExtDoubleAttr('debyeprecision', - '''Cutoff amplitude for the sine contributions to the F(Q). - [1e-6 unitless]''') +DebyePDFCalculator.debyeprecision = propertyFromExtDoubleAttr( + "debyeprecision", + """Cutoff amplitude for the sine contributions to the F(Q). + [1e-6 unitless]""", +) -DebyePDFCalculator.qmin = propertyFromExtDoubleAttr('qmin', - '''Lower bound of the Q-grid for the calculated F(Q). +DebyePDFCalculator.qmin = propertyFromExtDoubleAttr( + "qmin", + """Lower bound of the Q-grid for the calculated F(Q). Affects the shape envelope. [0 1/A] - ''') + """, +) -DebyePDFCalculator.qmax = propertyFromExtDoubleAttr('qmax', - '''Upper bound of the Q-grid for the calculated F(Q). +DebyePDFCalculator.qmax = propertyFromExtDoubleAttr( + "qmax", + """Upper bound of the Q-grid for the calculated F(Q). Affects the termination ripples. [25 1/A] - ''') + """, +) -DebyePDFCalculator.qstep = propertyFromExtDoubleAttr('qstep', - '''Spacing in the Q-grid. Q-values are at the multiples of qstep. +DebyePDFCalculator.qstep = propertyFromExtDoubleAttr( + "qstep", + """Spacing in the Q-grid. Q-values are at the multiples of qstep. [PI/extendedrmax A] unless user overridden. - See also setOptimumQstep, isOptimumQstep.''') + See also setOptimumQstep, isOptimumQstep.""", +) # method overrides to support optional keyword arguments + def _init_kwargs0(self, **kwargs): - '''Create a new instance of the DebyePDFCalculator. + """Create a new instance of the DebyePDFCalculator. Keyword arguments can be used to configure the calculator properties, for example: dpc = DebyePDFCalculator(qmax=20, rmin=7, rmax=15) Raise ValueError for invalid keyword argument. - ''' + """ DebyePDFCalculator.__boostpython__init(self) setattrFromKeywordArguments(self, **kwargs) return + DebyePDFCalculator.__boostpython__init = DebyePDFCalculator.__init__ DebyePDFCalculator.__init__ = _init_kwargs0 @@ -191,58 +241,74 @@ def _init_kwargs0(self, **kwargs): # Property wrappers to double attributes of the C++ PDFCalculator -PDFCalculator.peakprecision = propertyFromExtDoubleAttr('peakprecision', - '''Cutoff amplitude of the peak tail relative to the peak maximum. - [3.33e-6 unitless]''') +PDFCalculator.peakprecision = propertyFromExtDoubleAttr( + "peakprecision", + """Cutoff amplitude of the peak tail relative to the peak maximum. + [3.33e-6 unitless]""", +) -PDFCalculator.qmin = propertyFromExtDoubleAttr('qmin', - '''Lower bound of the experimental Q-range used. +PDFCalculator.qmin = propertyFromExtDoubleAttr( + "qmin", + """Lower bound of the experimental Q-range used. Affects the shape envelope. - [0 1/A]''') + [0 1/A]""", +) -PDFCalculator.qmax = propertyFromExtDoubleAttr('qmax', - '''Upper bound of the experimental Q-range used. +PDFCalculator.qmax = propertyFromExtDoubleAttr( + "qmax", + """Upper bound of the experimental Q-range used. Affects the termination ripples. Not used when zero. - [0 1/A]''') + [0 1/A]""", +) -PDFCalculator.qstep = propertyFromExtDoubleAttr('qstep', - '''Spacing in the Q-grid. Q-values are at the multiples of qstep. +PDFCalculator.qstep = propertyFromExtDoubleAttr( + "qstep", + """Spacing in the Q-grid. Q-values are at the multiples of qstep. The value is padded by rsteps so that PI/qstep > extendedrmax and PI/(qstep * rstep) is a power of 2. Read-only. - [PI/(padded extendedrmax) A]''') + [PI/(padded extendedrmax) A]""", +) -PDFCalculator.slope = propertyFromExtDoubleAttr('slope', - '''Slope of the linear PDF background. Assigned according to +PDFCalculator.slope = propertyFromExtDoubleAttr( + "slope", + """Slope of the linear PDF background. Assigned according to number density of the evaluated structure at each PDF calculation. Active for LinearBaseline. - [-4*pi*numdensity unitless]''') + [-4*pi*numdensity unitless]""", +) -PDFCalculator.spdiameter = propertyFromExtDoubleAttr('spdiameter', - '''Spherical particle diameter for PDF shape damping correction. +PDFCalculator.spdiameter = propertyFromExtDoubleAttr( + "spdiameter", + """Spherical particle diameter for PDF shape damping correction. Not used when zero. Active for SphericalShapeEnvelope. - [0 A]''') + [0 A]""", +) -PDFCalculator.stepcut = propertyFromExtDoubleAttr('stepcut', - '''r-boundary for a step cutoff of the calculated PDF. +PDFCalculator.stepcut = propertyFromExtDoubleAttr( + "stepcut", + """r-boundary for a step cutoff of the calculated PDF. Not used when negative or zero. Active for StepCutEnvelope. Not used when zero. Active for StepCutEnvelope. - [0 A]''') + [0 A]""", +) # method overrides to support optional keyword arguments + def _init_kwargs1(self, **kwargs): - '''Create a new instance of PDFCalculator. + """Create a new instance of PDFCalculator. Keyword arguments can be used to configure the calculator properties, for example: pc = PDFCalculator(qmax=20, rmin=7, rmax=15) Raise ValueError for invalid keyword argument. - ''' + """ PDFCalculator.__boostpython__init(self) setattrFromKeywordArguments(self, **kwargs) return + PDFCalculator.__boostpython__init = PDFCalculator.__init__ PDFCalculator.__init__ = _init_kwargs1 diff --git a/src/diffpy/srreal/pdfenvelope.py b/src/diffpy/srreal/pdfenvelope.py index d4cb93d3..e43a345a 100644 --- a/src/diffpy/srreal/pdfenvelope.py +++ b/src/diffpy/srreal/pdfenvelope.py @@ -21,13 +21,13 @@ # exported items -__all__ = ''' +__all__ = """ PDFEnvelope makePDFEnvelope QResolutionEnvelope ScaleEnvelope SphericalShapeEnvelope StepCutEnvelope - '''.split() + """.split() from diffpy.srreal import _final_imports from diffpy.srreal.srreal_ext import PDFEnvelope @@ -46,26 +46,35 @@ # attribute wrappers -QResolutionEnvelope.qdamp = propertyFromExtDoubleAttr('qdamp', - '''Dampening parameter in the Gaussian envelope function. - ''') - -ScaleEnvelope.scale = propertyFromExtDoubleAttr('scale', - '''Overall scale for a uniform scaling envelope. - ''') - -SphericalShapeEnvelope.spdiameter = propertyFromExtDoubleAttr('spdiameter', - '''Particle diameter in Angstroms for a spherical shape damping. - ''') - -StepCutEnvelope.stepcut = propertyFromExtDoubleAttr('stepcut', - '''Cutoff for a step-function envelope. - ''') +QResolutionEnvelope.qdamp = propertyFromExtDoubleAttr( + "qdamp", + """Dampening parameter in the Gaussian envelope function. + """, +) + +ScaleEnvelope.scale = propertyFromExtDoubleAttr( + "scale", + """Overall scale for a uniform scaling envelope. + """, +) + +SphericalShapeEnvelope.spdiameter = propertyFromExtDoubleAttr( + "spdiameter", + """Particle diameter in Angstroms for a spherical shape damping. + """, +) + +StepCutEnvelope.stepcut = propertyFromExtDoubleAttr( + "stepcut", + """Cutoff for a step-function envelope. + """, +) # Python functions wrapper + def makePDFEnvelope(name, fnc, replace=False, **dbattrs): - '''Helper function for registering Python function as a PDFEnvelope. + """Helper function for registering Python function as a PDFEnvelope. This is required for using Python function as PDFCalculator envelope. name -- unique string name for registering Python function in the @@ -100,12 +109,13 @@ def fexpdecay(x, expscale, exptail): pdfc = PDFCalculator() pdfc.addEnvelope(envelope) # or pdfc.addEnvelope("expdecay") - ''' + """ from diffpy.srreal.wraputils import _wrapAsRegisteredUnaryFunction - rv = _wrapAsRegisteredUnaryFunction(PDFEnvelope, name, fnc, - replace=replace, **dbattrs) + + rv = _wrapAsRegisteredUnaryFunction(PDFEnvelope, name, fnc, replace=replace, **dbattrs) return rv + # Import delayed tweaks of the extension classes. _final_imports.import_now() diff --git a/src/diffpy/srreal/peakprofile.py b/src/diffpy/srreal/peakprofile.py index e3745fa7..d082ac89 100644 --- a/src/diffpy/srreal/peakprofile.py +++ b/src/diffpy/srreal/peakprofile.py @@ -21,11 +21,7 @@ # exported items -__all__ = [ - 'PeakProfile', - 'GaussianProfile', - 'CroppedGaussianProfile' -] +__all__ = ["PeakProfile", "GaussianProfile", "CroppedGaussianProfile"] from diffpy.srreal import _final_imports from diffpy.srreal.srreal_ext import PeakProfile @@ -41,10 +37,12 @@ # add attribute wrappers for PeakProfile and derived classes -PeakProfile.peakprecision = propertyFromExtDoubleAttr('peakprecision', - '''Profile amplitude relative to the peak maximum for evaluating peak +PeakProfile.peakprecision = propertyFromExtDoubleAttr( + "peakprecision", + """Profile amplitude relative to the peak maximum for evaluating peak bounds xboundlo and xboundhi. [3.33e-6 unitless] - ''') + """, +) # Import delayed tweaks of the extension classes. diff --git a/src/diffpy/srreal/peakwidthmodel.py b/src/diffpy/srreal/peakwidthmodel.py index 59274712..75610987 100644 --- a/src/diffpy/srreal/peakwidthmodel.py +++ b/src/diffpy/srreal/peakwidthmodel.py @@ -21,12 +21,7 @@ # exported items -__all__ = [ - 'PeakWidthModel', - 'ConstantPeakWidth', - 'DebyeWallerPeakWidth', - 'JeongPeakWidth' -] +__all__ = ["PeakWidthModel", "ConstantPeakWidth", "DebyeWallerPeakWidth", "JeongPeakWidth"] from diffpy.srreal import _final_imports from diffpy.srreal.srreal_ext import PeakWidthModel, ConstantPeakWidth @@ -37,26 +32,35 @@ # add attribute wrappers for the derived classes -ConstantPeakWidth.width = propertyFromExtDoubleAttr('width', - '''Constant FWHM value returned by this model. - ''') +ConstantPeakWidth.width = propertyFromExtDoubleAttr( + "width", + """Constant FWHM value returned by this model. + """, +) -ConstantPeakWidth.bisowidth = propertyFromExtDoubleAttr('bisowidth', - '''Equivalent uniform Biso for this constant `width`. - ''') +ConstantPeakWidth.bisowidth = propertyFromExtDoubleAttr( + "bisowidth", + """Equivalent uniform Biso for this constant `width`. + """, +) -ConstantPeakWidth.uisowidth = propertyFromExtDoubleAttr('uisowidth', - '''Equivalent uniform Uiso for this constant `width`. - ''') +ConstantPeakWidth.uisowidth = propertyFromExtDoubleAttr( + "uisowidth", + """Equivalent uniform Uiso for this constant `width`. + """, +) -JeongPeakWidth.delta1 = propertyFromExtDoubleAttr('delta1', - 'Coefficient for (1/r) contribution to the peak sharpening.') +JeongPeakWidth.delta1 = propertyFromExtDoubleAttr( + "delta1", "Coefficient for (1/r) contribution to the peak sharpening." +) -JeongPeakWidth.delta2 = propertyFromExtDoubleAttr('delta2', - 'Coefficient for (1/r**2) contribution to the peak sharpening.') +JeongPeakWidth.delta2 = propertyFromExtDoubleAttr( + "delta2", "Coefficient for (1/r**2) contribution to the peak sharpening." +) -JeongPeakWidth.qbroad = propertyFromExtDoubleAttr('qbroad', - 'PDF peak broadening from increased intensity noise at high Q.') +JeongPeakWidth.qbroad = propertyFromExtDoubleAttr( + "qbroad", "PDF peak broadening from increased intensity noise at high Q." +) # Import delayed tweaks of the extension classes. diff --git a/src/diffpy/srreal/scatteringfactortable.py b/src/diffpy/srreal/scatteringfactortable.py index 5e4e1d6f..26f2ed3e 100644 --- a/src/diffpy/srreal/scatteringfactortable.py +++ b/src/diffpy/srreal/scatteringfactortable.py @@ -19,9 +19,7 @@ class ScatteringFactorTable -- scattering factors for atoms, ions and isotopes. # exported items, these also makes them show in pydoc. -__all__ = ['ScatteringFactorTable', - 'SFTXray', 'SFTElectron', 'SFTNeutron', 'SFTElectronNumber', - 'SFAverage'] +__all__ = ["ScatteringFactorTable", "SFTXray", "SFTElectron", "SFTNeutron", "SFTElectronNumber", "SFAverage"] from diffpy.srreal.srreal_ext import ScatteringFactorTable from diffpy.srreal.srreal_ext import SFTXray diff --git a/src/diffpy/srreal/sfaverage.py b/src/diffpy/srreal/sfaverage.py index fd1795f3..46c61b12 100644 --- a/src/diffpy/srreal/sfaverage.py +++ b/src/diffpy/srreal/sfaverage.py @@ -39,6 +39,7 @@ # class SFAverage ------------------------------------------------------------ + class SFAverage(object): """\ Calculate compositional statistics of atom scattering factors. @@ -103,12 +104,13 @@ def fromStructure(cls, stru, sftb, q=0): The calculated scattering factor averages. """ # a bit of duck-typing for faster handling of diffpy.structure - if hasattr(type(stru), 'composition'): + if hasattr(type(stru), "composition"): composition = stru.composition if isinstance(composition, dict): return cls.fromComposition(composition, sftb, q) # otherwise let's convert to a known structure type from diffpy.srreal.structureadapter import createStructureAdapter + adpt = createStructureAdapter(stru) composition = {} for i in range(adpt.countSites()): @@ -117,7 +119,6 @@ def fromStructure(cls, stru, sftb, q=0): composition[smbl] = composition.get(smbl, 0) + cnt return cls.fromComposition(composition, sftb, q) - @classmethod def fromComposition(cls, composition, sftb, q=0): """\ @@ -142,6 +143,7 @@ def fromComposition(cls, composition, sftb, q=0): The calculated scattering factor averages. """ from diffpy.srreal.scatteringfactortable import ScatteringFactorTable + sfa = cls() sfa.composition = {} if isinstance(composition, dict): @@ -154,8 +156,7 @@ def fromComposition(cls, composition, sftb, q=0): sfa.f1sum = 0.0 * q sfa.f2sum = 0.0 * q # resolve the lookup table object `tb` - tb = (sftb if not isinstance(sftb, str) - else ScatteringFactorTable.createByType(sftb)) + tb = sftb if not isinstance(sftb, str) else ScatteringFactorTable.createByType(sftb) for smbl, cnt in sfa.composition.items(): sfq = tb.lookup(smbl, q) sfa.f1sum += cnt * sfq @@ -166,4 +167,5 @@ def fromComposition(cls, composition, sftb, q=0): sfa.f2avg = sfa.f2sum / denom return sfa + # End of class SFAverage diff --git a/src/diffpy/srreal/structureadapter.py b/src/diffpy/srreal/structureadapter.py index 4740977b..dc9fdc30 100644 --- a/src/diffpy/srreal/structureadapter.py +++ b/src/diffpy/srreal/structureadapter.py @@ -29,8 +29,9 @@ EMPTY -- singleton instance of an empty structure. """ + def createStructureAdapter(stru): - ''' + """ Create StructureAdapter from a Python object. stru -- an object that is convertible to StructureAdapter, i.e., it has @@ -39,14 +40,17 @@ def createStructureAdapter(stru): Return a StructureAdapter instance. Raise TypeError if stru cannot be converted to StructureAdapter. - ''' - if isinstance(stru, StructureAdapter): return stru + """ + if isinstance(stru, StructureAdapter): + return stru import inspect + # build fully-qualified names of Python types in method resolution order cls = type(stru) fqnames = [str(tp).split("'")[1] for tp in inspect.getmro(cls)] for fqn in fqnames: - if not fqn in _adapter_converters_registry: continue + if not fqn in _adapter_converters_registry: + continue factory = _adapter_converters_registry[fqn] return factory(stru) # none of the registered factories could convert the stru object @@ -55,7 +59,7 @@ def createStructureAdapter(stru): def RegisterStructureAdapter(fqname, fnc=None): - '''Function decorator that marks it as a converter of specified + """Function decorator that marks it as a converter of specified object type to StructureAdapter class in diffpy.srreal. The registered structure object types can be afterwards directly used with calculators in diffpy.srreal as they would be implicitly converted to the internal @@ -75,14 +79,17 @@ def convertMyStructure(stru): ... See diffpy.srreal.structureconverters module for usage example. - ''' + """ + def __wrapper(fnc): _adapter_converters_registry[fqname] = fnc return fnc + if fnc is None: return __wrapper return __wrapper(fnc) + _adapter_converters_registry = {} # import of srreal_ext calls RegisterStructureAdapter, therefore it has @@ -101,8 +108,17 @@ def __wrapper(fnc): del _emptyStructureAdapter # silence the pyflakes syntax checker -assert all((Atom, AtomicStructureAdapter, PeriodicStructureAdapter, - CrystalStructureAdapter, StructureDifference, - nometa, nosymmetry, BaseBondGenerator)) +assert all( + ( + Atom, + AtomicStructureAdapter, + PeriodicStructureAdapter, + CrystalStructureAdapter, + StructureDifference, + nometa, + nosymmetry, + BaseBondGenerator, + ) +) # End of file diff --git a/src/diffpy/srreal/structureconverters.py b/src/diffpy/srreal/structureconverters.py index e504587d..210a2bbb 100644 --- a/src/diffpy/srreal/structureconverters.py +++ b/src/diffpy/srreal/structureconverters.py @@ -24,12 +24,13 @@ # Converter for Structure class from diffpy.structure ------------------------ + # TODO prune in version 1.4. -@RegisterStructureAdapter('diffpy.Structure.structure.Structure') -@RegisterStructureAdapter('diffpy.structure.structure.Structure') +@RegisterStructureAdapter("diffpy.Structure.structure.Structure") +@RegisterStructureAdapter("diffpy.structure.structure.Structure") def convertDiffPyStructure(stru): - 'Adapt Structure class from diffpy.structure package.' - haslattice = ((1, 1, 1, 90, 90, 90) != stru.lattice.abcABG()) + "Adapt Structure class from diffpy.structure package." + haslattice = (1, 1, 1, 90, 90, 90) != stru.lattice.abcABG() isperiodic = haslattice hasmeta = _DiffPyStructureMetadata.hasMetadata(stru) if hasmeta: @@ -46,18 +47,20 @@ def convertDiffPyStructure(stru): _fetchDiffPyStructureData(adpt, stru) return adpt + # Converters for Molecule and Crystal from pyobjcryst ------------------------ from diffpy.srreal.srreal_ext import convertObjCrystMolecule -RegisterStructureAdapter( - 'pyobjcryst._pyobjcryst.Molecule', convertObjCrystMolecule) + +RegisterStructureAdapter("pyobjcryst._pyobjcryst.Molecule", convertObjCrystMolecule) from diffpy.srreal.srreal_ext import convertObjCrystCrystal -RegisterStructureAdapter( - 'pyobjcryst._pyobjcryst.Crystal', convertObjCrystCrystal) + +RegisterStructureAdapter("pyobjcryst._pyobjcryst.Crystal", convertObjCrystCrystal) # Adapter classes and helpers for diffpy.structure class --------------------- + class _DiffPyStructureMetadata(object): "Base class for handling metadata information in the pdffit attribute." @@ -66,40 +69,38 @@ class _DiffPyStructureMetadata(object): @staticmethod def hasMetadata(stru): - """True if Structure object carries data in its pdffit attribute. - """ - rv = hasattr(stru, 'pdffit') and bool(stru.pdffit) + """True if Structure object carries data in its pdffit attribute.""" + rv = hasattr(stru, "pdffit") and bool(stru.pdffit) return rv - def _customPQConfig(self, pqobj): - """Apply PDF-related metadata if defined in PDFFit structure format. - """ + """Apply PDF-related metadata if defined in PDFFit structure format.""" pqname = type(pqobj).__name__ - if not pqname in ('PDFCalculator', 'DebyePDFCalculator'): return - if not self.pdffit: return + if not pqname in ("PDFCalculator", "DebyePDFCalculator"): + return + if not self.pdffit: + return # scale envtps = pqobj.usedenvelopetypes - if 'scale' not in envtps: - pqobj.addEnvelope('scale') - pqobj.scale = self.pdffit['scale'] + if "scale" not in envtps: + pqobj.addEnvelope("scale") + pqobj.scale = self.pdffit["scale"] # spdiameter if "spdiameter" in self.pdffit: - if not 'sphericalshape' in envtps: - pqobj.addEnvelope('sphericalshape') - pqobj.spdiameter = self.pdffit['spdiameter'] + if not "sphericalshape" in envtps: + pqobj.addEnvelope("sphericalshape") + pqobj.spdiameter = self.pdffit["spdiameter"] # stepcut if "stepcut" in self.pdffit: - if not 'stepcut' in envtps: - pqobj.addEnvelope('stepcut') - pqobj.stepcut = self.pdffit['stepcut'] + if not "stepcut" in envtps: + pqobj.addEnvelope("stepcut") + pqobj.stepcut = self.pdffit["stepcut"] # delta1, delta2 - set these only when using JeongPeakWidth model if pqobj.peakwidthmodel.type() == "jeong": - pqobj.delta1 = self.pdffit['delta1'] - pqobj.delta2 = self.pdffit['delta2'] + pqobj.delta1 = self.pdffit["delta1"] + pqobj.delta2 = self.pdffit["delta2"] return - def _fetchMetadata(self, stru): """Copy data from the pdffit attribute of diffpy Structure object @@ -114,16 +115,15 @@ def _fetchMetadata(self, stru): self.pdffit.update(stru.pdffit) return + # end of class _DiffPyStructureMetadata -class DiffPyStructureAtomicAdapter( - _DiffPyStructureMetadata, AtomicStructureAdapter): +class DiffPyStructureAtomicAdapter(_DiffPyStructureMetadata, AtomicStructureAdapter): pass -class DiffPyStructurePeriodicAdapter( - _DiffPyStructureMetadata, PeriodicStructureAdapter): +class DiffPyStructurePeriodicAdapter(_DiffPyStructureMetadata, PeriodicStructureAdapter): pass @@ -136,6 +136,7 @@ def _fetchDiffPyStructureData(adpt, stru): No return value. """ from diffpy.srreal.srreal_ext import Atom as AdapterAtom + # copy atoms del adpt[:] adpt.reserve(len(stru)) @@ -148,10 +149,11 @@ def _fetchDiffPyStructureData(adpt, stru): aa.xyz_cartn = a0.xyz aa.uij_cartn = a0.U adpt.append(aa) - if hasattr(adpt, 'setLatPar'): + if hasattr(adpt, "setLatPar"): adpt.setLatPar(*stru.lattice.abcABG()) for aa in adpt: adpt.toCartesian(aa) return + # End of file diff --git a/src/diffpy/srreal/tests/__init__.py b/src/diffpy/srreal/tests/__init__.py index f1b64d71..8f9447cf 100644 --- a/src/diffpy/srreal/tests/__init__.py +++ b/src/diffpy/srreal/tests/__init__.py @@ -25,8 +25,8 @@ del logging -def testsuite(pattern=''): - '''Create a unit tests suite for diffpy.srreal package. +def testsuite(pattern=""): + """Create a unit tests suite for diffpy.srreal package. Parameters ---------- @@ -39,14 +39,15 @@ def testsuite(pattern=''): ------- suite : `unittest.TestSuite` The TestSuite object containing the matching tests. - ''' + """ import re from os.path import dirname from itertools import chain from pkg_resources import resource_filename + loader = unittest.defaultTestLoader - thisdir = resource_filename(__name__, '') - depth = __name__.count('.') + 1 + thisdir = resource_filename(__name__, "") + depth = __name__.count(".") + 1 topdir = thisdir for i in range(depth): topdir = dirname(topdir) @@ -56,12 +57,12 @@ def testsuite(pattern=''): rx = re.compile(pattern) tsuites = list(chain.from_iterable(suite_all)) tsok = all(isinstance(ts, unittest.TestSuite) for ts in tsuites) - if not tsok: # pragma: no cover + if not tsok: # pragma: no cover return suite_all tcases = chain.from_iterable(tsuites) for tc in tcases: - tcwords = tc.id().split('.') - shortname = '.'.join(tcwords[-3:]) + tcwords = tc.id().split(".") + shortname = ".".join(tcwords[-3:]) if rx.search(shortname): suite.addTest(tc) # verify all tests are found for an empty pattern. @@ -70,12 +71,12 @@ def testsuite(pattern=''): def test(): - '''Execute all unit tests for the diffpy.srreal package. + """Execute all unit tests for the diffpy.srreal package. Returns ------- result : `unittest.TestResult` - ''' + """ suite = testsuite() runner = unittest.TextTestRunner() result = runner.run(suite) diff --git a/src/diffpy/srreal/tests/debug.py b/src/diffpy/srreal/tests/debug.py index be3127be..eb48ae31 100644 --- a/src/diffpy/srreal/tests/debug.py +++ b/src/diffpy/srreal/tests/debug.py @@ -22,10 +22,11 @@ """ -if __name__ == '__main__': +if __name__ == "__main__": import sys from diffpy.srreal.tests import testsuite - pattern = sys.argv[1] if len(sys.argv) > 1 else '' + + pattern = sys.argv[1] if len(sys.argv) > 1 else "" suite = testsuite(pattern) suite.debug() diff --git a/src/diffpy/srreal/tests/run.py b/src/diffpy/srreal/tests/run.py index 6f88d607..efbe2456 100644 --- a/src/diffpy/srreal/tests/run.py +++ b/src/diffpy/srreal/tests/run.py @@ -19,15 +19,18 @@ """ -if __name__ == '__main__': +if __name__ == "__main__": import sys + # show warnings by default if not sys.warnoptions: import os, warnings + warnings.simplefilter("default") # also affect subprocesses os.environ["PYTHONWARNINGS"] = "default" from diffpy.srreal.tests import test + # produce zero exit code for a successful test sys.exit(not test().wasSuccessful()) diff --git a/src/diffpy/srreal/tests/testatomradiitable.py b/src/diffpy/srreal/tests/testatomradiitable.py index c96a6fb8..d9e7ee98 100644 --- a/src/diffpy/srreal/tests/testatomradiitable.py +++ b/src/diffpy/srreal/tests/testatomradiitable.py @@ -12,6 +12,7 @@ # ---------------------------------------------------------------------------- + class TestAtomRadiiTable(unittest.TestCase): def setUp(self): @@ -23,94 +24,86 @@ def tearDown(self): return def test_pickling(self): - '''check pickling and unpickling of AtomRadiiTable. - ''' + """check pickling and unpickling of AtomRadiiTable.""" ctb1 = pickle.loads(pickle.dumps(self.ctb)) self.assertTrue(type(ctb1) is ConstantRadiiTable) self.assertEqual({}, ctb1.getAllCustom()) - self.ctb.setCustom('Na', 1.3) - self.ctb.foobar = 'foo' + self.ctb.setCustom("Na", 1.3) + self.ctb.foobar = "foo" self.ctb.setDefault(3.7) ctb2 = pickle.loads(pickle.dumps(self.ctb)) - self.assertEqual({'Na' : 1.3}, ctb2.getAllCustom()) - self.assertFalse(hasattr(ctb2, 'foobar')) + self.assertEqual({"Na": 1.3}, ctb2.getAllCustom()) + self.assertFalse(hasattr(ctb2, "foobar")) self.assertEqual(3.7, ctb2.getDefault()) return def test__standardLookup(self): - """check AtomRadiiTable._standardLookup() - """ - self.assertRaises(RuntimeError, self.rtb._standardLookup, - 'anything') - self.assertEqual(0.0, self.ctb._standardLookup('anything')) + """check AtomRadiiTable._standardLookup()""" + self.assertRaises(RuntimeError, self.rtb._standardLookup, "anything") + self.assertEqual(0.0, self.ctb._standardLookup("anything")) self.ctb.setDefault(7.3) - self.assertEqual(7.3, self.ctb._standardLookup('anything')) + self.assertEqual(7.3, self.ctb._standardLookup("anything")) return def test_fromString(self): - """check AtomRadiiTable.fromString() - """ - self.rtb.fromString('H:0.33, B:0.42') - self.assertEqual({'H' : 0.33, 'B' : 0.42}, self.rtb.getAllCustom()) - self.assertRaises(ValueError, self.rtb.fromString, - 'C:2.3, U:asdf') - self.assertEqual({'H' : 0.33, 'B' : 0.42}, self.rtb.getAllCustom()) - self.rtb.fromString('C:2.3,,,') + """check AtomRadiiTable.fromString()""" + self.rtb.fromString("H:0.33, B:0.42") + self.assertEqual({"H": 0.33, "B": 0.42}, self.rtb.getAllCustom()) + self.assertRaises(ValueError, self.rtb.fromString, "C:2.3, U:asdf") + self.assertEqual({"H": 0.33, "B": 0.42}, self.rtb.getAllCustom()) + self.rtb.fromString("C:2.3,,,") self.assertEqual(3, len(self.rtb.getAllCustom())) - self.assertEqual(2.3, self.rtb.lookup('C')) - self.rtb.fromString('H:3.3') + self.assertEqual(2.3, self.rtb.lookup("C")) + self.rtb.fromString("H:3.3") self.assertEqual(3, len(self.rtb.getAllCustom())) - self.assertEqual(3.3, self.rtb.lookup('H')) + self.assertEqual(3.3, self.rtb.lookup("H")) return def test_getAllCustom(self): - """check AtomRadiiTable.getAllCustom() - """ + """check AtomRadiiTable.getAllCustom()""" self.assertEqual({}, self.rtb.getAllCustom()) return def test_lookup(self): - """check AtomRadiiTable.lookup() - """ - self.assertRaises(RuntimeError, self.rtb.lookup, 'C') - self.assertEqual(0.0, self.ctb.lookup('C')) - self.rtb.setCustom('C', 1.23) - self.assertEqual(1.23, self.rtb.lookup('C')) + """check AtomRadiiTable.lookup()""" + self.assertRaises(RuntimeError, self.rtb.lookup, "C") + self.assertEqual(0.0, self.ctb.lookup("C")) + self.rtb.setCustom("C", 1.23) + self.assertEqual(1.23, self.rtb.lookup("C")) return def test_resetCustom(self): - """check AtomRadiiTable.resetCustom() - """ - self.rtb.setCustom('C', 1.23) + """check AtomRadiiTable.resetCustom()""" + self.rtb.setCustom("C", 1.23) self.assertTrue(self.rtb.getAllCustom()) self.rtb.resetAll() self.assertFalse(self.rtb.getAllCustom()) return def test_setCustom(self): - """check AtomRadiiTable.setCustom() - """ - self.rtb.setCustom('C', 1.23) - self.assertEqual(1.23, self.rtb.lookup('C')) - self.rtb.setCustom('C', 3.3) - self.assertEqual(3.3, self.rtb.lookup('C')) + """check AtomRadiiTable.setCustom()""" + self.rtb.setCustom("C", 1.23) + self.assertEqual(1.23, self.rtb.lookup("C")) + self.rtb.setCustom("C", 3.3) + self.assertEqual(3.3, self.rtb.lookup("C")) return def test_toString(self): - """check AtomRadiiTable.toString() - """ + """check AtomRadiiTable.toString()""" rtb = self.rtb - self.assertEqual('', rtb.toString()) - self.assertEqual('', rtb.toString('; ')) - rtb.fromString('C : 1.5, B:2.0') - self.assertEqual('B:2,C:1.5', rtb.toString()) - self.assertEqual('B:2; C:1.5', rtb.toString('; ')) + self.assertEqual("", rtb.toString()) + self.assertEqual("", rtb.toString("; ")) + rtb.fromString("C : 1.5, B:2.0") + self.assertEqual("B:2,C:1.5", rtb.toString()) + self.assertEqual("B:2; C:1.5", rtb.toString("; ")) return + # End of class TestAtomRadiiTable # ---------------------------------------------------------------------------- + @unittest.skipUnless(has_periodictable, _msg_noperiodictable) class TestCovalentRadiiTable(unittest.TestCase): @@ -122,28 +115,25 @@ def tearDown(self): return def test_pickling(self): - '''check pickling and unpickling of CovalentRadiiTable. - ''' + """check pickling and unpickling of CovalentRadiiTable.""" rtb1 = pickle.loads(pickle.dumps(self.rtb)) self.assertTrue(type(rtb1) is CovalentRadiiTable) self.assertEqual({}, rtb1.getAllCustom()) - self.rtb.setCustom('Na', 1.3) - self.rtb.foobar = 'foo' + self.rtb.setCustom("Na", 1.3) + self.rtb.foobar = "foo" rtb2 = pickle.loads(pickle.dumps(self.rtb)) - self.assertEqual({'Na' : 1.3}, rtb2.getAllCustom()) - self.assertEqual('foo', rtb2.foobar) + self.assertEqual({"Na": 1.3}, rtb2.getAllCustom()) + self.assertEqual("foo", rtb2.foobar) return def test__standardLookup(self): - """check CovalentRadiiTable._standardLookup() - """ - self.assertEqual(1.22, self.rtb._standardLookup('Ga')) + """check CovalentRadiiTable._standardLookup()""" + self.assertEqual(1.22, self.rtb._standardLookup("Ga")) return def test_create(self): - """check CovalentRadiiTable.create() - """ - self.rtb.setCustom('Na', 1.3) + """check CovalentRadiiTable.create()""" + self.rtb.setCustom("Na", 1.3) rtb2 = self.rtb.create() self.assertTrue(isinstance(rtb2, CovalentRadiiTable)) self.assertEqual(1, len(self.rtb.getAllCustom())) @@ -151,66 +141,60 @@ def test_create(self): return def test_clone(self): - """check CovalentRadiiTable.clone() - """ - self.rtb.setCustom('Na', 1.3) + """check CovalentRadiiTable.clone()""" + self.rtb.setCustom("Na", 1.3) rtb2 = self.rtb.clone() self.assertTrue(isinstance(rtb2, CovalentRadiiTable)) self.assertEqual(1, len(rtb2.getAllCustom())) - self.assertEqual(1.3, rtb2.lookup('Na')) + self.assertEqual(1.3, rtb2.lookup("Na")) return def test_fromString(self): - """check CovalentRadiiTable.fromString() - """ - self.rtb.fromString('Ga:2.22') - self.assertEqual(2.22, self.rtb.lookup('Ga')) + """check CovalentRadiiTable.fromString()""" + self.rtb.fromString("Ga:2.22") + self.assertEqual(2.22, self.rtb.lookup("Ga")) return def test_getAllCustom(self): - """check CovalentRadiiTable.getAllCustom() - """ + """check CovalentRadiiTable.getAllCustom()""" self.assertEqual({}, self.rtb.getAllCustom()) return def test_lookup(self): - """check CovalentRadiiTable.lookup() - """ - self.assertEqual(1.22, self.rtb.lookup('Ga')) - self.rtb.fromString('Ga:2.22') - self.assertEqual(2.22, self.rtb.lookup('Ga')) + """check CovalentRadiiTable.lookup()""" + self.assertEqual(1.22, self.rtb.lookup("Ga")) + self.rtb.fromString("Ga:2.22") + self.assertEqual(2.22, self.rtb.lookup("Ga")) return def test_resetCustom(self): - """check CovalentRadiiTable.resetCustom() - """ - self.rtb.fromString('B:2.33, Ga:2.22') - self.rtb.resetCustom('B') - self.rtb.resetCustom('nada') + """check CovalentRadiiTable.resetCustom()""" + self.rtb.fromString("B:2.33, Ga:2.22") + self.rtb.resetCustom("B") + self.rtb.resetCustom("nada") self.assertEqual(1, len(self.rtb.getAllCustom())) - self.assertEqual(0.84, self.rtb.lookup('B')) - self.assertEqual(2.22, self.rtb.lookup('Ga')) + self.assertEqual(0.84, self.rtb.lookup("B")) + self.assertEqual(2.22, self.rtb.lookup("Ga")) return def test_setCustom(self): - """check CovalentRadiiTable.setCustom() - """ - self.assertEqual(0.84, self.rtb.lookup('B')) - self.rtb.setCustom('B', 0.9) - self.assertEqual(0.9, self.rtb.lookup('B')) + """check CovalentRadiiTable.setCustom()""" + self.assertEqual(0.84, self.rtb.lookup("B")) + self.rtb.setCustom("B", 0.9) + self.assertEqual(0.9, self.rtb.lookup("B")) return def test_toString(self): - """check CovalentRadiiTable.toString() - """ - self.assertEqual('', self.rtb.toString(';---')) + """check CovalentRadiiTable.toString()""" + self.assertEqual("", self.rtb.toString(";---")) return + # End of class TestCovalentRadiiTable # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testattributes.py b/src/diffpy/srreal/tests/testattributes.py index 7c7e2f0d..cb4f2243 100644 --- a/src/diffpy/srreal/tests/testattributes.py +++ b/src/diffpy/srreal/tests/testattributes.py @@ -12,20 +12,18 @@ from diffpy.srreal.pairquantity import PairQuantity from diffpy.srreal.pdfcalculator import PDFCalculator + ############################################################################## class TestAttributes(unittest.TestCase): def setUp(self): return - def tearDown(self): return - def test___setattr__(self): - """check Attributes.__setattr__() - """ + """check Attributes.__setattr__()""" # normal attribute a = Attributes() a.x = 45 @@ -40,123 +38,112 @@ def test___setattr__(self): self.assertEqual(27, a._getDoubleAttr("x")) return - def test___getattr__(self): - """check Attributes.__getattr__() - """ + """check Attributes.__getattr__()""" a = Attributes() - self.assertRaises(AttributeError, getattr, a, 'invalid') + self.assertRaises(AttributeError, getattr, a, "invalid") a.x = 11 self.assertEqual(11, a.x) pdfc = PDFCalculator() - pdfc._setDoubleAttr('rmax', 12.34) + pdfc._setDoubleAttr("rmax", 12.34) self.assertEqual(12.34, pdfc.rmax) return - def test_garbage_collection(self): - """check garbage collection for Python defined Attributes - """ + """check garbage collection for Python defined Attributes""" # check if attributes are garbage collected pq = PairQuantity() wpq = weakref.ref(pq) self.assertFalse(wpq() is None) - pq._registerDoubleAttribute('foo') + pq._registerDoubleAttribute("foo") pq.foo = 45 - self.assertEqual(45, pq._getDoubleAttr('foo')) + self.assertEqual(45, pq._getDoubleAttr("foo")) del pq self.assertTrue(wpq() is None) return - def test__getDoubleAttr(self): - """check Attributes._getDoubleAttr() - """ + """check Attributes._getDoubleAttr()""" pdfc = PDFCalculator() pdfc.foo = 11 - self.assertRaises(AttributeError, pdfc._getDoubleAttr, 'foo') - pdfc._registerDoubleAttribute('foo') - self.assertEqual(11, pdfc._getDoubleAttr('foo')) + self.assertRaises(AttributeError, pdfc._getDoubleAttr, "foo") + pdfc._registerDoubleAttribute("foo") + self.assertEqual(11, pdfc._getDoubleAttr("foo")) pdfc.rmax = 22 - self.assertEqual(22, pdfc._getDoubleAttr('rmax')) - setattr(pdfc, 'rmax', 23) - self.assertEqual(23, pdfc._getDoubleAttr('rmax')) - self.assertRaises(Exception, setattr, pdfc, 'rmax', 'xxx') + self.assertEqual(22, pdfc._getDoubleAttr("rmax")) + setattr(pdfc, "rmax", 23) + self.assertEqual(23, pdfc._getDoubleAttr("rmax")) + self.assertRaises(Exception, setattr, pdfc, "rmax", "xxx") return - def test__hasDoubleAttr(self): - """check Attributes._hasDoubleAttr() - """ + """check Attributes._hasDoubleAttr()""" a = Attributes() a.foo = 45 - self.assertFalse(a._hasDoubleAttr('foo')) - a._registerDoubleAttribute('foo') - self.assertTrue(a._hasDoubleAttr('foo')) + self.assertFalse(a._hasDoubleAttr("foo")) + a._registerDoubleAttribute("foo") + self.assertTrue(a._hasDoubleAttr("foo")) return - def test__namesOfDoubleAttributes(self): - """check Attributes._namesOfDoubleAttributes() - """ + """check Attributes._namesOfDoubleAttributes()""" a = Attributes() self.assertEqual(0, len(a._namesOfDoubleAttributes())) pq = PairQuantity() self.assertNotEqual(0, len(pq._namesOfDoubleAttributes())) - self.assertFalse('bar' in pq._namesOfDoubleAttributes()) - pq._registerDoubleAttribute('bar') - self.assertTrue('bar' in pq._namesOfDoubleAttributes()) + self.assertFalse("bar" in pq._namesOfDoubleAttributes()) + pq._registerDoubleAttribute("bar") + self.assertTrue("bar" in pq._namesOfDoubleAttributes()) return - def test__namesOfWritableDoubleAttributes(self): - """check Attributes._namesOfDoubleAttributes() - """ + """check Attributes._namesOfDoubleAttributes()""" a = Attributes() self.assertEqual(0, len(a._namesOfDoubleAttributes())) - a._registerDoubleAttribute('bar', lambda obj: 13) - self.assertEqual(13, a._getDoubleAttr('bar')) + a._registerDoubleAttribute("bar", lambda obj: 13) + self.assertEqual(13, a._getDoubleAttr("bar")) self.assertEqual(13, a.bar) self.assertEqual(1, len(a._namesOfDoubleAttributes())) self.assertEqual(0, len(a._namesOfWritableDoubleAttributes())) pdfc = PDFCalculator() - self.assertTrue('extendedrmin' in pdfc._namesOfDoubleAttributes()) - self.assertTrue('extendedrmax' in pdfc._namesOfDoubleAttributes()) + self.assertTrue("extendedrmin" in pdfc._namesOfDoubleAttributes()) + self.assertTrue("extendedrmax" in pdfc._namesOfDoubleAttributes()) nwda = pdfc._namesOfWritableDoubleAttributes() - self.assertFalse('extendedrmin' in nwda) - self.assertFalse('extendedrmax' in nwda) + self.assertFalse("extendedrmin" in nwda) + self.assertFalse("extendedrmax" in nwda) return - def test__registerDoubleAttribute(self): - """check Attributes._registerDoubleAttribute() - """ - d = {'g_called' : False, 's_called' : False, 'value' : 0} + """check Attributes._registerDoubleAttribute()""" + d = {"g_called": False, "s_called": False, "value": 0} + def g(obj): - d['g_called'] = True - return d['value'] + d["g_called"] = True + return d["value"] + def s(obj, value): - d['s_called'] = True - d['value'] = value + d["s_called"] = True + d["value"] = value return + a = Attributes() wa = weakref.ref(a) - a._registerDoubleAttribute('a1', g, s) - self.assertFalse('a1' in a.__dict__) - self.assertFalse(d['g_called']) - self.assertFalse(d['s_called']) + a._registerDoubleAttribute("a1", g, s) + self.assertFalse("a1" in a.__dict__) + self.assertFalse(d["g_called"]) + self.assertFalse(d["s_called"]) self.assertEqual(0, a.a1) - self.assertTrue(d['g_called']) - self.assertFalse(d['s_called']) + self.assertTrue(d["g_called"]) + self.assertFalse(d["s_called"]) a.a1 = 47 - self.assertTrue(d['s_called']) - self.assertEqual(47, d['value']) - self.assertTrue(hasattr(a, 'a1')) - a._registerDoubleAttribute('a1readonly', g) + self.assertTrue(d["s_called"]) + self.assertEqual(47, d["value"]) + self.assertTrue(hasattr(a, "a1")) + a._registerDoubleAttribute("a1readonly", g) self.assertEqual(47, a.a1readonly) - self.assertTrue(hasattr(a, 'a1readonly')) - self.assertRaises(AttributeError, a._setDoubleAttr, 'a1readonly', 7) - self.assertRaises(AttributeError, setattr, a, 'a1readonly', 5) + self.assertTrue(hasattr(a, "a1readonly")) + self.assertRaises(AttributeError, a._setDoubleAttr, "a1readonly", 7) + self.assertRaises(AttributeError, setattr, a, "a1readonly", 5) self.assertEqual(47, a.a1readonly) a.a1 = 9 self.assertEqual(9, a.a1readonly) @@ -166,19 +153,18 @@ def s(obj, value): self.assertTrue(wa() is None) return - def test__setDoubleAttr(self): - """check Attributes._setDoubleAttr() - """ + """check Attributes._setDoubleAttr()""" pdfc = PDFCalculator() - pdfc._setDoubleAttr('scale', 1.23) - self.assertFalse('scale' in pdfc.__dict__) + pdfc._setDoubleAttr("scale", 1.23) + self.assertFalse("scale" in pdfc.__dict__) self.assertEqual(1.23, pdfc.scale) return + # End of class TestAttributes -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testbondcalculator.py b/src/diffpy/srreal/tests/testbondcalculator.py index fba47a37..76164a2a 100644 --- a/src/diffpy/srreal/tests/testbondcalculator.py +++ b/src/diffpy/srreal/tests/testbondcalculator.py @@ -16,26 +16,24 @@ # ---------------------------------------------------------------------------- + class TestBondCalculator(unittest.TestCase): def setUp(self): self.bdc = BondCalculator() - if not hasattr(self, 'rutile'): - type(self).rutile = loadDiffPyStructure('rutile.cif') - if not hasattr(self, 'nickel'): - type(self).nickel = loadDiffPyStructure('Ni.stru') - if not hasattr(self, 'niprim'): - type(self).niprim = loadDiffPyStructure('Ni_primitive.stru') + if not hasattr(self, "rutile"): + type(self).rutile = loadDiffPyStructure("rutile.cif") + if not hasattr(self, "nickel"): + type(self).nickel = loadDiffPyStructure("Ni.stru") + if not hasattr(self, "niprim"): + type(self).niprim = loadDiffPyStructure("Ni_primitive.stru") return - def tearDown(self): return - def test___init__(self): - """check BondCalculator.__init__() - """ + """check BondCalculator.__init__()""" self.assertEqual(0, self.bdc.rmin) self.assertEqual(5, self.bdc.rmax) self.assertEqual(0, len(self.bdc.distances)) @@ -45,10 +43,8 @@ def test___init__(self): self.assertRaises(TypeError, BondCalculator, invalid=55) return - def test___call__(self): - """check BondCalculator.__call__() - """ + """check BondCalculator.__call__()""" bdc = self.bdc bdc.rmax = 0 self.assertEqual(0, len(bdc(self.rutile))) @@ -62,10 +58,8 @@ def test___call__(self): self.assertEqual(2, bdc.rmax) return - def test_pickling(self): - '''check pickling and unpickling of BondCalculator. - ''' + """check pickling and unpickling of BondCalculator.""" bdc = self.bdc bdc.rmin = 0.1 bdc.rmax = 12.3 @@ -79,14 +73,13 @@ def test_pickling(self): self.assertFalse(bdc1.getPairMask(1, 2)) self.assertTrue(bdc1.getPairMask(0, 0)) self.assertTrue(numpy.array_equal(bdc.distances, bdc1.distances)) - self.assertRaises(RuntimeError, pickle_with_attr, bdc, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, bdc, foo="bar") return - def test_pickling_derived_structure(self): - '''check pickling of BondCalculator with DerivedStructureAdapter. - ''' + """check pickling of BondCalculator with DerivedStructureAdapter.""" from diffpy.srreal.tests.testutils import DerivedStructureAdapter + bdc = self.bdc stru0 = DerivedStructureAdapter() bdc.setStructure(stru0) @@ -100,20 +93,17 @@ def test_pickling_derived_structure(self): self.assertEqual(1, stru1.cpqcount) return - def test_distances(self): - """check BondCalculator.distances - """ + """check BondCalculator.distances""" self.bdc.eval(self.nickel) dst = self.bdc.distances - self.assertTrue(numpy.array_equal(dst, - BondCalculator()(self.nickel))) + self.assertTrue(numpy.array_equal(dst, BondCalculator()(self.nickel))) self.assertTrue(numpy.array_equal(dst, numpy.sort(dst))) self.bdc.maskAllPairs(False) for i in range(4): self.bdc.setPairMask(0, i, True) dst0a = self.bdc(self.nickel) - idx0a = (self.bdc.sites0 == 0) + idx0a = self.bdc.sites0 == 0 self.bdc.maskAllPairs(False) for i in range(4): self.bdc.setPairMask(3, i, True) @@ -124,20 +114,16 @@ def test_distances(self): self.assertTrue(numpy.allclose(dst0a[idx0a], dstp)) return - def test_directions(self): - """check BondCalculator.directions - """ + """check BondCalculator.directions""" dst = self.bdc(self.rutile) drs = self.bdc.directions nms = numpy.sqrt(numpy.sum(numpy.power(drs, 2), axis=1)) self.assertTrue(numpy.allclose(dst, nms)) return - def test_sites(self): - """check BondCalculator.sites - """ + """check BondCalculator.sites""" bdc = self.bdc dst = bdc(self.rutile) self.assertEqual(len(dst), len(bdc.sites0)) @@ -146,8 +132,7 @@ def test_sites(self): self.assertEqual(5, numpy.max(bdc.sites0)) self.assertEqual(0, numpy.min(bdc.sites1)) self.assertEqual(5, numpy.max(bdc.sites1)) - dij = [(tuple(d) + (i0, i1)) for d, i0, i1 in zip( - bdc.directions, bdc.sites0, bdc.sites1)] + dij = [(tuple(d) + (i0, i1)) for d, i0, i1 in zip(bdc.directions, bdc.sites0, bdc.sites1)] self.assertEqual(len(dij), len(set(dij))) bdc.maskAllPairs(False) bdc(self.rutile) @@ -158,16 +143,14 @@ def test_sites(self): self.assertEqual(set([3]), set(bdc.sites0).union(bdc.sites1)) return - def test_types(self): - """check BondCalculator.types - """ + """check BondCalculator.types""" bdc = self.bdc dst = bdc(self.rutile) self.assertEqual(len(dst), len(bdc.types0)) self.assertEqual(len(dst), len(bdc.types1)) - self.assertEqual(set(('Ti', 'O')), set(bdc.types0)) - self.assertEqual(set(('Ti', 'O')), set(bdc.types1)) + self.assertEqual(set(("Ti", "O")), set(bdc.types0)) + self.assertEqual(set(("Ti", "O")), set(bdc.types1)) self.assertFalse((bdc.types0 == bdc.types1).all()) bdc.maskAllPairs(False) bdc(self.rutile) @@ -176,13 +159,11 @@ def test_types(self): bdc.setPairMask(3, 3, True) bdc(self.rutile) self.assertTrue(len(bdc.types0)) - self.assertEqual(set(['O']), set(bdc.types0).union(set(bdc.types1))) + self.assertEqual(set(["O"]), set(bdc.types0).union(set(bdc.types1))) return - def test_filterCone(self): - """check BondCalculator.filterCone() - """ + """check BondCalculator.filterCone()""" bdc = self.bdc bdc.rmax = 2.5 self.assertEqual(12, len(bdc(self.niprim))) @@ -199,10 +180,8 @@ def test_filterCone(self): self.assertEqual(12, len(bdc(self.niprim))) return - def test_filterOff(self): - """check BondCalculator.filterOff() - """ + """check BondCalculator.filterOff()""" bdc = self.bdc bdc.rmax = 2.5 bdc.filterCone([1, 2, 3], -1) @@ -211,10 +190,8 @@ def test_filterOff(self): self.assertEqual(12, len(bdc(self.niprim))) return - def test_setPairMask(self): - '''check different setPairMask arguments. - ''' + """check different setPairMask arguments.""" bdc = self.bdc dall = bdc(self.nickel) bdc.maskAllPairs(False) @@ -230,39 +207,37 @@ def test_setPairMask(self): dst0c = bdc(self.nickel) self.assertTrue(numpy.array_equal(dst0a, dst0c)) bdc.maskAllPairs(False) - bdc.setPairMask(0, 'all', True) + bdc.setPairMask(0, "all", True) dst0d = bdc(self.nickel) self.assertTrue(numpy.array_equal(dst0a, dst0d)) - bdc.setPairMask('all', 'all', False) + bdc.setPairMask("all", "all", False) self.assertEqual(0, len(bdc(self.nickel))) - bdc.setPairMask('all', range(4), True) + bdc.setPairMask("all", range(4), True) dall2 = bdc(self.nickel) self.assertTrue(numpy.array_equal(dall, dall2)) - self.assertRaises(ValueError, bdc.setPairMask, 'fooo', 2, True) - self.assertRaises(ValueError, bdc.setPairMask, 'aLL', 2, True) + self.assertRaises(ValueError, bdc.setPairMask, "fooo", 2, True) + self.assertRaises(ValueError, bdc.setPairMask, "aLL", 2, True) return - def test_setTypeMask(self): - '''check different setTypeMask arguments. - ''' + """check different setTypeMask arguments.""" bdc = self.bdc dall = bdc(self.rutile) - bdc.setTypeMask('all', 'All', False) + bdc.setTypeMask("all", "All", False) self.assertTrue(numpy.array_equal(dall, bdc(self.rutile))) - bdc.setTypeMask('all', 'ALL', False) + bdc.setTypeMask("all", "ALL", False) self.assertEqual(0, len(bdc(self.rutile))) bdc.maskAllPairs(True) - bdc.setTypeMask('Ti', ['O'], True, others=False) + bdc.setTypeMask("Ti", ["O"], True, others=False) bdc() tps = set(zip(bdc.types0, bdc.types1)) self.assertEqual(2, len(tps)) - self.assertTrue(('Ti', 'O') in tps) - self.assertTrue(('O', 'Ti') in tps) - bdc.setTypeMask(['Ti'], self.rutile.element, 0, others=1) + self.assertTrue(("Ti", "O") in tps) + self.assertTrue(("O", "Ti") in tps) + bdc.setTypeMask(["Ti"], self.rutile.element, 0, others=1) bdc() tps = set(zip(bdc.types0, bdc.types1)) - self.assertEqual(set([('O', 'O')]), tps) + self.assertEqual(set([("O", "O")]), tps) return @@ -270,25 +245,23 @@ def test_setTypeMask(self): # ---------------------------------------------------------------------------- + @unittest.skipUnless(has_pyobjcryst, _msg_nopyobjcryst) class TestBondCalculatorObjCryst(unittest.TestCase): def setUp(self): self.bdc = BondCalculator() - if not hasattr(self, 'rutile'): - type(self).rutile = loadObjCrystCrystal('rutile.cif') - if not hasattr(self, 'nickel'): - type(self).nickel = loadObjCrystCrystal('Ni.cif') + if not hasattr(self, "rutile"): + type(self).rutile = loadObjCrystCrystal("rutile.cif") + if not hasattr(self, "nickel"): + type(self).nickel = loadObjCrystCrystal("Ni.cif") return - def tearDown(self): return - def test___call__(self): - """check BondCalculator.__call__() - """ + """check BondCalculator.__call__()""" bdc = self.bdc bdc.rmax = 0 self.assertEqual(0, len(bdc(self.rutile).tolist())) @@ -298,10 +271,8 @@ def test___call__(self): self.assertEqual(12, len(bdc(self.nickel))) return - def test_sites(self): - """check BondCalculator.sites - """ + """check BondCalculator.sites""" bdc = self.bdc dst = bdc(self.rutile) self.assertEqual(len(dst), len(bdc.sites0)) @@ -310,8 +281,7 @@ def test_sites(self): self.assertEqual(1, numpy.max(bdc.sites0)) self.assertEqual(0, numpy.min(bdc.sites1)) self.assertEqual(1, numpy.max(bdc.sites1)) - dij = [(tuple(d) + (i0, i1)) for d, i0, i1 in zip( - bdc.directions, bdc.sites0, bdc.sites1)] + dij = [(tuple(d) + (i0, i1)) for d, i0, i1 in zip(bdc.directions, bdc.sites0, bdc.sites1)] self.assertEqual(len(dij), len(set(dij))) bdc.maskAllPairs(False) bdc(self.rutile) @@ -322,16 +292,14 @@ def test_sites(self): self.assertEqual(set([1]), set(bdc.sites0).union(bdc.sites1)) return - def test_types(self): - """check BondCalculator.types - """ + """check BondCalculator.types""" bdc = self.bdc dst = bdc(self.rutile) self.assertEqual(len(dst), len(bdc.types0)) self.assertEqual(len(dst), len(bdc.types1)) - self.assertEqual(set(('Ti', 'O')), set(bdc.types0)) - self.assertEqual(set(('Ti', 'O')), set(bdc.types1)) + self.assertEqual(set(("Ti", "O")), set(bdc.types0)) + self.assertEqual(set(("Ti", "O")), set(bdc.types1)) self.assertNotEqual(bdc.types0.tolist(), bdc.types1.tolist()) bdc.maskAllPairs(False) bdc(self.rutile) @@ -340,13 +308,11 @@ def test_types(self): bdc.setPairMask(1, 1, True) bdc(self.rutile) self.assertTrue(len(bdc.types0)) - self.assertEqual(set(['O']), set(bdc.types0).union(set(bdc.types1))) + self.assertEqual(set(["O"]), set(bdc.types0).union(set(bdc.types1))) return - def test_filterCone(self): - """check BondCalculator.filterCone() - """ + """check BondCalculator.filterCone()""" bdc = self.bdc bdc.rmax = 2.5 bdc.filterCone([+0.5, +0.5, 0], 1) @@ -362,10 +328,8 @@ def test_filterCone(self): self.assertEqual(12, len(bdc(self.nickel))) return - def test_filterOff(self): - """check BondCalculator.filterOff() - """ + """check BondCalculator.filterOff()""" bdc = self.bdc bdc.rmax = 2.5 bdc.filterCone([1, 2, 3], -1) @@ -374,11 +338,12 @@ def test_filterOff(self): self.assertEqual(12, len(bdc(self.nickel))) return + # End of class TestBondCalculatorObjCryst # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testbvscalculator.py b/src/diffpy/srreal/tests/testbvscalculator.py index 488c6348..62efd7dd 100644 --- a/src/diffpy/srreal/tests/testbvscalculator.py +++ b/src/diffpy/srreal/tests/testbvscalculator.py @@ -11,35 +11,32 @@ from diffpy.srreal.tests.testutils import loadDiffPyStructure from diffpy.srreal.tests.testutils import pickle_with_attr + ############################################################################## class TestBVSCalculator(unittest.TestCase): def setUp(self): self.bvc = BVSCalculator() - if not hasattr(self, 'rutile'): - type(self).rutile = loadDiffPyStructure('rutile.cif') + if not hasattr(self, "rutile"): + type(self).rutile = loadDiffPyStructure("rutile.cif") # rutile.cif does not have charge data, we need to add them here - iondict = {'Ti' : 'Ti4+', 'O' : 'O2-'} - for a in self.rutile: a.element = iondict[a.element] + iondict = {"Ti": "Ti4+", "O": "O2-"} + for a in self.rutile: + a.element = iondict[a.element] return - def tearDown(self): return - def test___init__(self): - """check BVSCalculator.__init__() - """ + """check BVSCalculator.__init__()""" self.assertEqual(1e-5, self.bvc.valenceprecision) bvc1 = BVSCalculator(valenceprecision=1e-4) self.assertEqual(1e-4, bvc1.valenceprecision) return - def test___call__(self): - """check BVSCalculator.__call__() - """ + """check BVSCalculator.__call__()""" vcalc = self.bvc(self.rutile) self.assertEqual(len(self.rutile), len(vcalc)) self.assertEqual(tuple(self.bvc.value), tuple(vcalc)) @@ -51,10 +48,8 @@ def test___call__(self): self.assertTrue(abs((vo - vc) / vo) < 0.1) return - def test_bvdiff(self): - """check BVSCalculator.bvdiff - """ + """check BVSCalculator.bvdiff""" self.bvc(self.rutile) self.assertEqual(6, len(self.bvc.bvdiff)) # rutile is overbonded @@ -62,25 +57,21 @@ def test_bvdiff(self): self.assertTrue(bvd < 0) return - def test_bvmsdiff(self): - """check BVSCalculator.bvmsdiff - """ + """check BVSCalculator.bvmsdiff""" self.assertEqual(0, self.bvc.bvmsdiff) self.bvc(self.rutile) self.assertAlmostEqual(0.0158969, self.bvc.bvmsdiff, 6) return - def test_bvrmsdiff(self): - """check BVSCalculator.bvrmsdiff - """ + """check BVSCalculator.bvrmsdiff""" from math import sqrt + self.assertEqual(0, self.bvc.bvrmsdiff) self.bvc(self.rutile) self.assertTrue(self.bvc.bvrmsdiff > 0) - self.assertAlmostEqual(sqrt(self.bvc.bvmsdiff), - self.bvc.bvrmsdiff, 12) + self.assertAlmostEqual(sqrt(self.bvc.bvmsdiff), self.bvc.bvrmsdiff, 12) bvrmsd0 = self.bvc.bvrmsdiff # check mixed occupancy rutilemix = self.rutile.copy() @@ -93,34 +84,25 @@ def test_bvrmsdiff(self): self.assertAlmostEqual(bvrmsd0, self.bvc.bvrmsdiff, 12) return - def test_eval(self): - """check BVSCalculator.eval() - """ + """check BVSCalculator.eval()""" vcalc = self.bvc.eval(self.rutile) self.assertEqual(tuple(vcalc), tuple(self.bvc.value)) return - def test_valences(self): - """check BVSCalculator.valences - """ + """check BVSCalculator.valences""" self.bvc(self.rutile) - self.assertEqual((4, 4, -2, -2, -2, -2), - tuple(self.bvc.valences)) + self.assertEqual((4, 4, -2, -2, -2, -2), tuple(self.bvc.valences)) return - def test_value(self): - """check BVSCalculator.value - """ + """check BVSCalculator.value""" self.assertEqual(0, len(self.bvc.value)) return - def test_pickling(self): - '''check pickling and unpickling of BVSCalculator. - ''' + """check pickling and unpickling of BVSCalculator.""" bvsc = BVSCalculator() bvsc.rmin = 0.1 bvsc.rmax = 12.3 @@ -130,13 +112,11 @@ def test_pickling(self): self.assertFalse(bvsc is bvsc1) for a in bvsc._namesOfDoubleAttributes(): self.assertEqual(getattr(bvsc, a), getattr(bvsc1, a)) - self.assertRaises(RuntimeError, pickle_with_attr, bvsc, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, bvsc, foo="bar") return - def test_mask_pickling(self): - '''Check if mask gets properly pickled and restored. - ''' + """Check if mask gets properly pickled and restored.""" self.bvc.maskAllPairs(False) self.bvc.setPairMask(0, 1, True) self.assertTrue(False is self.bvc.getPairMask(0, 0)) @@ -146,13 +126,11 @@ def test_mask_pickling(self): self.assertTrue(True is bvc1.getPairMask(0, 1)) return - def test_table_pickling(self): - '''Check if bvparamtable gets correctly pickled and restored. - ''' - self.bvc.bvparamtable.setCustom('A', 1, 'B', -2, 7, 8) + """Check if bvparamtable gets correctly pickled and restored.""" + self.bvc.bvparamtable.setCustom("A", 1, "B", -2, 7, 8) bvc1 = pickle.loads(pickle.dumps(self.bvc)) - bpab = bvc1.bvparamtable.lookup('A+', 'B2-') + bpab = bvc1.bvparamtable.lookup("A+", "B2-") self.assertEqual("A", bpab.atom0) self.assertEqual(1, bpab.valence0) self.assertEqual("B", bpab.atom1) @@ -161,11 +139,10 @@ def test_table_pickling(self): self.assertEqual(8, bpab.B) return - def test_pickling_derived_structure(self): - '''check pickling of BVSCalculator with DerivedStructureAdapter. - ''' + """check pickling of BVSCalculator with DerivedStructureAdapter.""" from diffpy.srreal.tests.testutils import DerivedStructureAdapter + bvc = self.bvc stru0 = DerivedStructureAdapter() bvc.setStructure(stru0) @@ -179,15 +156,13 @@ def test_pickling_derived_structure(self): self.assertEqual(1, stru1.cpqcount) return - def test_table_atom_valence(self): - '''check calculation with defined valences in bvparamtable - ''' + """check calculation with defined valences in bvparamtable""" bvc = self.bvc barerutile = self.rutile.copy() for a in barerutile: - a.element = a.element.rstrip('+-012345678') - self.assertEqual({"Ti" : 2, "O" : 4}, barerutile.composition) + a.element = a.element.rstrip("+-012345678") + self.assertEqual({"Ti": 2, "O": 4}, barerutile.composition) self.assertFalse(any(bvc(barerutile))) bptb = bvc.bvparamtable bptb.setAtomValence("Ti", +4) @@ -201,9 +176,10 @@ def test_table_atom_valence(self): self.assertFalse(any(bvc(barerutile))) return + # End of class TestBVSCalculator -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testdebyepdfcalculator.py b/src/diffpy/srreal/tests/testdebyepdfcalculator.py index 78d8b0ef..9268613f 100644 --- a/src/diffpy/srreal/tests/testdebyepdfcalculator.py +++ b/src/diffpy/srreal/tests/testdebyepdfcalculator.py @@ -13,6 +13,7 @@ from diffpy.srreal.tests.testutils import pickle_with_attr from diffpy.srreal.tests.testpdfcalculator import _maxNormDiff + ############################################################################## class TestDebyePDFCalculator(unittest.TestCase): @@ -22,78 +23,69 @@ class TestDebyePDFCalculator(unittest.TestCase): def setUp(self): self.dpdfc = DebyePDFCalculator() if not TestDebyePDFCalculator.bucky: - TestDebyePDFCalculator.bucky = ( - loadDiffPyStructure('C60bucky.stru')) + TestDebyePDFCalculator.bucky = loadDiffPyStructure("C60bucky.stru") if not TestDebyePDFCalculator.tio2rutile: - TestDebyePDFCalculator.tio2rutile = ( - loadDiffPyStructure('TiO2_rutile-fit.stru')) + TestDebyePDFCalculator.tio2rutile = loadDiffPyStructure("TiO2_rutile-fit.stru") return -# def tearDown(self): -# return -# -# def test___call__(self): -# """check DebyePDFCalculator.__call__() -# """ -# return -# -# def test___init__(self): -# """check DebyePDFCalculator.__init__() -# """ -# return + # def tearDown(self): + # return + # + # def test___call__(self): + # """check DebyePDFCalculator.__call__() + # """ + # return + # + # def test___init__(self): + # """check DebyePDFCalculator.__init__() + # """ + # return def test___getattr__(self): - """check DebyePDFCalculator.__getattr__() - """ + """check DebyePDFCalculator.__getattr__()""" self.assertEqual(0.0, self.dpdfc.qmin) - self.dpdfc._setDoubleAttr('qmin', 1.23) + self.dpdfc._setDoubleAttr("qmin", 1.23) self.assertEqual(1.23, self.dpdfc.qmin) return def test___setattr__(self): - """check DebyePDFCalculator.__setattr__() - """ - self.assertNotEqual(1.23, self.dpdfc._getDoubleAttr('rmin')) + """check DebyePDFCalculator.__setattr__()""" + self.assertNotEqual(1.23, self.dpdfc._getDoubleAttr("rmin")) self.dpdfc.rmin = 1.23 - self.assertEqual(1.23, self.dpdfc._getDoubleAttr('rmin')) + self.assertEqual(1.23, self.dpdfc._getDoubleAttr("rmin")) return def test__getDoubleAttr(self): - """check DebyePDFCalculator._getDoubleAttr() - """ + """check DebyePDFCalculator._getDoubleAttr()""" gdba = self.dpdfc._getDoubleAttr - self.assertEqual(1.0, gdba('scale')) - self.assertEqual(0.0, gdba('qdamp')) - self.assertRaises(Exception, gdba, 'notanattribute') + self.assertEqual(1.0, gdba("scale")) + self.assertEqual(0.0, gdba("qdamp")) + self.assertRaises(Exception, gdba, "notanattribute") return def test__hasDoubleAttr(self): - """check DebyePDFCalculator._hasDoubleAttr() - """ - self.assertTrue(self.dpdfc._hasDoubleAttr('scale')) - self.assertFalse(self.dpdfc._hasDoubleAttr('notanattribute')) + """check DebyePDFCalculator._hasDoubleAttr()""" + self.assertTrue(self.dpdfc._hasDoubleAttr("scale")) + self.assertFalse(self.dpdfc._hasDoubleAttr("notanattribute")) return def test__namesOfDoubleAttributes(self): - """check DebyePDFCalculator._namesOfDoubleAttributes() - """ + """check DebyePDFCalculator._namesOfDoubleAttributes()""" self.assertTrue(type(self.dpdfc._namesOfDoubleAttributes()) is set) - self.assertTrue('qmax' in self.dpdfc._namesOfDoubleAttributes()) + self.assertTrue("qmax" in self.dpdfc._namesOfDoubleAttributes()) return def test__setDoubleAttr(self): - """check DebyePDFCalculator._setDoubleAttr() - """ + """check DebyePDFCalculator._setDoubleAttr()""" gdba = self.dpdfc._getDoubleAttr sdba = self.dpdfc._setDoubleAttr - self.assertEqual(0.0, gdba('rmin')) - sdba('rmin', 3.0) - self.assertEqual(3.0, gdba('rmin')) + self.assertEqual(0.0, gdba("rmin")) + sdba("rmin", 3.0) + self.assertEqual(3.0, gdba("rmin")) return def test_PDF_C60bucky(self): - """check DebyePDFCalculator.pdf for C60 Bucky ball. - """ + """check DebyePDFCalculator.pdf for C60 Bucky ball.""" qmax = self.dpdfc.qmax r0, g0 = PDFCalculator(qmax=qmax)(self.bucky) r1, g1 = self.dpdfc(self.bucky) @@ -102,8 +94,7 @@ def test_PDF_C60bucky(self): return def test_partial_pdfs(self): - """Check calculation of partial PDFs. - """ + """Check calculation of partial PDFs.""" dpdfc = self.dpdfc dpdfc.qmin = 1.0 rutile = self.tio2rutile @@ -119,9 +110,9 @@ def test_partial_pdfs(self): self.assertTrue(numpy.allclose(g0, g1 + g1i)) # Ti-O dpdfc.maskAllPairs(False) - dpdfc.setTypeMask('all', 'ALL', True) - dpdfc.setTypeMask('Ti', 'Ti', False) - dpdfc.setTypeMask('O', 'O', False) + dpdfc.setTypeMask("all", "ALL", True) + dpdfc.setTypeMask("Ti", "Ti", False) + dpdfc.setTypeMask("O", "O", False) r2, g2 = dpdfc(rutile) self.assertTrue(numpy.array_equal(r0, r2)) dpdfc.invertMask() @@ -139,7 +130,7 @@ def test_partial_pdfs(self): self.assertTrue(numpy.array_equal(g2i, g2ti)) # O-O dpdfc.maskAllPairs(False) - dpdfc.setTypeMask('O', 'O', True) + dpdfc.setTypeMask("O", "O", True) r3, g3 = dpdfc(rutile) dpdfc.invertMask() r3i, g3i = dpdfc(rutile) @@ -149,12 +140,11 @@ def test_partial_pdfs(self): return def test_pickling(self): - '''check pickling and unpickling of PDFCalculator. - ''' + """check pickling and unpickling of PDFCalculator.""" dpdfc = self.dpdfc - dpdfc.setScatteringFactorTableByType('N') - dpdfc.scatteringfactortable.setCustomAs('Na', 'Na', 7) - dpdfc.addEnvelope('sphericalshape') + dpdfc.setScatteringFactorTableByType("N") + dpdfc.scatteringfactortable.setCustomAs("Na", "Na", 7) + dpdfc.addEnvelope("sphericalshape") dpdfc.debyeprecision = 0.001 dpdfc.delta1 = 0.2 dpdfc.delta2 = 0.3 @@ -174,21 +164,17 @@ def test_pickling(self): sft = dpdfc.scatteringfactortable sft1 = dpdfc1.scatteringfactortable self.assertEqual(sft.type(), sft1.type()) - self.assertEqual(7.0, sft1.lookup('Na')) + self.assertEqual(7.0, sft1.lookup("Na")) for a in dpdfc._namesOfDoubleAttributes(): self.assertEqual(getattr(dpdfc, a), getattr(dpdfc1, a)) - self.assertEqual(13.3, - dpdfc1.getEnvelope('sphericalshape').spdiameter) - self.assertEqual(dpdfc._namesOfDoubleAttributes(), - dpdfc1._namesOfDoubleAttributes()) + self.assertEqual(13.3, dpdfc1.getEnvelope("sphericalshape").spdiameter) + self.assertEqual(dpdfc._namesOfDoubleAttributes(), dpdfc1._namesOfDoubleAttributes()) self.assertEqual(dpdfc.usedenvelopetypes, dpdfc1.usedenvelopetypes) - self.assertRaises(RuntimeError, pickle_with_attr, dpdfc, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, dpdfc, foo="bar") return - def test_mask_pickling(self): - '''Check if mask gets properly pickled and restored. - ''' + """Check if mask gets properly pickled and restored.""" self.dpdfc.maskAllPairs(False) self.dpdfc.setPairMask(0, 1, True) self.dpdfc.setTypeMask("Na", "Cl", True) @@ -201,11 +187,10 @@ def test_mask_pickling(self): self.assertTrue(True is self.dpdfc.getTypeMask("Cl", "Na")) return - def test_pickling_derived_structure(self): - '''check pickling of DebyePDFCalculator with DerivedStructureAdapter. - ''' + """check pickling of DebyePDFCalculator with DerivedStructureAdapter.""" from diffpy.srreal.tests.testutils import DerivedStructureAdapter + dpdfc = self.dpdfc stru0 = DerivedStructureAdapter() dpdfc.setStructure(stru0) @@ -268,7 +253,7 @@ def test_pickling_derived_structure(self): # End of class TestDebyePDFCalculator -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testoverlapcalculator.py b/src/diffpy/srreal/tests/testoverlapcalculator.py index 44d83312..09881233 100644 --- a/src/diffpy/srreal/tests/testoverlapcalculator.py +++ b/src/diffpy/srreal/tests/testoverlapcalculator.py @@ -18,18 +18,19 @@ # ---------------------------------------------------------------------------- + class TestOverlapCalculator(unittest.TestCase): pool = None def setUp(self): self.olc = OverlapCalculator() - if not hasattr(self, 'rutile'): - type(self).rutile = loadDiffPyStructure('rutile.cif') - if not hasattr(self, 'nickel'): - type(self).nickel = loadDiffPyStructure('Ni.stru') - if not hasattr(self, 'niprim'): - type(self).niprim = loadDiffPyStructure('Ni_primitive.stru') + if not hasattr(self, "rutile"): + type(self).rutile = loadDiffPyStructure("rutile.cif") + if not hasattr(self, "nickel"): + type(self).nickel = loadDiffPyStructure("Ni.stru") + if not hasattr(self, "niprim"): + type(self).niprim = loadDiffPyStructure("Ni_primitive.stru") return def tearDown(self): @@ -40,8 +41,7 @@ def tearDown(self): return def test___init__(self): - """check OverlapCalculator.__init__() - """ + """check OverlapCalculator.__init__()""" self.assertEqual(0, self.olc.rmin) self.assertTrue(100 <= self.olc.rmax) self.assertEqual(0, self.olc.rmaxused) @@ -49,15 +49,14 @@ def test___init__(self): return def test___call__(self): - """check OverlapCalculator.__call__() - """ + """check OverlapCalculator.__call__()""" olc = self.olc sso1 = olc(self.rutile) self.assertEqual(6, len(sso1)) self.assertFalse(numpy.any(sso1)) self.assertEqual(0.0, olc.rmaxused) rtb = olc.atomradiitable - rtb.fromString('Ti:1.6, O:0.66') + rtb.fromString("Ti:1.6, O:0.66") sso2 = olc(self.rutile) self.assertEqual(6, len(sso2[sso2 > 0])) self.assertEqual(3.2, olc.rmaxused) @@ -67,8 +66,7 @@ def test___call__(self): return def test___getstate__(self): - """check OverlapCalculator.__getstate__() - """ + """check OverlapCalculator.__getstate__()""" olc = self.olc self.assertIs(None, olc.__getstate__()[-1]) tb = CovalentRadiiTable() @@ -79,8 +77,7 @@ def test___getstate__(self): return def test_pickling(self): - '''check pickling and unpickling of OverlapCalculator. - ''' + """check pickling and unpickling of OverlapCalculator.""" olc = self.olc olc.rmin = 0.1 olc.rmax = 12.3 @@ -92,14 +89,12 @@ def test_pickling(self): self.assertEqual(getattr(olc, a), getattr(olc1, a)) self.assertFalse(olc1.getPairMask(1, 2)) self.assertTrue(olc1.getPairMask(0, 0)) - self.assertTrue(numpy.array_equal( - olc.sitesquareoverlaps, olc1.sitesquareoverlaps)) - self.assertRaises(RuntimeError, pickle_with_attr, olc, foo='bar') + self.assertTrue(numpy.array_equal(olc.sitesquareoverlaps, olc1.sitesquareoverlaps)) + self.assertRaises(RuntimeError, pickle_with_attr, olc, foo="bar") return def test_pickling_artb(self): - '''check pickling and unpickling of OverlapCalculator.atomradiitable. - ''' + """check pickling and unpickling of OverlapCalculator.atomradiitable.""" olc = self.olc olc.atomradiitable.setDefault(1.3) spkl = pickle.dumps(olc) @@ -107,19 +102,19 @@ def test_pickling_artb(self): self.assertFalse(olc is olc1) self.assertEqual(1.3, olc1.atomradiitable.getDefault()) olc.atomradiitable = CovalentRadiiTable() - olc.atomradiitable.setCustom('Na', 2) + olc.atomradiitable.setCustom("Na", 2) olc.atomradiitable.foo = 123 spkl2 = pickle.dumps(olc) olc2 = pickle.loads(spkl2) - self.assertEqual(2, olc2.atomradiitable.lookup('Na')) + self.assertEqual(2, olc2.atomradiitable.lookup("Na")) self.assertEqual(1, len(olc2.atomradiitable.getAllCustom())) self.assertEqual(123, olc2.atomradiitable.foo) return def test_pickling_derived_structure(self): - '''check pickling of OverlapCalculator with DerivedStructureAdapter. - ''' + """check pickling of OverlapCalculator with DerivedStructureAdapter.""" from diffpy.srreal.tests.testutils import DerivedStructureAdapter + olc = self.olc stru0 = DerivedStructureAdapter() olc.setStructure(stru0) @@ -134,52 +129,48 @@ def test_pickling_derived_structure(self): return def test_parallel(self): - """check parallel run of OverlapCalculator - """ + """check parallel run of OverlapCalculator""" import multiprocessing from diffpy.srreal.parallel import createParallelCalculator + ncpu = 4 self.pool = multiprocessing.Pool(processes=ncpu) olc = self.olc - polc = createParallelCalculator(OverlapCalculator(), - ncpu, self.pool.imap_unordered) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + polc = createParallelCalculator(OverlapCalculator(), ncpu, self.pool.imap_unordered) + olc.atomradiitable.fromString("Ti:1.6, O:0.66") polc.atomradiitable = olc.atomradiitable self.assertTrue(numpy.array_equal(olc(self.rutile), polc(self.rutile))) self.assertTrue(olc.totalsquareoverlap > 0.0) self.assertEqual(olc.totalsquareoverlap, polc.totalsquareoverlap) - self.assertEqual(sorted(zip(olc.sites0, olc.sites1)), - sorted(zip(polc.sites0, polc.sites1))) + self.assertEqual(sorted(zip(olc.sites0, olc.sites1)), sorted(zip(polc.sites0, polc.sites1))) olc.atomradiitable.resetAll() self.assertEqual(0.0, sum(olc(self.rutile))) self.assertEqual(0.0, sum(polc(self.rutile))) return def test_distances(self): - """check OverlapCalculator.distances - """ + """check OverlapCalculator.distances""" olc = self.olc olc(self.nickel) self.assertEqual(0, len(olc.distances)) - olc.atomradiitable.setCustom('Ni', 1.25) + olc.atomradiitable.setCustom("Ni", 1.25) olc(self.nickel) self.assertEqual(4 * 12, len(olc.distances)) dmin = numpy.sqrt(0.5) * self.nickel.lattice.a self.assertAlmostEqual(dmin, numpy.min(olc.distances)) self.assertAlmostEqual(dmin, numpy.max(olc.distances)) olc.maskAllPairs(False) - olc.setPairMask(0, 'all', True) + olc.setPairMask(0, "all", True) olc(self.nickel) self.assertEqual(12 + 12, len(olc.distances)) return def test_directions(self): - """check OverlapCalculator.directions - """ + """check OverlapCalculator.directions""" olc = self.olc olc(self.nickel) self.assertEqual([], olc.directions.tolist()) - olc.atomradiitable.setCustom('Ni', 1.25) + olc.atomradiitable.setCustom("Ni", 1.25) olc.eval(self.nickel) drs = self.olc.directions nms = numpy.sqrt(numpy.sum(numpy.power(drs, 2), axis=1)) @@ -188,10 +179,9 @@ def test_directions(self): return def test_gradients(self): - """check OverlapCalculator.gradients - """ + """check OverlapCalculator.gradients""" olc = self.olc - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertEqual((6, 3), olc.gradients.shape) self.assertTrue(numpy.allclose([0, 0, 0], numpy.sum(olc.gradients))) @@ -199,7 +189,7 @@ def test_gradients(self): self.assertTrue(abs(g2[0]) > 0.1) tso0 = olc.totalsquareoverlap dx = 1e-8 - rutile2 = loadDiffPyStructure('rutile.cif') + rutile2 = loadDiffPyStructure("rutile.cif") rutile2[2].xyz_cartn += [dx, 0.0, 0.0] olc.eval(rutile2) g2nx = (olc.totalsquareoverlap - tso0) / dx @@ -207,63 +197,59 @@ def test_gradients(self): return def test_sitesquareoverlaps(self): - """check OverlapCalculator.sitesquareoverlaps - """ + """check OverlapCalculator.sitesquareoverlaps""" olc = self.olc self.assertTrue(numpy.array_equal([], olc.sitesquareoverlaps)) olc(self.rutile) self.assertTrue(numpy.array_equal(6 * [0.0], olc.sitesquareoverlaps)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") sso = olc(self.rutile) self.assertTrue(numpy.array_equal(sso, olc.sitesquareoverlaps)) self.assertTrue(numpy.all(sso)) return def test_totalsquareoverlap(self): - """check OverlapCalculator.totalsquareoverlap - """ + """check OverlapCalculator.totalsquareoverlap""" olc = self.olc self.assertEqual(0.0, olc.totalsquareoverlap) olc(self.rutile) self.assertEqual(0.0, olc.totalsquareoverlap) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertTrue(1.20854162728, olc.totalsquareoverlap) return def test_meansquareoverlap(self): - """check OverlapCalculator.meansquareoverlap - """ + """check OverlapCalculator.meansquareoverlap""" olc = self.olc self.assertEqual(0.0, olc.meansquareoverlap) olc(self.nickel) self.assertEqual(0.0, olc.meansquareoverlap) - olc.atomradiitable.setCustom('Ni', 1.25) + olc.atomradiitable.setCustom("Ni", 1.25) olc(self.nickel) mso0 = olc.meansquareoverlap self.assertTrue(mso0 > 0.0) sso1 = olc(self.niprim) self.assertEqual(1, len(sso1)) self.assertAlmostEqual(mso0, olc.meansquareoverlap) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertAlmostEqual(0.201423604547, olc.meansquareoverlap) return def test_flipDiffTotal(self): - """check OverlapCalculator.flipDiffTotal - """ + """check OverlapCalculator.flipDiffTotal""" olc = self.olc - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertEqual(0.0, olc.flipDiffTotal(0, 0)) self.assertEqual(0.0, olc.flipDiffTotal(0, 1)) self.assertEqual(0.0, olc.flipDiffTotal(2, 5)) tso0 = olc.totalsquareoverlap olc2 = copy.copy(olc) - rutile2 = loadDiffPyStructure('rutile.cif') - rutile2[0].element = 'O' - rutile2[2].element = 'Ti' + rutile2 = loadDiffPyStructure("rutile.cif") + rutile2[0].element = "O" + rutile2[2].element = "Ti" olc2(rutile2) fdt02 = olc2.totalsquareoverlap - tso0 self.assertTrue(fdt02 > 0.01) @@ -273,48 +259,44 @@ def test_flipDiffTotal(self): return def test_getNeighborSites(self): - """check OverlapCalculator.getNeighborSites - """ + """check OverlapCalculator.getNeighborSites""" olc = self.olc olc(self.rutile) self.assertEqual(set(), olc.getNeighborSites(0)) self.assertEqual(set(), olc.getNeighborSites(3)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) oxygens = list(range(2, 6)) self.assertEqual(set([0] + oxygens), olc.getNeighborSites(0)) self.assertEqual(set([1] + oxygens), olc.getNeighborSites(1)) self.assertEqual(set(range(2)), olc.getNeighborSites(2)) self.assertEqual(set(range(2)), olc.getNeighborSites(5)) - n5, = numpy.array([5], dtype=int) + (n5,) = numpy.array([5], dtype=int) self.assertEqual(set(range(2)), olc.getNeighborSites(n5)) return def test_coordinations(self): - """check OverlapCalculator.coordinations - """ + """check OverlapCalculator.coordinations""" olc = self.olc self.assertEqual(0, len(olc.coordinations)) olc(self.rutile) self.assertEqual(6, len(olc.coordinations)) self.assertFalse(numpy.any(olc.coordinations)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) - self.assertTrue(numpy.array_equal( - [8, 8, 3, 3, 3, 3], olc.coordinations)) + self.assertTrue(numpy.array_equal([8, 8, 3, 3, 3, 3], olc.coordinations)) return def test_coordinationByTypes(self): - """check OverlapCalculator.coordinationByTypes - """ + """check OverlapCalculator.coordinationByTypes""" olc = self.olc olc(self.rutile) self.assertEqual({}, olc.coordinationByTypes(0)) self.assertEqual({}, olc.coordinationByTypes(5)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) - cTi = {'Ti' : 2.0, 'O' : 6.0} - cO = {'Ti' : 3.0} + cTi = {"Ti": 2.0, "O": 6.0} + cO = {"Ti": 3.0} self.assertEqual(cTi, olc.coordinationByTypes(0)) self.assertEqual(cTi, olc.coordinationByTypes(1)) self.assertEqual(cO, olc.coordinationByTypes(2)) @@ -324,91 +306,88 @@ def test_coordinationByTypes(self): return def test_neighborhoods(self): - """check OverlapCalculator.neighborhoods - """ + """check OverlapCalculator.neighborhoods""" olc = self.olc self.assertEqual([], olc.neighborhoods) olc(self.rutile) self.assertEqual([set((i,)) for i in range(6)], olc.neighborhoods) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertEqual([set(range(6))], olc.neighborhoods) - olc.atomradiitable.setCustom('Ti', 1.8) - olc.atomradiitable.setCustom('O', 0.1) + olc.atomradiitable.setCustom("Ti", 1.8) + olc.atomradiitable.setCustom("O", 0.1) olc(self.rutile) nghbs = [set((0, 1))] + [set((i,)) for i in range(2, 6)] self.assertEqual(nghbs, olc.neighborhoods) return + # End of class TestOverlapCalculator # ---------------------------------------------------------------------------- + @unittest.skipUnless(has_pyobjcryst, _msg_nopyobjcryst) class TestOverlapCalculatorObjCryst(unittest.TestCase): def setUp(self): self.olc = OverlapCalculator() - if not hasattr(self, 'rutile'): - type(self).rutile = loadObjCrystCrystal('rutile.cif') - if not hasattr(self, 'nickel'): - type(self).nickel = loadObjCrystCrystal('Ni.cif') + if not hasattr(self, "rutile"): + type(self).rutile = loadObjCrystCrystal("rutile.cif") + if not hasattr(self, "nickel"): + type(self).nickel = loadObjCrystCrystal("Ni.cif") return def tearDown(self): return def test_totalsquareoverlap(self): - """check OverlapCalculator.totalsquareoverlap for ObjCryst crystal - """ + """check OverlapCalculator.totalsquareoverlap for ObjCryst crystal""" olc = self.olc self.assertEqual(0.0, olc.totalsquareoverlap) olc(self.rutile) self.assertEqual(0.0, olc.totalsquareoverlap) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertTrue(1.20854162728, olc.totalsquareoverlap) return def test_meansquareoverlap(self): - """check OverlapCalculator.meansquareoverlap for ObjCryst crystal - """ + """check OverlapCalculator.meansquareoverlap for ObjCryst crystal""" olc = self.olc self.assertEqual(0.0, olc.meansquareoverlap) olc(self.rutile) self.assertEqual(0.0, olc.meansquareoverlap) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertAlmostEqual(0.201423604547, olc.meansquareoverlap) return def test_flipDiffTotal(self): - """check OverlapCalculator.flipDiffTotal for an ObjCryst crystal - """ + """check OverlapCalculator.flipDiffTotal for an ObjCryst crystal""" olc = self.olc olc(self.rutile) self.assertEqual(0.0, olc.flipDiffTotal(0, 1)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) tso0 = olc.totalsquareoverlap olc2 = copy.copy(olc) - olc2.atomradiitable.fromString('Ti:0.66, O:1.6') + olc2.atomradiitable.fromString("Ti:0.66, O:1.6") olc2(self.rutile) fdt01 = olc2.totalsquareoverlap - tso0 self.assertAlmostEqual(fdt01, olc.flipDiffTotal(0, 1)) return def test_flipDiffMean(self): - """check OverlapCalculator.flipDiffMean for an ObjCryst crystal - """ + """check OverlapCalculator.flipDiffMean for an ObjCryst crystal""" olc = self.olc olc(self.rutile) self.assertEqual(0.0, olc.flipDiffMean(0, 1)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) mso0 = olc.meansquareoverlap olc2 = copy.copy(olc) - olc2.atomradiitable.fromString('Ti:0.66, O:1.6') + olc2.atomradiitable.fromString("Ti:0.66, O:1.6") olc2(self.rutile) fdm01 = olc2.meansquareoverlap - mso0 self.assertAlmostEqual(fdm01, olc.flipDiffMean(0, 1)) @@ -418,63 +397,60 @@ def test_flipDiffMean(self): return def test_getNeighborSites(self): - """check OverlapCalculator.getNeighborSites for an ObjCryst crystal - """ + """check OverlapCalculator.getNeighborSites for an ObjCryst crystal""" olc = self.olc olc(self.rutile) self.assertEqual(set(), olc.getNeighborSites(0)) self.assertEqual(set(), olc.getNeighborSites(1)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertEqual(set([0, 1]), olc.getNeighborSites(0)) self.assertEqual(set([0]), olc.getNeighborSites(1)) return def test_coordinations(self): - """check OverlapCalculator.coordinations for an ObjCryst crystal - """ + """check OverlapCalculator.coordinations for an ObjCryst crystal""" olc = self.olc self.assertEqual(0, len(olc.coordinations)) olc(self.rutile) self.assertEqual(2, len(olc.coordinations)) self.assertFalse(numpy.any(olc.coordinations)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertTrue(numpy.array_equal([8, 3], olc.coordinations)) return def test_coordinationByTypes(self): - """check OverlapCalculator.coordinationByTypes for an ObjCryst crystal - """ + """check OverlapCalculator.coordinationByTypes for an ObjCryst crystal""" olc = self.olc olc(self.rutile) self.assertEqual({}, olc.coordinationByTypes(0)) self.assertEqual({}, olc.coordinationByTypes(1)) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) - cTi = {'Ti' : 2.0, 'O' : 6.0} - cO = {'Ti' : 3.0} + cTi = {"Ti": 2.0, "O": 6.0} + cO = {"Ti": 3.0} self.assertEqual(cTi, olc.coordinationByTypes(0)) self.assertEqual(cO, olc.coordinationByTypes(1)) return def test_neighborhoods(self): - """check OverlapCalculator.neighborhoods for an ObjCryst crystal - """ + """check OverlapCalculator.neighborhoods for an ObjCryst crystal""" olc = self.olc self.assertEqual([], olc.neighborhoods) olc(self.rutile) self.assertEqual([set((i,)) for i in range(2)], olc.neighborhoods) - olc.atomradiitable.fromString('Ti:1.6, O:0.66') + olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) self.assertEqual([set((0, 1))], olc.neighborhoods) return + # End of class TestOverlapCalculatorObjCryst # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testpairquantity.py b/src/diffpy/srreal/tests/testpairquantity.py index 2bf755ab..3fa96c80 100644 --- a/src/diffpy/srreal/tests/testpairquantity.py +++ b/src/diffpy/srreal/tests/testpairquantity.py @@ -15,57 +15,56 @@ # ---------------------------------------------------------------------------- + class TestBasePairQuantity(unittest.TestCase): def setUp(self): self.bpq = BasePairQuantity() return - def test_pickling(self): "verify pickling is disabled for the C++ base class." self.assertRaises(RuntimeError, pickle.dumps, self.bpq) return + # End of class TestBasePairQuantity # ---------------------------------------------------------------------------- + class TestPairQuantity(unittest.TestCase): def setUp(self): self.pq = PairQuantity() return - def test_evaluatortype(self): - """check PairQuantity.evaluatortype property. - """ + """check PairQuantity.evaluatortype property.""" pq = self.pq - self.assertTrue(pq.evaluatortype in ('BASIC', 'OPTIMIZED')) - pq.evaluatortype = 'BASIC' - self.assertEqual('BASIC', pq.evaluatortype) - self.assertRaises(ValueError, setattr, pq, 'evaluatortype', 'invalid') - self.assertRaises(ValueError, setattr, pq, 'evaluatortype', 'basic') - self.assertRaises(ValueError, setattr, pq, 'evaluatortype', 'BASic') + self.assertTrue(pq.evaluatortype in ("BASIC", "OPTIMIZED")) + pq.evaluatortype = "BASIC" + self.assertEqual("BASIC", pq.evaluatortype) + self.assertRaises(ValueError, setattr, pq, "evaluatortype", "invalid") + self.assertRaises(ValueError, setattr, pq, "evaluatortype", "basic") + self.assertRaises(ValueError, setattr, pq, "evaluatortype", "BASic") # check all supported evaluators in PDFCalculator pdfc = PDFCalculator() - self.assertEqual('OPTIMIZED', pdfc.evaluatortype) - pdfc.evaluatortype = 'BASIC' - self.assertEqual('BASIC', pdfc.evaluatortype) - pdfc.evaluatortype = 'CHECK' - self.assertEqual('CHECK', pdfc.evaluatortype) - pdfc.evaluatortype = 'OPTIMIZED' - self.assertEqual('OPTIMIZED', pdfc.evaluatortype) + self.assertEqual("OPTIMIZED", pdfc.evaluatortype) + pdfc.evaluatortype = "BASIC" + self.assertEqual("BASIC", pdfc.evaluatortype) + pdfc.evaluatortype = "CHECK" + self.assertEqual("CHECK", pdfc.evaluatortype) + pdfc.evaluatortype = "OPTIMIZED" + self.assertEqual("OPTIMIZED", pdfc.evaluatortype) return - def test_setStructure(self): - """check PairQuantity.setStructure() - """ + """check PairQuantity.setStructure()""" Structure = mod_structure.Structure Atom = mod_structure.Atom from diffpy.srreal.structureadapter import EMPTY + stru = Structure([Atom("Ar", [0.1, 0.2, 0.3])]) self.pq.setStructure(stru) adpt = self.pq.getStructure() @@ -76,10 +75,8 @@ def test_setStructure(self): self.assertEqual(0, adpt.countSites()) return - def test_setPairMask_args(self): - """check argument type handling in setPairMask - """ + """check argument type handling in setPairMask""" spm = self.pq.setPairMask gpm = self.pq.getPairMask self.assertRaises(TypeError, spm, 0.0, 0, False) @@ -92,19 +89,16 @@ def test_setPairMask_args(self): self.assertFalse(gpm(2, 7)) return - def test_getStructure(self): - """check PairQuantity.getStructure() - """ + """check PairQuantity.getStructure()""" adpt = self.pq.getStructure() self.assertEqual(0, adpt.countSites()) return - def test_ticker(self): - """check PairQuantity.ticker() - """ + """check PairQuantity.ticker()""" from diffpy.srreal.eventticker import EventTicker + et0 = EventTicker(self.pq.ticker()) self.pq.rmax = 3.77 et1 = self.pq.ticker() @@ -112,10 +106,8 @@ def test_ticker(self): self.assertTrue(et0 < et1) return - def test_ticker_override(self): - """check Python override of PairQuantity.ticker. - """ + """check Python override of PairQuantity.ticker.""" pqcnt = PQCounter() self.assertEqual(0, pqcnt.tcnt) et0 = pqcnt.ticker() @@ -130,16 +122,14 @@ def test_ticker_override(self): self.assertEqual(1, pqcnt.tcnt) # Check if ticker call from OPTIMIZED evaluator is handled # with our Python override. - pqcnt.evaluatortype = 'OPTIMIZED' + pqcnt.evaluatortype = "OPTIMIZED" self.assertEqual(1, pqcnt.tcnt) pqcnt.eval() self.assertEqual(2, pqcnt.tcnt) return - def test__addPairContribution(self): - """Check Python override of PairQuantity._addPairContribution. - """ + """Check Python override of PairQuantity._addPairContribution.""" pqcnt = PQCounter() self.assertEqual(0, pqcnt(carbonzchain(0))) self.assertEqual(0, pqcnt(carbonzchain(1))) @@ -147,42 +137,36 @@ def test__addPairContribution(self): self.assertEqual(10, pqcnt(carbonzchain(5))) return - def test_optimized_evaluation(self): - """Check OPTIMIZED evaluation in Python-defined calculator class. - """ + """Check OPTIMIZED evaluation in Python-defined calculator class.""" c8 = carbonzchain(8) c9 = carbonzchain(9) pqd = PQDerived() # wrapper for evaluation using specified evaluatortype. # Use pq.eval twice to trigger optimized evaluation. - eval_as = lambda evtp, pq, stru : ( - setattr(pq, 'evaluatortype', evtp), - pq.eval(stru), pq.eval())[-1] - eval_as('BASIC', pqd, c8) - self.assertEqual('BASIC', pqd.evaluatortype) + eval_as = lambda evtp, pq, stru: (setattr(pq, "evaluatortype", evtp), pq.eval(stru), pq.eval())[-1] + eval_as("BASIC", pqd, c8) + self.assertEqual("BASIC", pqd.evaluatortype) # pqd does not support OPTIMIZED evaluation. Its use will # raise ValueError or RuntimeError for older libdiffpy. # Here we check for StandardError that covers them both. - self.assertRaises(Exception, - eval_as, 'OPTIMIZED', pqd, c8) + self.assertRaises(Exception, eval_as, "OPTIMIZED", pqd, c8) # PQCounter supports OPTIMIZED evaluation mode. ocnt = PQCounter() - ocnt.evaluatortype = 'OPTIMIZED' + ocnt.evaluatortype = "OPTIMIZED" self.assertEqual(28, ocnt(c8)) self.assertEqual(28, ocnt(c8)) - self.assertEqual('OPTIMIZED', ocnt.evaluatortypeused) + self.assertEqual("OPTIMIZED", ocnt.evaluatortypeused) self.assertEqual(36, ocnt(c9)) - self.assertEqual('OPTIMIZED', ocnt.evaluatortypeused) + self.assertEqual("OPTIMIZED", ocnt.evaluatortypeused) self.assertEqual(28, ocnt(c8)) - self.assertEqual('OPTIMIZED', ocnt.evaluatortypeused) + self.assertEqual("OPTIMIZED", ocnt.evaluatortypeused) return - def test_pickling(self): - '''check pickling and unpickling of PairQuantity. - ''' + """check pickling and unpickling of PairQuantity.""" from diffpy.srreal.tests.testutils import DerivedStructureAdapter + stru0 = DerivedStructureAdapter() self.pq.setStructure(stru0) self.assertEqual(1, stru0.cpqcount) @@ -201,12 +185,14 @@ def test_pickling(self): self.assertEqual("asdf", pcnt2.foo) return + # End of class TestPairQuantity # ---------------------------------------------------------------------------- # helper for testing PairQuantity overrides + class PQDerived(PairQuantity): tcnt = 0 @@ -215,10 +201,12 @@ def ticker(self): self.tcnt += 1 return PairQuantity.ticker(self) + # End of class PQDerived # helper for testing support for optimized evaluation + class PQCounter(PQDerived): def __init__(self): @@ -228,7 +216,7 @@ def __init__(self): return def __call__(self, structure=None): - rv, = self.eval(structure) + (rv,) = self.eval(structure) return rv def _addPairContribution(self, bnds, sumscale): @@ -244,17 +232,19 @@ def _restorePartialValue(self): del self.__stashed_value return + # End of class PQCounter + def carbonzchain(n): "Helper function that returns a z-chain of Carbon atoms." Structure = mod_structure.Structure Atom = mod_structure.Atom - rv = Structure([Atom('C', [0, 0, z]) for z in range(n)]) + rv = Structure([Atom("C", [0, 0, z]) for z in range(n)]) return rv -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testparallel.py b/src/diffpy/srreal/tests/testparallel.py index 9373dca6..6924ab8a 100644 --- a/src/diffpy/srreal/tests/testparallel.py +++ b/src/diffpy/srreal/tests/testparallel.py @@ -10,6 +10,7 @@ from diffpy.srreal.tests.testutils import loadDiffPyStructure from diffpy.srreal.parallel import createParallelCalculator + ############################################################################## class TestRoutines(unittest.TestCase): @@ -20,11 +21,13 @@ class TestRoutines(unittest.TestCase): def setUp(self): if self.cdse is None: - type(self).cdse = loadDiffPyStructure('CdSe_cadmoselite.cif') - for a in self.cdse: a.Uisoequiv = 0.003 + type(self).cdse = loadDiffPyStructure("CdSe_cadmoselite.cif") + for a in self.cdse: + a.Uisoequiv = 0.003 if self.nickel is None: - type(self).nickel = loadDiffPyStructure('Ni.cif') - for a in self.nickel: a.Uisoequiv = 0.003 + type(self).nickel = loadDiffPyStructure("Ni.cif") + for a in self.nickel: + a.Uisoequiv = 0.003 return def tearDown(self): @@ -40,34 +43,30 @@ def pool(self): self._pool = multiprocessing.Pool(processes=self.ncpu) return self._pool - def test_parallel_evaluatortype(self): - """check handling of the evaluatortype property - """ + """check handling of the evaluatortype property""" from diffpy.srreal.pdfcalculator import PDFCalculator + pdfc = PDFCalculator() - self.assertEqual('OPTIMIZED', pdfc.evaluatortype) + self.assertEqual("OPTIMIZED", pdfc.evaluatortype) ppdfc = createParallelCalculator(pdfc, 2, map) - self.assertEqual('BASIC', ppdfc.evaluatortype) - self.assertEqual('BASIC', pdfc.evaluatortype) - ppdfc.evaluatortype = 'BASIC' - self.assertRaises(ValueError, - setattr, ppdfc, 'evaluatortype', 'OPTIMIZED') + self.assertEqual("BASIC", ppdfc.evaluatortype) + self.assertEqual("BASIC", pdfc.evaluatortype) + ppdfc.evaluatortype = "BASIC" + self.assertRaises(ValueError, setattr, ppdfc, "evaluatortype", "OPTIMIZED") return - def test_parallel_pdf(self): - """check parallel PDFCalculator - """ + """check parallel PDFCalculator""" from diffpy.srreal.pdfcalculator import PDFCalculator + pdfc = PDFCalculator() r0, g0 = pdfc(self.cdse) ppdfc1 = createParallelCalculator(PDFCalculator(), 3, map) r1, g1 = ppdfc1(self.cdse) self.assertTrue(numpy.array_equal(r0, r1)) self.assertTrue(numpy.allclose(g0, g1)) - ppdfc2 = createParallelCalculator(PDFCalculator(), - self.ncpu, self.pool.imap_unordered) + ppdfc2 = createParallelCalculator(PDFCalculator(), self.ncpu, self.pool.imap_unordered) r2, g2 = ppdfc2(self.cdse) self.assertTrue(numpy.array_equal(r0, r2)) self.assertTrue(numpy.allclose(g0, g2)) @@ -84,25 +83,23 @@ def test_parallel_pdf(self): self.assertTrue(numpy.allclose(g0a, g2a)) return - def test_parallel_bonds(self): - """check parallel BondCalculator - """ + """check parallel BondCalculator""" from diffpy.srreal.bondcalculator import BondCalculator + nickel = self.nickel bc = BondCalculator() d0 = bc(nickel) pbc1 = createParallelCalculator(BondCalculator(), 3, map) d1 = pbc1(nickel) self.assertTrue(numpy.array_equal(d0, d1)) - pbc2 = createParallelCalculator(BondCalculator(), - self.ncpu, self.pool.imap_unordered) + pbc2 = createParallelCalculator(BondCalculator(), self.ncpu, self.pool.imap_unordered) d2 = pbc2(nickel) self.assertTrue(numpy.array_equal(d0, d2)) bc.rmax = pbc1.rmax = pbc2.rmax = 2.5 for bci in (bc, pbc1, pbc2): bci.maskAllPairs(False) - bci.setPairMask(0, 'all', True) + bci.setPairMask(0, "all", True) bci.filterCone([1, 0, 0], 48) d0a = bc(nickel) self.assertEqual(8, len(d0a)) @@ -112,9 +109,10 @@ def test_parallel_bonds(self): self.assertTrue(numpy.array_equal(d0a, d2a)) return + # End of class TestRoutines -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testpdfbaseline.py b/src/diffpy/srreal/tests/testpdfbaseline.py index 327ffded..d3fd8277 100644 --- a/src/diffpy/srreal/tests/testpdfbaseline.py +++ b/src/diffpy/srreal/tests/testpdfbaseline.py @@ -15,14 +15,14 @@ # ---------------------------------------------------------------------------- + class TestPDFBaseline(unittest.TestCase): def setUp(self): - self.linear = PDFBaseline.createByType('linear') - self.zero = PDFBaseline.createByType('zero') + self.linear = PDFBaseline.createByType("linear") + self.zero = PDFBaseline.createByType("zero") return - def tearDown(self): for tp in PDFBaseline.getRegisteredTypes(): PDFBaseline._deregisterType(tp) @@ -30,19 +30,15 @@ def tearDown(self): self.zero._registerThisType() return - def test___init__(self): - """check PDFBaseline.__init__() - """ + """check PDFBaseline.__init__()""" self.assertEqual(0.0, self.linear.slope) - self.linear._setDoubleAttr('slope', 2.0) + self.linear._setDoubleAttr("slope", 2.0) self.assertEqual(2.0, self.linear.slope) return - def test___call__(self): - """check PDFBaseline.__call__() - """ + """check PDFBaseline.__call__()""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PDFBaseline().__call__, 37) self.assertEqual(0.0, self.zero(10)) @@ -51,7 +47,7 @@ def test___call__(self): self.assertEqual(0.0, self.linear(345)) self.linear.slope = -2 self.assertEqual(-7.0, self.linear(3.5)) - self.assertEqual(-2.0, self.linear._getDoubleAttr('slope')) + self.assertEqual(-2.0, self.linear._getDoubleAttr("slope")) x = numpy.arange(0, 10.001, 0.1) xb = numpy.array([(0.0, xi) for xi in x])[:, 1] self.assertTrue(xb.strides > x.strides) @@ -59,52 +55,42 @@ def test___call__(self): self.assertTrue(numpy.array_equal(-2 * x, self.linear(xb))) return - def test_clone(self): - """check PDFBaseline.clone - """ + """check PDFBaseline.clone""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PDFBaseline().clone) self.linear.slope = 17 bl2 = self.linear.clone() - self.assertEqual('linear', bl2.type()) + self.assertEqual("linear", bl2.type()) self.assertEqual(17.0, bl2.slope) - self.assertEqual(17.0, bl2._getDoubleAttr('slope')) + self.assertEqual(17.0, bl2._getDoubleAttr("slope")) return - def test_create(self): - """check PDFBaseline.create - """ + """check PDFBaseline.create""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PDFBaseline().create) - self.assertEqual('zero', self.zero.create().type()) - self.assertEqual('linear', self.linear.create().type()) + self.assertEqual("zero", self.zero.create().type()) + self.assertEqual("linear", self.linear.create().type()) self.linear.slope = 17 self.assertEqual(0.0, self.linear.create().slope) return - def test_type(self): - """check PDFBaseline.type - """ + """check PDFBaseline.type""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PDFBaseline().type) - self.assertEqual('linear', self.linear.type()) - self.assertEqual('zero', self.zero.type()) + self.assertEqual("linear", self.linear.type()) + self.assertEqual("zero", self.zero.type()) self.assertTrue(type(self.linear) is LinearBaseline) self.assertTrue(type(self.zero) is ZeroBaseline) return - def test__aliasType(self): - """check PDFBaseline._aliasType. - """ + """check PDFBaseline._aliasType.""" self.assertRaises(ValueError, PDFBaseline.createByType, "alias") - self.assertRaises(RuntimeError, PDFBaseline._aliasType, - "invalid", "alias") - self.assertRaises(RuntimeError, PDFBaseline._aliasType, - "linear", "zero") + self.assertRaises(RuntimeError, PDFBaseline._aliasType, "invalid", "alias") + self.assertRaises(RuntimeError, PDFBaseline._aliasType, "linear", "zero") PDFBaseline._aliasType("linear", "alias") bl = PDFBaseline.createByType("alias") self.assertEqual("linear", bl.type()) @@ -114,81 +100,64 @@ def test__aliasType(self): bl1 = PDFBaseline.createByType("alias") self.assertTrue(isinstance(bl1, LinearBaseline)) # no other type can be aliased to the existing name. - self.assertRaises(RuntimeError, PDFBaseline._aliasType, - "zero", "alias") + self.assertRaises(RuntimeError, PDFBaseline._aliasType, "zero", "alias") return - def test__deregisterType(self): - """check PDFBaseline._deregisterType. - """ + """check PDFBaseline._deregisterType.""" self.assertEqual(0, PDFBaseline._deregisterType("nonexistent")) PDFBaseline._aliasType("linear", "alias") self.assertEqual(2, PDFBaseline._deregisterType("alias")) - self.assertFalse('linear' in PDFBaseline.getRegisteredTypes()) + self.assertFalse("linear" in PDFBaseline.getRegisteredTypes()) self.assertEqual(0, PDFBaseline._deregisterType("alias")) return - def test_createByType(self): - """check PDFBaseline.createByType() - """ - self.assertRaises(ValueError, PDFBaseline.createByType, 'notregistered') + """check PDFBaseline.createByType()""" + self.assertRaises(ValueError, PDFBaseline.createByType, "notregistered") return - def test_isRegisteredType(self): - """check PDFBaseline.isRegisteredType() - """ + """check PDFBaseline.isRegisteredType()""" self.assertTrue(PDFBaseline.isRegisteredType("linear")) self.assertFalse(PDFBaseline.isRegisteredType("nonexistent")) PDFBaseline._deregisterType("linear") self.assertFalse(PDFBaseline.isRegisteredType("linear")) return - def test_getAliasedTypes(self): - """check PDFBaseline.getAliasedTypes() - """ + """check PDFBaseline.getAliasedTypes()""" self.assertEqual({}, PDFBaseline.getAliasedTypes()) PDFBaseline._aliasType("linear", "foo") PDFBaseline._aliasType("linear", "bar") PDFBaseline._aliasType("linear", "linear") PDFBaseline._aliasType("bar", "foo") - self.assertEqual({'bar' : 'linear', 'foo' : 'linear'}, - PDFBaseline.getAliasedTypes()) + self.assertEqual({"bar": "linear", "foo": "linear"}, PDFBaseline.getAliasedTypes()) return - def test_getRegisteredTypes(self): - """check PDFBaseline.getRegisteredTypes - """ + """check PDFBaseline.getRegisteredTypes""" regtypes = PDFBaseline.getRegisteredTypes() self.assertTrue(2 <= len(regtypes)) - self.assertTrue('linear' in regtypes) - self.assertTrue('zero' in regtypes) + self.assertTrue("linear" in regtypes) + self.assertTrue("zero" in regtypes) return - def test_pickling(self): - '''check pickling and unpickling of PDFBaseline. - ''' + """check pickling and unpickling of PDFBaseline.""" linear = self.linear linear.slope = 11 linear2 = pickle.loads(pickle.dumps(linear)) - self.assertEqual('linear', linear2.type()) + self.assertEqual("linear", linear2.type()) self.assertEqual(11, linear2.slope) - self.assertEqual(11, linear2._getDoubleAttr('slope')) - self.assertRaises(RuntimeError, pickle_with_attr, linear, foo='bar') - self.assertRaises(RuntimeError, pickle_with_attr, self.zero, foo='bar') + self.assertEqual(11, linear2._getDoubleAttr("slope")) + self.assertRaises(RuntimeError, pickle_with_attr, linear, foo="bar") + self.assertRaises(RuntimeError, pickle_with_attr, self.zero, foo="bar") return - def test_makePDFBaseline(self): - '''check the makePDFBaseline wrapper. - ''' - pbl = makePDFBaseline('parabolabaseline', - parabola_baseline, a=1, b=2, c=3) + """check the makePDFBaseline wrapper.""" + pbl = makePDFBaseline("parabolabaseline", parabola_baseline, a=1, b=2, c=3) self.assertEqual(3, pbl(0)) self.assertEqual(6, pbl(1)) self.assertEqual(11, pbl(2)) @@ -199,59 +168,56 @@ def test_makePDFBaseline(self): self.assertEqual(0, pbl2.b) self.assertEqual(3, pbl2.c) self.assertEqual([7, 3, 28], [pbl2(x) for x in [-2, 0, 5]]) - pbl3 = PDFBaseline.createByType('parabolabaseline') + pbl3 = PDFBaseline.createByType("parabolabaseline") self.assertEqual(1, pbl3.a) self.assertEqual(2, pbl3.b) self.assertEqual(3, pbl3.c) - pbl.foo = 'bar' + pbl.foo = "bar" pbl4 = pickle.loads(pickle.dumps(pbl)) self.assertEqual([7, 3, 28], [pbl4(x) for x in [-2, 0, 5]]) - self.assertEqual('bar', pbl4.foo) + self.assertEqual("bar", pbl4.foo) # fail if this baseline type already exists. - self.assertRaises(RuntimeError, makePDFBaseline, 'linear', - parabola_baseline, a=1, b=2, c=3) - self.assertRaises(RuntimeError, makePDFBaseline, 'parabolabaseline', - parabola_baseline, a=1, b=2, c=3) + self.assertRaises(RuntimeError, makePDFBaseline, "linear", parabola_baseline, a=1, b=2, c=3) + self.assertRaises(RuntimeError, makePDFBaseline, "parabolabaseline", parabola_baseline, a=1, b=2, c=3) # check replacement of an existing type. - makePDFBaseline('linear', parabola_baseline, replace=True, - a=1, b=2, c=4) - pbl4 = PDFBaseline.createByType('linear') - self.assertEqual(set(('a', 'b', 'c')), pbl4._namesOfDoubleAttributes()) + makePDFBaseline("linear", parabola_baseline, replace=True, a=1, b=2, c=4) + pbl4 = PDFBaseline.createByType("linear") + self.assertEqual(set(("a", "b", "c")), pbl4._namesOfDoubleAttributes()) self.assertEqual(4, pbl4.c) # check baseline with no attributes - pbl5 = makePDFBaseline('myzero', lambda x: 0.0) + pbl5 = makePDFBaseline("myzero", lambda x: 0.0) self.assertEqual(0, pbl5(33)) self.assertEqual(set(), pbl5._namesOfDoubleAttributes()) return - def test_picking_owned(self): - '''verify pickling of PDFBaseline owned by PDF calculators. - ''' - pbl = makePDFBaseline('parabolabaseline', - parabola_baseline, a=1, b=2, c=3) + """verify pickling of PDFBaseline owned by PDF calculators.""" + pbl = makePDFBaseline("parabolabaseline", parabola_baseline, a=1, b=2, c=3) pbl.a = 7 - pbl.foobar = 'asdf' + pbl.foobar = "asdf" pc = PDFCalculator() pc.baseline = pbl self.assertIs(pbl, pc.baseline) pc2 = pickle.loads(pickle.dumps(pc)) pbl2 = pc2.baseline self.assertEqual(7, pbl2.a) - self.assertEqual('asdf', pbl2.foobar) - self.assertEqual('parabolabaseline', pbl2.type()) + self.assertEqual("asdf", pbl2.foobar) + self.assertEqual("parabolabaseline", pbl2.type()) return + # End of class TestPDFBaseline # ---------------------------------------------------------------------------- # function for wrapping by makePDFBaseline + def parabola_baseline(x, a, b, c): return a * x**2 + b * x + c -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testpdfcalcobjcryst.py b/src/diffpy/srreal/tests/testpdfcalcobjcryst.py index 2193888d..4f5960a7 100644 --- a/src/diffpy/srreal/tests/testpdfcalcobjcryst.py +++ b/src/diffpy/srreal/tests/testpdfcalcobjcryst.py @@ -17,20 +17,23 @@ # helper functions + def _loadExpectedPDF(basefilename): - '''Read expected result and return a tuple of (r, g, cfgdict). - ''' - rxf = re.compile(r'[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?') + """Read expected result and return a tuple of (r, g, cfgdict).""" + rxf = re.compile(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?") fullpath = datafile(basefilename) cfgdict = {} fp = open(fullpath) for line in fp: - if line[:1] != '#': break + if line[:1] != "#": + break w = line.split() - has_cfgdata = (len(w) == 4 and w[2] == '=') - if not has_cfgdata: continue + has_cfgdata = len(w) == 4 and w[2] == "=" + if not has_cfgdata: + continue cfgdict[w[1]] = w[3] - if rxf.match(w[3]): cfgdict[w[1]] = float(w[3]) + if rxf.match(w[3]): + cfgdict[w[1]] = float(w[3]) fp.close() r, g = numpy.loadtxt(fullpath, usecols=(0, 1), unpack=True) rv = (r, g, cfgdict) @@ -38,34 +41,35 @@ def _loadExpectedPDF(basefilename): def _makePDFCalculator(crst, cfgdict): - '''Return a PDFCalculator object evaluated for a pyobjcryst.Crystal crst. - ''' - pdfcargs = {k : v for k, v in cfgdict.items() - if k not in ('biso', 'type')} + """Return a PDFCalculator object evaluated for a pyobjcryst.Crystal crst.""" + pdfcargs = {k: v for k, v in cfgdict.items() if k not in ("biso", "type")} pdfc = PDFCalculator(**pdfcargs) - if 'biso' in cfgdict: + if "biso" in cfgdict: reg = crst.GetScatteringPowerRegistry() for i in range(reg.GetNb()): sp = reg.GetObj(i) - sp.SetBiso(cfgdict['biso']) - if 'type' in cfgdict: - pdfc.scatteringfactortable = cfgdict['type'] + sp.SetBiso(cfgdict["biso"]) + if "type" in cfgdict: + pdfc.scatteringfactortable = cfgdict["type"] pdfc.eval(crst) # avoid metadata override by PDFFitStructure for k, v in pdfcargs.items(): setattr(pdfc, k, v) return pdfc + # ---------------------------------------------------------------------------- + @unittest.skipUnless(has_pyobjcryst, _msg_nopyobjcryst) class TestPDFCalcObjcryst(unittest.TestCase): def _comparePDFs(self, nickname, pdfbasename, cifbasename): def setself(**kwtoset): for n, v in kwtoset.items(): - setattr(self, nickname + '_' + n, v) + setattr(self, nickname + "_" + n, v) return + r, gobs, cfg = _loadExpectedPDF(pdfbasename) setself(r=r, gobs=gobs, cfg=cfg) crst = loadObjCrystCrystal(cifbasename) @@ -76,38 +80,30 @@ def setself(**kwtoset): setself(gcalc=gcalc, mxnd=mxnd) return - def test_CdSeN(self): - '''check PDFCalculator on ObjCryst loaded CIF, neutrons - ''' - self._comparePDFs('cdsen', - 'CdSe_cadmoselite_N.fgr', 'CdSe_cadmoselite.cif') + """check PDFCalculator on ObjCryst loaded CIF, neutrons""" + self._comparePDFs("cdsen", "CdSe_cadmoselite_N.fgr", "CdSe_cadmoselite.cif") self.assertTrue(self.cdsen_mxnd < 0.01) return - def test_CdSeX(self): - '''check PDFCalculator on ObjCryst loaded CIF, xrays - ''' - self._comparePDFs('cdsex', - 'CdSe_cadmoselite_X.fgr', 'CdSe_cadmoselite.cif') + """check PDFCalculator on ObjCryst loaded CIF, xrays""" + self._comparePDFs("cdsex", "CdSe_cadmoselite_X.fgr", "CdSe_cadmoselite.cif") self.assertTrue(self.cdsex_mxnd < 0.01) return - def test_rutileaniso(self): - '''check PDFCalculator on ObjCryst loaded anisotropic rutile - ''' - self._comparePDFs('rutileaniso', - 'TiO2_rutile-fit.fgr', 'TiO2_rutile-fit.cif') + """check PDFCalculator on ObjCryst loaded anisotropic rutile""" + self._comparePDFs("rutileaniso", "TiO2_rutile-fit.fgr", "TiO2_rutile-fit.cif") self.assertTrue(self.rutileaniso_mxnd < 0.057) return + # End of class TestPDFCalcObjcryst # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testpdfcalculator.py b/src/diffpy/srreal/tests/testpdfcalculator.py index e018d325..7c1e2645 100644 --- a/src/diffpy/srreal/tests/testpdfcalculator.py +++ b/src/diffpy/srreal/tests/testpdfcalculator.py @@ -16,17 +16,19 @@ # helper functions + def _maxNormDiff(yobs, ycalc): - '''Returned maximum difference normalized by RMS of the yobs - ''' + """Returned maximum difference normalized by RMS of the yobs""" yobsa = numpy.array(yobs) obsmax = numpy.max(numpy.fabs(yobsa)) or 1 ynmdiff = (yobsa - ycalc) / obsmax rv = max(numpy.fabs(ynmdiff)) return rv + # ---------------------------------------------------------------------------- + class TestPDFCalculator(unittest.TestCase): nickel = None @@ -35,28 +37,25 @@ class TestPDFCalculator(unittest.TestCase): def setUp(self): self.pdfcalc = PDFCalculator() if not self.nickel: - type(self).nickel = loadDiffPyStructure('Ni.stru') + type(self).nickel = loadDiffPyStructure("Ni.stru") if not self.tio2rutile: - type(self).tio2rutile = ( - loadDiffPyStructure('TiO2_rutile-fit.stru')) + type(self).tio2rutile = loadDiffPyStructure("TiO2_rutile-fit.stru") return def tearDown(self): return def test___init__(self): - """check PDFCalculator.__init__() - """ + """check PDFCalculator.__init__()""" pdfc = PDFCalculator(qmin=13, rmin=4, rmax=99) self.assertEqual(13, pdfc.qmin) self.assertEqual(4, pdfc.rmin) self.assertEqual(99, pdfc.rmax) - self.assertEqual(99, pdfc._getDoubleAttr('rmax')) + self.assertEqual(99, pdfc._getDoubleAttr("rmax")) return def test___call__(self): - """Check PDFCalculator.__call__() - """ + """Check PDFCalculator.__call__()""" r0, g0 = self.pdfcalc(self.tio2rutile, rmin=2) self.assertEqual(2.0, r0[0]) r1, g1 = self.pdfcalc(self.tio2rutile, scale=7) @@ -65,7 +64,7 @@ def test___call__(self): rutile2 = self.tio2rutile.copy() # work around Structure bug of shared pdffit dictionary rutile2.pdffit = dict(self.tio2rutile.pdffit) - rutile2.pdffit['spdiameter'] = 5.0 + rutile2.pdffit["spdiameter"] = 5.0 r3, g3 = self.pdfcalc(rutile2) self.assertEqual(0.0, sum(g3[r3 >= 5] ** 2)) r4, g4 = self.pdfcalc(rutile2, scale=1, spdiameter=0) @@ -74,53 +73,47 @@ def test___call__(self): return def test__getDoubleAttr(self): - """check PDFCalculator._getDoubleAttr() - """ + """check PDFCalculator._getDoubleAttr()""" gdba = self.pdfcalc._getDoubleAttr - self.assertEqual(1.0, gdba('scale')) - self.assertEqual(0.0, gdba('qdamp')) - self.assertRaises(Exception, gdba, 'notanattribute') + self.assertEqual(1.0, gdba("scale")) + self.assertEqual(0.0, gdba("qdamp")) + self.assertRaises(Exception, gdba, "notanattribute") return def test__hasDoubleAttr(self): - """check PDFCalculator._hasDoubleAttr() - """ - self.assertTrue(self.pdfcalc._hasDoubleAttr('scale')) - self.assertFalse(self.pdfcalc._hasDoubleAttr('notanattribute')) + """check PDFCalculator._hasDoubleAttr()""" + self.assertTrue(self.pdfcalc._hasDoubleAttr("scale")) + self.assertFalse(self.pdfcalc._hasDoubleAttr("notanattribute")) return def test__namesOfDoubleAttributes(self): - """check PDFCalculator._namesOfDoubleAttributes() - """ + """check PDFCalculator._namesOfDoubleAttributes()""" self.assertTrue(type(self.pdfcalc._namesOfDoubleAttributes()) is set) - self.assertTrue('qmax' in self.pdfcalc._namesOfDoubleAttributes()) + self.assertTrue("qmax" in self.pdfcalc._namesOfDoubleAttributes()) return def test__setDoubleAttr(self): - """check PDFCalculator._setDoubleAttr() - """ + """check PDFCalculator._setDoubleAttr()""" gdba = self.pdfcalc._getDoubleAttr sdba = self.pdfcalc._setDoubleAttr - self.assertEqual(0.0, gdba('rmin')) - sdba('rmin', 3.0) - self.assertEqual(3.0, gdba('rmin')) + self.assertEqual(0.0, gdba("rmin")) + sdba("rmin", 3.0) + self.assertEqual(3.0, gdba("rmin")) return def test_eval_nickel(self): - """check PDFCalculator.eval() on simple Nickel data - """ - fnipf2 = datafile('Ni-fit.fgr') + """check PDFCalculator.eval() on simple Nickel data""" + fnipf2 = datafile("Ni-fit.fgr") gpf2 = numpy.loadtxt(fnipf2, usecols=(1,)) - self.pdfcalc._setDoubleAttr('rmax', 10.0001) + self.pdfcalc._setDoubleAttr("rmax", 10.0001) self.pdfcalc.eval(self.nickel) gcalc = self.pdfcalc.pdf self.assertTrue(_maxNormDiff(gpf2, gcalc) < 0.0091) return def test_eval_rutile(self): - """check PDFCalculator.eval() on anisotropic rutile data - """ - frutile = datafile('TiO2_rutile-fit.fgr') + """check PDFCalculator.eval() on anisotropic rutile data""" + frutile = datafile("TiO2_rutile-fit.fgr") gpf2 = numpy.loadtxt(frutile, usecols=(1,)) # configure calculator according to testdata/TiO2_ruitile-fit.fgr self.pdfcalc.qmax = 26 @@ -143,8 +136,7 @@ def test_eval_rutile(self): return def test_partial_pdfs(self): - """Check calculation of partial PDFs. - """ + """Check calculation of partial PDFs.""" pdfc = self.pdfcalc pdfc.rstep = 0.1 rutile = self.tio2rutile @@ -208,8 +200,7 @@ def test_partial_pdfs(self): return def test_full_mask(self): - '''Test PDFCalculator for a fully masked structure. - ''' + """Test PDFCalculator for a fully masked structure.""" pdfc = self.pdfcalc pdfc.rstep = 0.1 rutile = self.tio2rutile @@ -225,8 +216,7 @@ def test_full_mask(self): return def test_zero_mask(self): - '''Test PDFCalculator with a totally masked out structure. - ''' + """Test PDFCalculator with a totally masked out structure.""" pdfc = self.pdfcalc pdfc.rstep = 0.1 rutile = self.tio2rutile @@ -241,12 +231,11 @@ def test_zero_mask(self): return def test_pickling(self): - '''check pickling and unpickling of PDFCalculator. - ''' + """check pickling and unpickling of PDFCalculator.""" pdfc = self.pdfcalc - pdfc.scatteringfactortable = 'N' - pdfc.scatteringfactortable.setCustomAs('Na', 'Na', 7) - pdfc.addEnvelope('sphericalshape') + pdfc.scatteringfactortable = "N" + pdfc.scatteringfactortable.setCustomAs("Na", "Na", 7) + pdfc.addEnvelope("sphericalshape") pdfc.delta1 = 0.2 pdfc.delta2 = 0.3 pdfc.maxextension = 10.1 @@ -266,20 +255,17 @@ def test_pickling(self): sft = pdfc.scatteringfactortable sft1 = pdfc1.scatteringfactortable self.assertEqual(sft.type(), sft1.type()) - self.assertEqual(7.0, sft1.lookup('Na')) + self.assertEqual(7.0, sft1.lookup("Na")) for a in pdfc._namesOfDoubleAttributes(): self.assertEqual(getattr(pdfc, a), getattr(pdfc1, a)) - self.assertEqual(13.3, - pdfc1.getEnvelope('sphericalshape').spdiameter) - self.assertEqual(pdfc._namesOfDoubleAttributes(), - pdfc1._namesOfDoubleAttributes()) + self.assertEqual(13.3, pdfc1.getEnvelope("sphericalshape").spdiameter) + self.assertEqual(pdfc._namesOfDoubleAttributes(), pdfc1._namesOfDoubleAttributes()) self.assertEqual(pdfc.usedenvelopetypes, pdfc1.usedenvelopetypes) - self.assertRaises(RuntimeError, pickle_with_attr, pdfc, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, pdfc, foo="bar") return def test_mask_pickling(self): - '''Check if mask gets properly pickled and restored. - ''' + """Check if mask gets properly pickled and restored.""" self.pdfcalc.maskAllPairs(False) self.pdfcalc.setPairMask(0, 1, True) self.assertTrue(False is self.pdfcalc.getPairMask(0, 0)) @@ -290,9 +276,9 @@ def test_mask_pickling(self): return def test_pickling_derived_structure(self): - '''check pickling of PDFCalculator with DerivedStructureAdapter. - ''' + """check pickling of PDFCalculator with DerivedStructureAdapter.""" from diffpy.srreal.tests.testutils import DerivedStructureAdapter + pdfc = self.pdfcalc stru0 = DerivedStructureAdapter() pdfc.setStructure(stru0) @@ -307,20 +293,19 @@ def test_pickling_derived_structure(self): return def test_envelopes(self): - '''Check the envelopes property. - ''' + """Check the envelopes property.""" from diffpy.srreal.pdfenvelope import PDFEnvelope + pc = self.pdfcalc self.assertTrue(len(pc.envelopes) > 0) pc.clearEnvelopes() self.assertEqual(0, len(pc.envelopes)) - pc.addEnvelope(PDFEnvelope.createByType('scale')) + pc.addEnvelope(PDFEnvelope.createByType("scale")) self.assertEqual(1, len(pc.envelopes)) - self.assertEqual('scale', pc.envelopes[0].type()) - pc.envelopes += ('qresolution',) - self.assertEqual(('qresolution', 'scale'), pc.usedenvelopetypes) - self.assertTrue(all([isinstance(e, PDFEnvelope) - for e in pc.envelopes])) + self.assertEqual("scale", pc.envelopes[0].type()) + pc.envelopes += ("qresolution",) + self.assertEqual(("qresolution", "scale"), pc.usedenvelopetypes) + self.assertTrue(all([isinstance(e, PDFEnvelope) for e in pc.envelopes])) return @@ -353,41 +338,40 @@ def test_envelopes(self): # ---------------------------------------------------------------------------- + class TestFFTRoutines(unittest.TestCase): def test_fft_conversions(self): - """Verify conversions of arguments in fftgtof function. - """ - fnipf2 = datafile('Ni-fit.fgr') + """Verify conversions of arguments in fftgtof function.""" + fnipf2 = datafile("Ni-fit.fgr") data = numpy.loadtxt(fnipf2) dr = 0.01 - fq0, dq0 = fftgtof(data[:,1], dr) - fq1, dq1 = fftgtof(data[:,1].copy(), dr) - fq2, dq2 = fftgtof(list(data[:,1]), dr) + fq0, dq0 = fftgtof(data[:, 1], dr) + fq1, dq1 = fftgtof(data[:, 1].copy(), dr) + fq2, dq2 = fftgtof(list(data[:, 1]), dr) self.assertTrue(numpy.array_equal(fq0, fq1)) self.assertTrue(numpy.array_equal(fq0, fq2)) self.assertEqual(dq0, dq1) self.assertEqual(dq0, dq2) return - def test_fft_roundtrip(self): - """Check if forward and inverse transformation recover the input. - """ - fnipf2 = datafile('Ni-fit.fgr') + """Check if forward and inverse transformation recover the input.""" + fnipf2 = datafile("Ni-fit.fgr") g0 = numpy.loadtxt(fnipf2, usecols=(1,)) dr0 = 0.01 fq, dq = fftgtof(g0, dr0) g1, dr1 = fftftog(fq, dq) self.assertAlmostEqual(dr0, dr1, 12) - self.assertTrue(numpy.allclose(g0, g1[:g0.size])) + self.assertTrue(numpy.allclose(g0, g1[: g0.size])) return + # End of class TestFFTRoutines # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testpdfenvelope.py b/src/diffpy/srreal/tests/testpdfenvelope.py index 48751290..7adb1060 100644 --- a/src/diffpy/srreal/tests/testpdfenvelope.py +++ b/src/diffpy/srreal/tests/testpdfenvelope.py @@ -16,32 +16,28 @@ # ---------------------------------------------------------------------------- + class TestPDFEnvelope(unittest.TestCase): def setUp(self): - self.fstepcut = PDFEnvelope.createByType('stepcut') + self.fstepcut = PDFEnvelope.createByType("stepcut") self.fstepcut.stepcut = 5 - self.fscale = PDFEnvelope.createByType('scale') + self.fscale = PDFEnvelope.createByType("scale") return - def tearDown(self): - PDFEnvelope._deregisterType('parabolaenvelope') + PDFEnvelope._deregisterType("parabolaenvelope") return - def test___init__(self): - """check PDFEnvelope.__init__() - """ + """check PDFEnvelope.__init__()""" self.assertEqual(1.0, self.fscale.scale) - self.fscale._setDoubleAttr('scale', 2.0) + self.fscale._setDoubleAttr("scale", 2.0) self.assertEqual(2.0, self.fscale.scale) return - def test___call__(self): - """check PDFEnvelope.__call__() - """ + """check PDFEnvelope.__call__()""" x = numpy.arange(0, 9.1, 0.3) xb = numpy.array([(0.0, xi) for xi in x])[:, 1] self.assertTrue(xb.strides > x.strides) @@ -59,76 +55,61 @@ def test___call__(self): self.assertEqual(-2.0, self.fscale(3.5)) return - def test_clone(self): - """check PDFEnvelope.clone - """ + """check PDFEnvelope.clone""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PDFEnvelope().clone) self.fstepcut.stepcut = 17 e2 = self.fstepcut.clone() - self.assertEqual('stepcut', e2.type()) + self.assertEqual("stepcut", e2.type()) self.assertEqual(17.0, e2.stepcut) - self.assertEqual(17.0, e2._getDoubleAttr('stepcut')) + self.assertEqual(17.0, e2._getDoubleAttr("stepcut")) return - def test_create(self): - """check PDFEnvelope.create - """ + """check PDFEnvelope.create""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PDFEnvelope().create) - self.assertEqual('stepcut', self.fstepcut.create().type()) - self.assertEqual('scale', self.fscale.create().type()) + self.assertEqual("stepcut", self.fstepcut.create().type()) + self.assertEqual("scale", self.fscale.create().type()) self.fstepcut.stepcut = 17 self.assertEqual(0.0, self.fstepcut.create().stepcut) return - def test_type(self): - """check PDFEnvelope.type - """ + """check PDFEnvelope.type""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PDFEnvelope().type) - self.assertEqual('stepcut', self.fstepcut.type()) - self.assertEqual('scale', self.fscale.type()) + self.assertEqual("stepcut", self.fstepcut.type()) + self.assertEqual("scale", self.fscale.type()) return - def test_createByType(self): - """check PDFEnvelope.createByType() - """ - self.assertRaises(ValueError, PDFEnvelope.createByType, 'notregistered') + """check PDFEnvelope.createByType()""" + self.assertRaises(ValueError, PDFEnvelope.createByType, "notregistered") return - def test_getRegisteredTypes(self): - """check PDFEnvelope.getRegisteredTypes - """ + """check PDFEnvelope.getRegisteredTypes""" regtypes = PDFEnvelope.getRegisteredTypes() self.assertTrue(2 <= len(regtypes)) - self.assertTrue('stepcut' in regtypes) - self.assertTrue('scale' in regtypes) + self.assertTrue("stepcut" in regtypes) + self.assertTrue("scale" in regtypes) return - def test_pickling(self): - '''check pickling and unpickling of PDFEnvelope. - ''' + """check pickling and unpickling of PDFEnvelope.""" stp = self.fstepcut stp.stepcut = 11 stp2 = pickle.loads(pickle.dumps(stp)) - self.assertEqual('stepcut', stp2.type()) + self.assertEqual("stepcut", stp2.type()) self.assertEqual(11, stp2.stepcut) - self.assertEqual(11, stp2._getDoubleAttr('stepcut')) + self.assertEqual(11, stp2._getDoubleAttr("stepcut")) return - def test_makePDFEnvelope(self): - '''check the makePDFEnvelope wrapper. - ''' - pbl = makePDFEnvelope('parabolaenvelope', - parabola_envelope, a=1, b=2, c=3) + """check the makePDFEnvelope wrapper.""" + pbl = makePDFEnvelope("parabolaenvelope", parabola_envelope, a=1, b=2, c=3) self.assertEqual(3, pbl(0)) self.assertEqual(6, pbl(1)) self.assertEqual(11, pbl(2)) @@ -139,25 +120,22 @@ def test_makePDFEnvelope(self): self.assertEqual(0, pbl2.b) self.assertEqual(3, pbl2.c) self.assertEqual([7, 3, 28], [pbl2(x) for x in [-2, 0, 5]]) - pbl3 = PDFEnvelope.createByType('parabolaenvelope') + pbl3 = PDFEnvelope.createByType("parabolaenvelope") self.assertEqual(1, pbl3.a) self.assertEqual(2, pbl3.b) self.assertEqual(3, pbl3.c) pbl3.a = 0 - pbl3.foo = 'asdf' + pbl3.foo = "asdf" pbl3cp = pickle.loads(pickle.dumps(pbl3)) self.assertEqual(0, pbl3cp.a) - self.assertEqual('asdf', pbl3cp.foo) + self.assertEqual("asdf", pbl3cp.foo) return - def test_picking_owned(self): - '''verify pickling of envelopes owned by PDF calculators. - ''' - pbl = makePDFEnvelope('parabolaenvelope', - parabola_envelope, a=1, b=2, c=3) + """verify pickling of envelopes owned by PDF calculators.""" + pbl = makePDFEnvelope("parabolaenvelope", parabola_envelope, a=1, b=2, c=3) pbl.a = 7 - pbl.foobar = 'asdf' + pbl.foobar = "asdf" pc = PDFCalculator() pc.envelopes = (pbl,) dbpc = DebyePDFCalculator() @@ -173,117 +151,119 @@ def test_picking_owned(self): dbpc2 = pickle.loads(pickle.dumps(dbpc)) self.assertEqual(3.5, pc2.scale) self.assertEqual(3.5, dbpc2.scale) - pblcopies = [pc2.getEnvelope("parabolaenvelope"), - dbpc2.getEnvelope("parabolaenvelope")] + pblcopies = [pc2.getEnvelope("parabolaenvelope"), dbpc2.getEnvelope("parabolaenvelope")] for pbl2 in pblcopies: self.assertEqual(7, pbl2.a) - self.assertEqual('asdf', pbl2.foobar) - self.assertEqual('parabolaenvelope', pbl2.type()) + self.assertEqual("asdf", pbl2.foobar) + self.assertEqual("parabolaenvelope", pbl2.type()) return + # ---------------------------------------------------------------------------- + class TestQResolutionEnvelope(unittest.TestCase): def setUp(self): self.evlp = QResolutionEnvelope() return - def test_type(self): - self.assertEqual('qresolution', self.evlp.type()) - self.assertTrue(hasattr(self.evlp, 'qdamp')) + self.assertEqual("qresolution", self.evlp.type()) + self.assertTrue(hasattr(self.evlp, "qdamp")) return - def test_pickling(self): evlp = self.evlp evlp.qdamp = 3 evlp2 = pickle.loads(pickle.dumps(evlp)) self.assertEqual(QResolutionEnvelope, type(evlp2)) self.assertEqual(3, evlp2.qdamp) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") return + # ---------------------------------------------------------------------------- + class TestScaleEnvelope(unittest.TestCase): def setUp(self): self.evlp = ScaleEnvelope() return - def test_type(self): - self.assertEqual('scale', self.evlp.type()) - self.assertTrue(hasattr(self.evlp, 'scale')) + self.assertEqual("scale", self.evlp.type()) + self.assertTrue(hasattr(self.evlp, "scale")) return - def test_pickling(self): evlp = self.evlp evlp.scale = 3 evlp2 = pickle.loads(pickle.dumps(evlp)) self.assertEqual(ScaleEnvelope, type(evlp2)) self.assertEqual(3, evlp2.scale) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") return + # ---------------------------------------------------------------------------- + class TestSphericalShapeEnvelope(unittest.TestCase): def setUp(self): self.evlp = SphericalShapeEnvelope() return - def test_type(self): - self.assertEqual('sphericalshape', self.evlp.type()) - self.assertTrue(hasattr(self.evlp, 'spdiameter')) + self.assertEqual("sphericalshape", self.evlp.type()) + self.assertTrue(hasattr(self.evlp, "spdiameter")) return - def test_pickling(self): evlp = self.evlp evlp.spdiameter = 3 evlp2 = pickle.loads(pickle.dumps(evlp)) self.assertEqual(SphericalShapeEnvelope, type(evlp2)) self.assertEqual(3, evlp2.spdiameter) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") return + # ---------------------------------------------------------------------------- + class TestStepCutEnvelope(unittest.TestCase): def setUp(self): self.evlp = StepCutEnvelope() return - def test_type(self): - self.assertEqual('stepcut', self.evlp.type()) - self.assertTrue(hasattr(self.evlp, 'stepcut')) + self.assertEqual("stepcut", self.evlp.type()) + self.assertTrue(hasattr(self.evlp, "stepcut")) return - def test_pickling(self): evlp = self.evlp evlp.stepcut = 3 evlp2 = pickle.loads(pickle.dumps(evlp)) self.assertEqual(StepCutEnvelope, type(evlp2)) self.assertEqual(3, evlp2.stepcut) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") return + # ---------------------------------------------------------------------------- + def parabola_envelope(x, a, b, c): - 'parabola function for wrapping by makePDFEnvelope' + "parabola function for wrapping by makePDFEnvelope" return a * x**2 + b * x + c -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testpeakprofile.py b/src/diffpy/srreal/tests/testpeakprofile.py index 50f86ae3..d187e969 100644 --- a/src/diffpy/srreal/tests/testpeakprofile.py +++ b/src/diffpy/srreal/tests/testpeakprofile.py @@ -15,65 +15,54 @@ # ---------------------------------------------------------------------------- + class TestPeakProfile(unittest.TestCase): def setUp(self): - self.pkgauss = PeakProfile.createByType('gaussian') - self.pkcropped = PeakProfile.createByType('croppedgaussian') + self.pkgauss = PeakProfile.createByType("gaussian") + self.pkcropped = PeakProfile.createByType("croppedgaussian") return - def tearDown(self): return - def test___init__(self): - """check PeakProfile.__init__() - """ + """check PeakProfile.__init__()""" self.assertNotEqual(0.0, self.pkgauss.peakprecision) - self.assertEqual(self.pkgauss.peakprecision, - self.pkcropped.peakprecision) - self.pkgauss._setDoubleAttr('peakprecision', 0.01) + self.assertEqual(self.pkgauss.peakprecision, self.pkcropped.peakprecision) + self.pkgauss._setDoubleAttr("peakprecision", 0.01) self.assertEqual(0.01, self.pkgauss.peakprecision) return - def test_create(self): - """check PeakProfile.create - """ + """check PeakProfile.create""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PeakProfile().create) - self.assertEqual('gaussian', self.pkgauss.create().type()) + self.assertEqual("gaussian", self.pkgauss.create().type()) self.pkgauss.peakprecision = 0.007 self.assertNotEqual(0.007, self.pkgauss.create().peakprecision) return - def test_clone(self): - """check PeakProfile.clone - """ + """check PeakProfile.clone""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PeakProfile().clone) self.pkgauss.peakprecision = 0.0003 pkg2 = self.pkgauss.clone() - self.assertEqual('gaussian', pkg2.type()) + self.assertEqual("gaussian", pkg2.type()) self.assertEqual(0.0003, pkg2.peakprecision) - self.assertEqual(0.0003, pkg2._getDoubleAttr('peakprecision')) + self.assertEqual(0.0003, pkg2._getDoubleAttr("peakprecision")) return - def test_type(self): - """check PeakProfile.type - """ + """check PeakProfile.type""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PeakProfile().type) - self.assertEqual('croppedgaussian', self.pkcropped.type()) + self.assertEqual("croppedgaussian", self.pkcropped.type()) return - def test___call__(self): - """check PeakProfile.__call__() - """ + """check PeakProfile.__call__()""" ymx = self.pkgauss(0.0, 1) yhalflo = self.pkgauss(-0.5, 1) yhalfhi = self.pkgauss(-0.5, 1) @@ -83,11 +72,10 @@ def test___call__(self): self.assertNotEqual(0, self.pkgauss(10, 1)) return - def test_ticker(self): - """check PeakProfile.ticker() - """ + """check PeakProfile.ticker()""" from diffpy.srreal.eventticker import EventTicker + et0 = EventTicker(self.pkgauss.ticker()) self.pkgauss.peakprecision = 0.003 et1 = self.pkgauss.ticker() @@ -95,10 +83,8 @@ def test_ticker(self): self.assertTrue(et0 < et1) return - def test_ticker_override(self): - """check method override for PeakProfile.ticker in a derived class. - """ + """check method override for PeakProfile.ticker in a derived class.""" pkf = MySawTooth() self.assertEqual(0, pkf.tcnt) et0 = pkf.ticker() @@ -116,33 +102,30 @@ def test_ticker_override(self): self.assertEqual(2, pkf.tcnt) return - def test_getRegisteredTypes(self): - """check PeakProfile.getRegisteredTypes - """ + """check PeakProfile.getRegisteredTypes""" regtypes = PeakProfile.getRegisteredTypes() self.assertTrue(2 <= len(regtypes)) - self.assertTrue(regtypes.issuperset( - ['gaussian', 'croppedgaussian'])) + self.assertTrue(regtypes.issuperset(["gaussian", "croppedgaussian"])) return - def test_pickling(self): - '''check pickling and unpickling of PeakProfile. - ''' + """check pickling and unpickling of PeakProfile.""" pkg = self.pkgauss pkg.peakprecision = 0.0011 pkg2 = pickle.loads(pickle.dumps(pkg)) - self.assertEqual('gaussian', pkg2.type()) + self.assertEqual("gaussian", pkg2.type()) self.assertEqual(0.0011, pkg2.peakprecision) - self.assertEqual(0.0011, pkg2._getDoubleAttr('peakprecision')) - self.assertRaises(RuntimeError, pickle_with_attr, pkg, foo='bar') + self.assertEqual(0.0011, pkg2._getDoubleAttr("peakprecision")) + self.assertRaises(RuntimeError, pickle_with_attr, pkg, foo="bar") pkc = self.pkcropped - self.assertRaises(RuntimeError, pickle_with_attr, pkc, foo='bar') + self.assertRaises(RuntimeError, pickle_with_attr, pkc, foo="bar") return + # ---------------------------------------------------------------------------- + class MySawTooth(PeakProfile): "Helper class for testing PeakProfile." @@ -154,9 +137,11 @@ def create(self): def clone(self): import copy + return copy.copy(self) tcnt = 0 + def ticker(self): self.tcnt += 1 return PeakProfile.ticker(self) @@ -164,7 +149,8 @@ def ticker(self): def __call__(self, x, fwhm): w = 1.0 * fwhm rv = (1 - abs(x) / w) / (1.0 * w) - if rv < 0: rv = 0 + if rv < 0: + rv = 0 return rv def xboundlo(self, fwhm): @@ -173,67 +159,64 @@ def xboundlo(self, fwhm): def xboundhi(self, fwhm): return +fwhm + # End of class MySawTooth + class TestPeakProfileOwner(unittest.TestCase): def setUp(self): MySawTooth()._registerThisType() self.pc = PDFCalculator() - self.pc.peakprofile = 'mysawtooth' + self.pc.peakprofile = "mysawtooth" self.pkf = self.pc.peakprofile self.pkf.peakprecision = 0.0017 return - def tearDown(self): PeakProfile._deregisterType(self.pkf.type()) return - def test_pkftype(self): - '''Check type of the owned PeakProfile instance. - ''' - self.assertEqual('mysawtooth', self.pc.peakprofile.type()) + """Check type of the owned PeakProfile instance.""" + self.assertEqual("mysawtooth", self.pc.peakprofile.type()) return - def test_custom_peakprofile(self): "Check if our MySawTooth is indeed applied." - c2 = mod_structure.Structure(2 * [mod_structure.Atom('C')]) + c2 = mod_structure.Structure(2 * [mod_structure.Atom("C")]) c2.z = [0, 1] c2.Uisoequiv = 0.01 r, g = self.pc(c2) k = g.argmax() self.assertEqual(1, r[k]) - self.assertTrue(numpy.allclose(numpy.diff(g[k - 5:k], 2), 0)) - self.assertTrue(numpy.allclose(numpy.diff(g[k:k + 5], 2), 0)) + self.assertTrue(numpy.allclose(numpy.diff(g[k - 5 : k], 2), 0)) + self.assertTrue(numpy.allclose(numpy.diff(g[k : k + 5], 2), 0)) pkf2 = self.pc.peakprofile.clone() self.assertTrue(isinstance(pkf2, MySawTooth)) self.assertEqual(0.0017, pkf2.peakprecision) return - def test_pickling(self): - '''Check pickling of an owned PeakProfile instance. - ''' + """Check pickling of an owned PeakProfile instance.""" pc1 = pickle.loads(pickle.dumps(self.pc)) self.pkf.peakprecision = 0.0003 - self.pkf.foo = 'bar' + self.pkf.foo = "bar" pc2 = pickle.loads(pickle.dumps(self.pc)) - self.assertEqual('mysawtooth', pc1.peakprofile.type()) + self.assertEqual("mysawtooth", pc1.peakprofile.type()) self.assertEqual(0.0017, pc1.peakprofile.peakprecision) self.assertEqual(0.0017, pc1.peakprecision) - self.assertFalse(hasattr(pc1.peakprofile, 'foo')) - self.assertEqual('mysawtooth', pc2.peakprofile.type()) + self.assertFalse(hasattr(pc1.peakprofile, "foo")) + self.assertEqual("mysawtooth", pc2.peakprofile.type()) self.assertEqual(0.0003, pc2.peakprofile.peakprecision) self.assertEqual(0.0003, pc2.peakprecision) - self.assertEqual('bar', pc2.peakprofile.foo) + self.assertEqual("bar", pc2.peakprofile.foo) return + # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testpeakwidthmodel.py b/src/diffpy/srreal/tests/testpeakwidthmodel.py index 830b3bdb..18a00465 100644 --- a/src/diffpy/srreal/tests/testpeakwidthmodel.py +++ b/src/diffpy/srreal/tests/testpeakwidthmodel.py @@ -15,24 +15,23 @@ # ---------------------------------------------------------------------------- + class TestPeakWidthModel(unittest.TestCase): tio2stru = None tio2adpt = None def setUp(self): - self.pwconst = PeakWidthModel.createByType('constant') + self.pwconst = PeakWidthModel.createByType("constant") self.pwconst.width = 2 if self.tio2stru is None: - self.tio2stru = loadDiffPyStructure('rutile.cif') + self.tio2stru = loadDiffPyStructure("rutile.cif") self.tio2adpt = createStructureAdapter(self.tio2stru) return - def tearDown(self): return - def _genbonds(self, rmin, rmax): "Return ready-to-use BondGenerator for rutile." bnds = self.tio2adpt.createBondGenerator() @@ -41,63 +40,52 @@ def _genbonds(self, rmin, rmax): bnds.rewind() return bnds - def test___init__(self): - """check PeakWidthModel.__init__() - """ + """check PeakWidthModel.__init__()""" self.assertEqual(2.0, self.pwconst.width) - self.pwconst._setDoubleAttr('width', 3.0) + self.pwconst._setDoubleAttr("width", 3.0) self.assertEqual(3.0, self.pwconst.width) return - def test_create(self): - """check PeakWidthModel.create - """ + """check PeakWidthModel.create""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PeakWidthModel().create) - self.assertEqual('constant', self.pwconst.create().type()) + self.assertEqual("constant", self.pwconst.create().type()) self.pwconst.width = 17 self.assertEqual(0.0, self.pwconst.create().width) return - def test_clone(self): - """check PeakWidthModel.clone - """ + """check PeakWidthModel.clone""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PeakWidthModel().clone) self.pwconst.width = 17 pwc2 = self.pwconst.clone() - self.assertEqual('constant', pwc2.type()) + self.assertEqual("constant", pwc2.type()) self.assertEqual(17.0, pwc2.width) - self.assertEqual(17.0, pwc2._getDoubleAttr('width')) + self.assertEqual(17.0, pwc2._getDoubleAttr("width")) return - def test_type(self): - """check PeakWidthModel.type - """ + """check PeakWidthModel.type""" # this is a virtual method in the base class self.assertRaises(RuntimeError, PeakWidthModel().type) - self.assertEqual('constant', self.pwconst.type()) + self.assertEqual("constant", self.pwconst.type()) return - def test_calculate(self): - """check PeakWidthModel.calculate() - """ + """check PeakWidthModel.calculate()""" pwm = PeakWidthModel() bnds = self._genbonds(1, 2) self.assertRaises(RuntimeError, pwm.calculate, bnds) self.assertEqual(2.0, self.pwconst.calculate(bnds)) return - def test_isowidths(self): - """check ConstantPeakWidth properties bisowidth, uisowidth. - """ + """check ConstantPeakWidth properties bisowidth, uisowidth.""" from numpy import pi + cnpw = self.pwconst dwpw = DebyeWallerPeakWidth() bnds = self._genbonds(1, 2) @@ -107,21 +95,17 @@ def test_isowidths(self): self.assertAlmostEqual(cnpw.bisowidth, 8 * pi**2 * cnpw.uisowidth, 12) return - def test_maxWidth(self): - """check PeakWidthModel.maxWidth() - """ - self.assertRaises(RuntimeError, PeakWidthModel().maxWidth, - self.tio2adpt, 0, 10) + """check PeakWidthModel.maxWidth()""" + self.assertRaises(RuntimeError, PeakWidthModel().maxWidth, self.tio2adpt, 0, 10) self.assertEqual(2.0, self.pwconst.maxWidth(self.tio2adpt, 0, 10)) self.assertEqual(2.0, self.pwconst.maxWidth(self.tio2stru, 0, 10)) return - def test_ticker(self): - """check PeakWidthModel.ticker() - """ + """check PeakWidthModel.ticker()""" from diffpy.srreal.eventticker import EventTicker + et0 = EventTicker(self.pwconst.ticker()) self.pwconst.width = 3 et1 = self.pwconst.ticker() @@ -129,10 +113,8 @@ def test_ticker(self): self.assertTrue(et0 < et1) return - def test_ticker_override(self): - """check PeakWidthModel.ticker override in a Python-derived class. - """ + """check PeakWidthModel.ticker override in a Python-derived class.""" pwm = MyPWM() self.assertEqual(0, pwm.tcnt) et0 = pwm.ticker() @@ -150,76 +132,67 @@ def test_ticker_override(self): self.assertEqual(2, pwm.tcnt) return - def test_getRegisteredTypes(self): - """check PeakWidthModel.getRegisteredTypes - """ + """check PeakWidthModel.getRegisteredTypes""" regtypes = PeakWidthModel.getRegisteredTypes() self.assertTrue(3 <= len(regtypes)) - self.assertTrue(regtypes.issuperset( - ['constant', 'debye-waller', 'jeong'])) + self.assertTrue(regtypes.issuperset(["constant", "debye-waller", "jeong"])) return - def test_pickling(self): - '''check pickling and unpickling of PeakWidthModel. - ''' + """check pickling and unpickling of PeakWidthModel.""" pwc = self.pwconst pwc.width = 11 pwc2 = pickle.loads(pickle.dumps(pwc)) - self.assertEqual('constant', pwc2.type()) + self.assertEqual("constant", pwc2.type()) self.assertEqual(11, pwc2.width) - self.assertEqual(11, pwc2._getDoubleAttr('width')) + self.assertEqual(11, pwc2._getDoubleAttr("width")) return + # ---------------------------------------------------------------------------- + class TestDebyeWallerPeakWidth(unittest.TestCase): def setUp(self): self.pwm = DebyeWallerPeakWidth() return - def test_type(self): - """check DebyeWallerPeakWidth.type - """ - self.assertEqual('debye-waller', self.pwm.type()) + """check DebyeWallerPeakWidth.type""" + self.assertEqual("debye-waller", self.pwm.type()) self.assertEqual(0, len(self.pwm._namesOfDoubleAttributes())) return - def test_pickling(self): - """check pickling of DebyeWallerPeakWidth class. - """ - self.assertEqual('debye-waller', self.pwm.type()) + """check pickling of DebyeWallerPeakWidth class.""" + self.assertEqual("debye-waller", self.pwm.type()) pwm = self.pwm pwm2 = pickle.loads(pickle.dumps(pwm)) self.assertEqual(DebyeWallerPeakWidth, type(pwm2)) return + # ---------------------------------------------------------------------------- + class TestJeongPeakWidth(unittest.TestCase): def setUp(self): self.pwm = JeongPeakWidth() return - def test_type(self): - """check JeongPeakWidth.type - """ - self.assertEqual('jeong', self.pwm.type()) - self.assertTrue(hasattr(self.pwm, 'delta1')) - self.assertTrue(hasattr(self.pwm, 'delta2')) - self.assertTrue(hasattr(self.pwm, 'qbroad')) + """check JeongPeakWidth.type""" + self.assertEqual("jeong", self.pwm.type()) + self.assertTrue(hasattr(self.pwm, "delta1")) + self.assertTrue(hasattr(self.pwm, "delta2")) + self.assertTrue(hasattr(self.pwm, "qbroad")) return - def test_pickling(self): - """check pickling of the DebyeWallerPeakWidth class - """ + """check pickling of the DebyeWallerPeakWidth class""" pwm = self.pwm pwm.delta1 = 1 pwm.delta2 = 2 @@ -231,8 +204,10 @@ def test_pickling(self): self.assertEqual(3, pwm2.qbroad) return + # ---------------------------------------------------------------------------- + class MyPWM(PeakWidthModel): "Helper class for testing PeakWidthModelOwner." @@ -240,7 +215,7 @@ class MyPWM(PeakWidthModel): def __init__(self): PeakWidthModel.__init__(self) - self._registerDoubleAttribute('pwmscale') + self._registerDoubleAttribute("pwmscale") return def type(self): @@ -251,18 +226,22 @@ def create(self): def clone(self): import copy + return copy.copy(self) def calculate(self, bnds): return self.pwmscale * bnds.msd() tcnt = 0 + def ticker(self): self.tcnt += 1 return PeakWidthModel.ticker(self) + # End of class MyPWM + class TestPeakWidthOwner(unittest.TestCase): @classmethod @@ -270,7 +249,6 @@ def tearDownClass(cls): assert "mypwm" not in PeakWidthModel.getRegisteredTypes() return - def setUp(self): self.pc = PDFCalculator() self.dbpc = DebyePDFCalculator() @@ -279,25 +257,21 @@ def setUp(self): self.dbpc.peakwidthmodel = self.pwm return - def test_pwmtype(self): - '''Check type of the owned PeakWidthModel instance. - ''' - self.assertEqual('mypwm', self.pc.peakwidthmodel.type()) - self.assertEqual('mypwm', self.dbpc.peakwidthmodel.type()) + """Check type of the owned PeakWidthModel instance.""" + self.assertEqual("mypwm", self.pc.peakwidthmodel.type()) + self.assertEqual("mypwm", self.dbpc.peakwidthmodel.type()) return - def test_pickling(self): - '''Check pickling of an owned PeakWidthModel instance. - ''' + """Check pickling of an owned PeakWidthModel instance.""" pc1 = pickle.loads(pickle.dumps(self.pc)) self.pwm.pwmscale = 3 pc2 = pickle.loads(pickle.dumps(self.pc)) - self.assertEqual('mypwm', pc1.peakwidthmodel.type()) + self.assertEqual("mypwm", pc1.peakwidthmodel.type()) self.assertEqual(1.5, pc1.peakwidthmodel.pwmscale) self.assertEqual(1.5, pc1.pwmscale) - self.assertEqual('mypwm', pc2.peakwidthmodel.type()) + self.assertEqual("mypwm", pc2.peakwidthmodel.type()) self.assertEqual(3, pc2.peakwidthmodel.pwmscale) self.assertEqual(3, pc2.pwmscale) dbpc2 = pickle.loads(pickle.dumps(self.dbpc)) @@ -305,9 +279,10 @@ def test_pickling(self): self.assertEqual(3, dbpc2.pwmscale) return + # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testscatteringfactortable.py b/src/diffpy/srreal/tests/testscatteringfactortable.py index 4edd6023..ba4dbebc 100644 --- a/src/diffpy/srreal/tests/testscatteringfactortable.py +++ b/src/diffpy/srreal/tests/testscatteringfactortable.py @@ -16,57 +16,70 @@ # ---------------------------------------------------------------------------- + class LocalTable(ScatteringFactorTable): def clone(self): import copy + return copy.copy(self) - def create(self): return LocalTable() - def _standardLookup(self, smbl, q): return q + 1 - def radiationType(self): return "LTB" - def type(self): return "localtable" + + def create(self): + return LocalTable() + + def _standardLookup(self, smbl, q): + return q + 1 + + def radiationType(self): + return "LTB" + + def type(self): + return "localtable" + def ticker(self): self.tcnt += 1 return ScatteringFactorTable.ticker(self) + tcnt = 0 + # ---------------------------------------------------------------------------- + class TestScatteringFactorTable(unittest.TestCase): def setUp(self): - self.sftx = ScatteringFactorTable.createByType('X') - self.sftn = ScatteringFactorTable.createByType('N') + self.sftx = ScatteringFactorTable.createByType("X") + self.sftn = ScatteringFactorTable.createByType("N") LocalTable()._registerThisType() return def tearDown(self): - ScatteringFactorTable._deregisterType('localtable') + ScatteringFactorTable._deregisterType("localtable") return def test_class_registry(self): - """check if instances are aliased by radiationType(). - """ - ltb = ScatteringFactorTable.createByType('LTB') + """check if instances are aliased by radiationType().""" + ltb = ScatteringFactorTable.createByType("LTB") self.assertTrue(type(ltb) is LocalTable) - ltb2 = ScatteringFactorTable.createByType('localtable') + ltb2 = ScatteringFactorTable.createByType("localtable") self.assertTrue(type(ltb2) is LocalTable) return def test_ticker(self): - """check ScatteringFactorTable.ticker() - """ + """check ScatteringFactorTable.ticker()""" from diffpy.srreal.eventticker import EventTicker + et0 = EventTicker(self.sftx.ticker()) - self.sftx.setCustomAs('D', 'H') + self.sftx.setCustomAs("D", "H") et1 = self.sftx.ticker() self.assertNotEqual(et0, et1) self.assertTrue(et0 < et1) return def test_ticker_override(self): - """check Python override of ScatteringFactorTable.ticker. - """ + """check Python override of ScatteringFactorTable.ticker.""" from diffpy.srreal.pdfcalculator import PDFCalculator + lsft = LocalTable() self.assertEqual(0, lsft.tcnt) et0 = lsft.ticker() @@ -85,108 +98,101 @@ def test_ticker_override(self): return def test_pickling(self): - """check pickling of ScatteringFactorTable instances. - """ + """check pickling of ScatteringFactorTable instances.""" self.assertEqual(0, len(self.sftx.getCustomSymbols())) - self.sftx.setCustomAs('Na', 'Na', 123) - self.sftx.setCustomAs('Calias', 'C') + self.sftx.setCustomAs("Na", "Na", 123) + self.sftx.setCustomAs("Calias", "C") self.assertEqual(2, len(self.sftx.getCustomSymbols())) sftx1 = pickle.loads(pickle.dumps(self.sftx)) self.assertEqual(2, len(sftx1.getCustomSymbols())) - self.assertAlmostEqual(123, sftx1.lookup('Na'), 12) - self.assertEqual(self.sftx.lookup('C'), sftx1.lookup('Calias')) + self.assertAlmostEqual(123, sftx1.lookup("Na"), 12) + self.assertEqual(self.sftx.lookup("C"), sftx1.lookup("Calias")) self.assertEqual(self.sftx.type(), sftx1.type()) pwa = pickle_with_attr - self.assertRaises(RuntimeError, pwa, SFTXray(), foo='bar') - self.assertRaises(RuntimeError, pwa, SFTElectron(), foo='bar') - self.assertRaises(RuntimeError, pwa, SFTNeutron(), foo='bar') - self.assertRaises(RuntimeError, pwa, SFTElectronNumber(), foo='bar') + self.assertRaises(RuntimeError, pwa, SFTXray(), foo="bar") + self.assertRaises(RuntimeError, pwa, SFTElectron(), foo="bar") + self.assertRaises(RuntimeError, pwa, SFTNeutron(), foo="bar") + self.assertRaises(RuntimeError, pwa, SFTElectronNumber(), foo="bar") return def test_picking_owned(self): - '''verify pickling of envelopes owned by PDF calculators. - ''' + """verify pickling of envelopes owned by PDF calculators.""" pc = PDFCalculator() dbpc = DebyePDFCalculator() ltb = LocalTable() - ltb.setCustomAs('Na', 'Na', 37) - ltb.foo = 'bar' + ltb.setCustomAs("Na", "Na", 37) + ltb.foo = "bar" pc.scatteringfactortable = ltb dbpc.scatteringfactortable = ltb self.assertIs(ltb, pc.scatteringfactortable) self.assertIs(ltb, dbpc.scatteringfactortable) pc2 = pickle.loads(pickle.dumps(pc)) dbpc2 = pickle.loads(pickle.dumps(dbpc)) - self.assertEqual('localtable', pc2.scatteringfactortable.type()) - self.assertEqual('localtable', dbpc2.scatteringfactortable.type()) - self.assertEqual(37, pc2.scatteringfactortable.lookup('Na')) - self.assertEqual(37, dbpc2.scatteringfactortable.lookup('Na')) - self.assertEqual('bar', pc2.scatteringfactortable.foo) - self.assertEqual('bar', dbpc2.scatteringfactortable.foo) + self.assertEqual("localtable", pc2.scatteringfactortable.type()) + self.assertEqual("localtable", dbpc2.scatteringfactortable.type()) + self.assertEqual(37, pc2.scatteringfactortable.lookup("Na")) + self.assertEqual(37, dbpc2.scatteringfactortable.lookup("Na")) + self.assertEqual("bar", pc2.scatteringfactortable.foo) + self.assertEqual("bar", dbpc2.scatteringfactortable.foo) return def test_pickling_derived(self): - """check pickling of a derived classes. - """ + """check pickling of a derived classes.""" lsft = LocalTable() - self.assertEqual(3, lsft._standardLookup('Na', 2)) + self.assertEqual(3, lsft._standardLookup("Na", 2)) self.assertEqual(set(), lsft.getCustomSymbols()) - lsft.foobar = 'asdf' - lsft.setCustomAs('Na', 'Na', 123) + lsft.foobar = "asdf" + lsft.setCustomAs("Na", "Na", 123) self.assertEqual(1, len(lsft.getCustomSymbols())) lsft1 = pickle.loads(pickle.dumps(lsft)) self.assertEqual(1, len(lsft1.getCustomSymbols())) - self.assertAlmostEqual(123, lsft1.lookup('Na'), 12) - self.assertEqual('asdf', lsft1.foobar) + self.assertAlmostEqual(123, lsft1.lookup("Na"), 12) + self.assertEqual("asdf", lsft1.foobar) self.assertEqual(lsft.type(), lsft1.type()) - self.assertEqual(3, lsft1._standardLookup('Cl', 2)) - self.assertEqual(1, lsft1.lookup('H')) + self.assertEqual(3, lsft1._standardLookup("Cl", 2)) + self.assertEqual(1, lsft1.lookup("H")) return def test_derived_create(self): - """Check override of ScatteringFactorTable.create in Python class. - """ + """Check override of ScatteringFactorTable.create in Python class.""" lsft = LocalTable() - lsft.setCustomAs('Xy', 'Na') + lsft.setCustomAs("Xy", "Na") lsft2 = lsft.create() self.assertTrue(isinstance(lsft2, LocalTable)) self.assertEqual(set(), lsft2.getCustomSymbols()) return def test_derived_clone(self): - """Check override of ScatteringFactorTable.clone in Python class. - """ + """Check override of ScatteringFactorTable.clone in Python class.""" lsft = LocalTable() - lsft.setCustomAs('Xy', 'Na') + lsft.setCustomAs("Xy", "Na") lsft2 = lsft.clone() self.assertTrue(isinstance(lsft2, LocalTable)) - self.assertEqual(set(['Xy']), lsft2.getCustomSymbols()) + self.assertEqual(set(["Xy"]), lsft2.getCustomSymbols()) return def test_lookup(self): - """Check ScatteringFactorTable.lookup handling of array arguments. - """ + """Check ScatteringFactorTable.lookup handling of array arguments.""" qa = numpy.linspace(0, 50) - qb = numpy.array([(x, 0.0) for x in qa])[:,0] + qb = numpy.array([(x, 0.0) for x in qa])[:, 0] self.assertTrue(qb.strides > qa.strides) sftx = self.sftx - fmn0 = numpy.array([sftx.lookup('Mn', x) for x in qa]) - self.assertTrue(numpy.array_equal(fmn0, sftx.lookup('Mn', qa))) - self.assertTrue(numpy.array_equal(fmn0, sftx.lookup('Mn', qb))) - self.assertTrue(numpy.array_equal( - fmn0.reshape(5, 10), sftx.lookup('Mn', qa.reshape(5, 10)))) - self.assertTrue(numpy.array_equal( - fmn0.reshape(5, 2, 5), sftx.lookup('Mn', qa.reshape(5, 2, 5)))) - self.assertTrue(numpy.array_equal(fmn0, sftx.lookup('Mn', list(qa)))) - self.assertRaises(TypeError, sftx.lookup, 'Na', 'asdf') - self.assertRaises(TypeError, sftx.lookup, 'Na', {}) + fmn0 = numpy.array([sftx.lookup("Mn", x) for x in qa]) + self.assertTrue(numpy.array_equal(fmn0, sftx.lookup("Mn", qa))) + self.assertTrue(numpy.array_equal(fmn0, sftx.lookup("Mn", qb))) + self.assertTrue(numpy.array_equal(fmn0.reshape(5, 10), sftx.lookup("Mn", qa.reshape(5, 10)))) + self.assertTrue(numpy.array_equal(fmn0.reshape(5, 2, 5), sftx.lookup("Mn", qa.reshape(5, 2, 5)))) + self.assertTrue(numpy.array_equal(fmn0, sftx.lookup("Mn", list(qa)))) + self.assertRaises(TypeError, sftx.lookup, "Na", "asdf") + self.assertRaises(TypeError, sftx.lookup, "Na", {}) return + # End of class TestScatteringFactorTable # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testsfaverage.py b/src/diffpy/srreal/tests/testsfaverage.py index f7838405..b23cb8a6 100644 --- a/src/diffpy/srreal/tests/testsfaverage.py +++ b/src/diffpy/srreal/tests/testsfaverage.py @@ -15,24 +15,23 @@ # ---------------------------------------------------------------------------- + class TestSFAverage(unittest.TestCase): def setUp(self): - self.sftx = ScatteringFactorTable.createByType('X') - self.sftn = ScatteringFactorTable.createByType('N') + self.sftx = ScatteringFactorTable.createByType("X") + self.sftn = ScatteringFactorTable.createByType("N") return def tearDown(self): return - def test_fromStructure_CdSe(self): - """check SFAverage.fromStructure() for CdSe - """ - cdse = loadDiffPyStructure('CdSe_cadmoselite.cif') + """check SFAverage.fromStructure() for CdSe""" + cdse = loadDiffPyStructure("CdSe_cadmoselite.cif") sfavg = SFAverage.fromStructure(cdse, self.sftx) - fcd = self.sftx.lookup('Cd') - fse = self.sftx.lookup('Se') + fcd = self.sftx.lookup("Cd") + fse = self.sftx.lookup("Se") self.assertTrue(isinstance(sfavg.f1sum, float)) self.assertAlmostEqual(0.5 * (fcd + fse), sfavg.f1avg) self.assertAlmostEqual(0.5 * (fcd**2 + fse**2), sfavg.f2avg) @@ -46,23 +45,19 @@ def test_fromStructure_CdSe(self): self.assertEqual(sfavg.f2sum, sfavg2.f2sum[0]) sfavg3 = SFAverage.fromStructure(cdse, self.sftn, qa) self.assertEqual(sfavg3.f1sum[0], sfavg3.f1sum[-1]) - sfavg4 = SFAverage.fromStructure(cdse, 'N', qa) + sfavg4 = SFAverage.fromStructure(cdse, "N", qa) self.assertTrue(numpy.array_equal(sfavg3.f1sum, sfavg4.f1sum)) self.assertTrue(numpy.array_equal(sfavg3.f2sum, sfavg4.f2sum)) - sfavg5 = SFAverage.fromStructure(cdse, 'EN', qa) + sfavg5 = SFAverage.fromStructure(cdse, "EN", qa) self.assertFalse(numpy.array_equal(sfavg3.f1sum, sfavg5.f1sum)) - self.assertRaises(TypeError, SFAverage.fromStructure, - 'notastructure', self.sftx) - self.assertRaises(ValueError, SFAverage.fromStructure, - cdse, 'invalid') + self.assertRaises(TypeError, SFAverage.fromStructure, "notastructure", self.sftx) + self.assertRaises(ValueError, SFAverage.fromStructure, cdse, "invalid") return - def test_fromComposition(self): - """check SFAverage.fromComposition() - """ - sfavg1 = SFAverage.fromComposition({'Na' : 1, 'Cl' : 1}, self.sftx) - fm = ['Na', 0.25, 'Cl', 0.75, 'Cl', 0.25, 'Na', 0.5, 'Na', 0.25] + """check SFAverage.fromComposition()""" + sfavg1 = SFAverage.fromComposition({"Na": 1, "Cl": 1}, self.sftx) + fm = ["Na", 0.25, "Cl", 0.75, "Cl", 0.25, "Na", 0.5, "Na", 0.25] smblcnts = zip(fm[0::2], fm[1::2]) sfavg2 = SFAverage.fromComposition(smblcnts, self.sftx) self.assertEqual(sfavg1.f1sum, sfavg2.f1sum) @@ -74,39 +69,40 @@ def test_fromComposition(self): self.assertEqual(0, sfempty.count) return + # End of class TestSFAverage # ---------------------------------------------------------------------------- + @unittest.skipUnless(has_pyobjcryst, _msg_nopyobjcryst) class TestSFAverageObjCryst(unittest.TestCase): def setUp(self): - self.sftx = ScatteringFactorTable.createByType('X') + self.sftx = ScatteringFactorTable.createByType("X") return def tearDown(self): return - def test_from_rutile(self): - """check SFAverage.fromStructure for pyobjcryst Crystal of rutile. - """ - rutile = loadObjCrystCrystal('rutile.cif') + """check SFAverage.fromStructure for pyobjcryst Crystal of rutile.""" + rutile = loadObjCrystCrystal("rutile.cif") qa = numpy.arange(0, 25, 0.1) sfavg = SFAverage.fromStructure(rutile, self.sftx, qa) - fti = self.sftx.lookup('Ti', qa) - fo = self.sftx.lookup('O', qa) + fti = self.sftx.lookup("Ti", qa) + fo = self.sftx.lookup("O", qa) self.assertTrue(numpy.allclose((fti + 2 * fo) / 3.0, sfavg.f1avg)) fti2, fo2 = fti**2, fo**2 self.assertTrue(numpy.allclose((fti2 + 2 * fo2) / 3.0, sfavg.f2avg)) self.assertEqual(6, sfavg.count) + # End of class TestSFAverageObjCryst # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/teststructureadapter.py b/src/diffpy/srreal/tests/teststructureadapter.py index 9224ace9..932a4ddc 100644 --- a/src/diffpy/srreal/tests/teststructureadapter.py +++ b/src/diffpy/srreal/tests/teststructureadapter.py @@ -13,22 +13,28 @@ from diffpy.srreal.tests.testutils import loadDiffPyStructure from diffpy.srreal.tests.testutils import loadCrystalStructureAdapter from diffpy.srreal.structureadapter import ( - createStructureAdapter, nometa, nosymmetry, StructureAdapter, - AtomicStructureAdapter, Atom, PeriodicStructureAdapter, - CrystalStructureAdapter) + createStructureAdapter, + nometa, + nosymmetry, + StructureAdapter, + AtomicStructureAdapter, + Atom, + PeriodicStructureAdapter, + CrystalStructureAdapter, +) import diffpy.srreal.tests.testutils as testutils # ---------------------------------------------------------------------------- + class TestRoutines(unittest.TestCase): def setUp(self): - self.nickel = loadDiffPyStructure('Ni.stru') + self.nickel = loadDiffPyStructure("Ni.stru") return def test_createStructureAdapter(self): - """check createStructureAdapter() routine. - """ + """check createStructureAdapter() routine.""" adpt = createStructureAdapter(self.nickel) self.assertEqual(4, adpt.countSites()) self.assertTrue(False is adpt.siteAnisotropy(0)) @@ -42,11 +48,9 @@ def test_createStructureAdapter(self): return def test_createStructureAdapterTypes(self): - '''Check types returned by conversion from diffpy.structure. - ''' - from diffpy.srreal.structureconverters import ( - DiffPyStructureAtomicAdapter, - DiffPyStructurePeriodicAdapter) + """Check types returned by conversion from diffpy.structure.""" + from diffpy.srreal.structureconverters import DiffPyStructureAtomicAdapter, DiffPyStructurePeriodicAdapter + adpt = createStructureAdapter(self.nickel) self.assertTrue(type(adpt) is DiffPyStructurePeriodicAdapter) self.nickel.pdffit = None @@ -61,8 +65,7 @@ def test_createStructureAdapterTypes(self): return def test_createStructureAdapter_int64_occupancy(self): - """Check Structure conversion when occupany is of numpy.int64 type. - """ + """Check Structure conversion when occupany is of numpy.int64 type.""" self.nickel[0].occupancy = numpy.int64(0) self.nickel[1].occupancy = numpy.int64(1) adpt = createStructureAdapter(self.nickel) @@ -71,38 +74,37 @@ def test_createStructureAdapter_int64_occupancy(self): return def test_pickling(self): - '''check pickling of StructureAdapter instances. - ''' + """check pickling of StructureAdapter instances.""" adpt = createStructureAdapter(self.nickel) adpt1 = pickle.loads(pickle.dumps(adpt)) self.assertFalse(adpt is adpt1) self.assertEqual(adpt.countSites(), adpt1.countSites()) self.assertEqual(adpt.totalOccupancy(), adpt1.totalOccupancy()) self.assertEqual(adpt.siteAtomType(1), adpt1.siteAtomType(1)) - self.assertTrue(numpy.array_equal( - adpt.siteCartesianPosition(1), adpt1.siteCartesianPosition(1))) + self.assertTrue(numpy.array_equal(adpt.siteCartesianPosition(1), adpt1.siteCartesianPosition(1))) self.assertEqual(adpt.siteMultiplicity(1), adpt1.siteMultiplicity(1)) self.assertEqual(adpt.siteOccupancy(1), adpt1.siteOccupancy(1)) self.assertTrue(adpt.siteAnisotropy(1) is adpt1.siteAnisotropy(1)) - self.assertTrue(numpy.array_equal( - adpt.siteCartesianUij(1), adpt1.siteCartesianUij(1))) + self.assertTrue(numpy.array_equal(adpt.siteCartesianUij(1), adpt1.siteCartesianUij(1))) return def test_pickle_nonwrapped(self): - '''Check if pickling works for non-wrapped C++ object. - ''' + """Check if pickling works for non-wrapped C++ object.""" from diffpy.srreal.structureadapter import EMPTY as e0 + spkl = pickle.dumps(e0) e1 = pickle.loads(spkl) self.assertEqual(0, e1.countSites()) return + # End of class TestStructureAdapter # ---------------------------------------------------------------------------- + class TestDerivedAdapter(unittest.TestCase): - 'Check functionality in a Python-derived StructureAdapter class.' + "Check functionality in a Python-derived StructureAdapter class." DerivedCls = testutils.DerivedStructureAdapter @@ -111,8 +113,7 @@ def setUp(self): return def test__customPQConfig(self): - """check if DerivedCls._customPQConfig gets called. - """ + """check if DerivedCls._customPQConfig gets called.""" self.assertEqual(0, self.adpt.cpqcount) pc = PDFCalculator() pc.setStructure(self.adpt) @@ -122,8 +123,7 @@ def test__customPQConfig(self): return def test_pickling(self): - '''check pickling of DerivedCls instances. - ''' + """check pickling of DerivedCls instances.""" self.adpt.cpqcount = 1 adpt1 = pickle.loads(pickle.dumps(self.adpt)) self.assertTrue(self.DerivedCls is type(adpt1)) @@ -136,31 +136,36 @@ def test_pickling(self): self.assertEqual(3, adpt1.cpqcount) return + # End of class TestDerivedAdapter + class TestDerivedAtomicAdapter(TestDerivedAdapter): DerivedCls = testutils.DerivedAtomicStructureAdapter + class TestDerivedPeriodicAdapter(TestDerivedAdapter): DerivedCls = testutils.DerivedPeriodicStructureAdapter + class TestDerivedCrystalAdapter(TestDerivedAdapter): DerivedCls = testutils.DerivedCrystalStructureAdapter + # ---------------------------------------------------------------------------- + class TestNoMeta(unittest.TestCase): def setUp(self): - self.nickel = loadDiffPyStructure('Ni.stru') + self.nickel = loadDiffPyStructure("Ni.stru") return def test_nometa(self): - '''check NoMetaStructureAdapter. - ''' + """check NoMetaStructureAdapter.""" r0, g0 = PDFCalculator()(self.nickel) ni1 = self.nickel.copy() - ni1.pdffit['scale'] = 2.0 + ni1.pdffit["scale"] = 2.0 r1, g1 = PDFCalculator()(ni1) self.assertTrue(numpy.array_equal(r0, r1)) self.assertTrue(numpy.allclose(2 * g0, g1)) @@ -170,7 +175,7 @@ def test_nometa(self): self.assertTrue(numpy.array_equal(r0, r1nm)) self.assertTrue(numpy.allclose(g0, g1nm)) ni2 = self.nickel.copy() - ni2.pdffit['delta2'] = 4 + ni2.pdffit["delta2"] = 4 r2, g2 = PDFCalculator()(ni2) r2, g2nm = PDFCalculator()(nometa(ni2)) self.assertFalse(numpy.allclose(g0, g2)) @@ -183,11 +188,10 @@ def test_nometa(self): return def test_nometa_pickling(self): - '''check pickling of the NoMetaStructureAdapter wrapper. - ''' + """check pickling of the NoMetaStructureAdapter wrapper.""" r0, g0 = PDFCalculator()(self.nickel) ni1 = self.nickel.copy() - ni1.pdffit['scale'] = 2.0 + ni1.pdffit["scale"] = 2.0 ni1nm = pickle.loads(pickle.dumps(nometa(ni1))) self.assertFalse(ni1nm is ni1) r1nm, g1nm = PDFCalculator()(ni1nm) @@ -196,25 +200,25 @@ def test_nometa_pickling(self): return def test_nometa_twice(self): - '''check that second call of nometa returns the same object. - ''' + """check that second call of nometa returns the same object.""" adpt1 = nometa(self.nickel) adpt2 = nometa(adpt1) self.assertTrue(adpt1 is adpt2) + # End of class TestNoMeta # ---------------------------------------------------------------------------- + class TestNoSymmetry(unittest.TestCase): def setUp(self): - self.nickel = loadDiffPyStructure('Ni.stru') + self.nickel = loadDiffPyStructure("Ni.stru") return def test_nosymmetry(self): - '''check NoSymmetryStructureAdapter. - ''' + """check NoSymmetryStructureAdapter.""" pdfc0 = PDFCalculator() r0, g0 = pdfc0(self.nickel) rdf0 = pdfc0.rdf @@ -224,7 +228,7 @@ def test_nosymmetry(self): r1, g1 = pdfc1(niuc) self.assertTrue(numpy.array_equal(r0, r1)) self.assertFalse(numpy.allclose(g0, g1)) - tail = (r0 > 5.0) + tail = r0 > 5.0 self.assertTrue(numpy.allclose(0.0 * g1[tail], g1[tail])) rdf0 = pdfc0.rdf rdf1 = pdfc1.rdf @@ -238,15 +242,13 @@ def test_nosymmetry(self): return def test_nosymmetry_twice(self): - '''check that second call of nosymmetry returns the same object. - ''' + """check that second call of nosymmetry returns the same object.""" adpt1 = nosymmetry(self.nickel) adpt2 = nosymmetry(adpt1) self.assertTrue(adpt1 is adpt2) def test_nosymmetry_pickling(self): - '''check pickling of the NoSymmetryStructureAdapter wrapper. - ''' + """check pickling of the NoSymmetryStructureAdapter wrapper.""" ni1ns = nosymmetry(self.nickel) r1, g1 = PDFCalculator()(ni1ns) ni2ns = pickle.loads(pickle.dumps(ni1ns)) @@ -256,38 +258,38 @@ def test_nosymmetry_pickling(self): self.assertTrue(numpy.array_equal(g1, g2)) return + # End of class TestNoSymmetry # ---------------------------------------------------------------------------- + @unittest.skipUnless(has_pyobjcryst, _msg_nopyobjcryst) class TestPyObjCrystAdapter(unittest.TestCase): def setUp(self): - rutile_crystal = loadObjCrystCrystal('TiO2_rutile-fit.cif') + rutile_crystal = loadObjCrystCrystal("TiO2_rutile-fit.cif") self.rutile = createStructureAdapter(rutile_crystal) return def test_objcryst_adapter(self): - '''check ObjCrystStructureAdapter for rutile. - ''' + """check ObjCrystStructureAdapter for rutile.""" self.assertEqual(2, self.rutile.countSites()) self.assertEqual(6, self.rutile.totalOccupancy()) self.assertEqual("Ti", self.rutile.siteAtomType(0)) self.assertEqual("O", self.rutile.siteAtomType(1)) self.assertTrue(True is self.rutile.siteAnisotropy(0)) self.assertTrue(True is self.rutile.siteAnisotropy(1)) - self.assertTrue(numpy.allclose( - numpy.diag([0.008698, 0.008698, 0.005492]), - self.rutile.siteCartesianUij(0))) - self.assertTrue(numpy.allclose( - numpy.diag([0.021733, 0.021733, 0.007707]), - self.rutile.siteCartesianUij(1))) + self.assertTrue( + numpy.allclose(numpy.diag([0.008698, 0.008698, 0.005492]), self.rutile.siteCartesianUij(0)) + ) + self.assertTrue( + numpy.allclose(numpy.diag([0.021733, 0.021733, 0.007707]), self.rutile.siteCartesianUij(1)) + ) return def test_objcryst_pickling(self): - '''check pickling of the NoSymmetryStructureAdapter wrapper. - ''' + """check pickling of the NoSymmetryStructureAdapter wrapper.""" r0, g0 = PDFCalculator()(self.rutile) rutile1 = pickle.loads(pickle.dumps(self.rutile)) self.assertFalse(self.rutile is rutile1) @@ -296,12 +298,14 @@ def test_objcryst_pickling(self): self.assertTrue(numpy.array_equal(g0, g1)) return + # End of class TestPyObjCrystAdapter # ---------------------------------------------------------------------------- + class IndexRangeTests(object): - 'Check error handling for site index arguments.' + "Check error handling for site index arguments." AdptClass = None @@ -310,73 +314,71 @@ def setUp(self): return def test_siteAtomTypeIndex(self): - """Check out-of-range arguments in AdptClass.siteAtomType. - """ + """Check out-of-range arguments in AdptClass.siteAtomType.""" cnt = self.adpt.countSites() self.assertRaises(IndexError, self.adpt.siteAtomType, cnt) self.assertRaises(IndexError, self.adpt.siteAtomType, -1) return def test_siteCartesianPositionIndex(self): - """Check out-of-range arguments in AdptClass.siteCartesianPosition. - """ + """Check out-of-range arguments in AdptClass.siteCartesianPosition.""" cnt = self.adpt.countSites() self.assertRaises(IndexError, self.adpt.siteCartesianPosition, cnt) self.assertRaises(IndexError, self.adpt.siteCartesianPosition, -1) return def test_siteMultiplicityIndex(self): - """Check out-of-range arguments in AdptClass.siteMultiplicity. - """ + """Check out-of-range arguments in AdptClass.siteMultiplicity.""" cnt = self.adpt.countSites() self.assertRaises(IndexError, self.adpt.siteMultiplicity, cnt) self.assertRaises(IndexError, self.adpt.siteMultiplicity, -1) return def test_siteOccupancyIndex(self): - """Check out-of-range arguments in AdptClass.siteOccupancy. - """ + """Check out-of-range arguments in AdptClass.siteOccupancy.""" cnt = self.adpt.countSites() self.assertRaises(IndexError, self.adpt.siteOccupancy, cnt) self.assertRaises(IndexError, self.adpt.siteOccupancy, -1) return def test_siteAnisotropyIndex(self): - """Check out-of-range arguments in AdptClass.siteAnisotropy. - """ + """Check out-of-range arguments in AdptClass.siteAnisotropy.""" cnt = self.adpt.countSites() self.assertRaises(IndexError, self.adpt.siteAnisotropy, cnt) self.assertRaises(IndexError, self.adpt.siteAnisotropy, -1) return def test_siteCartesianUijIndex(self): - """Check out-of-range arguments in AdptClass.siteCartesianUij. - """ + """Check out-of-range arguments in AdptClass.siteCartesianUij.""" cnt = self.adpt.countSites() self.assertRaises(IndexError, self.adpt.siteCartesianUij, cnt) self.assertRaises(IndexError, self.adpt.siteCartesianUij, -1) return + # End of class IndexRangeTests TestCase = unittest.TestCase # test index bounds for C++ classes + class TestAtomicAdapterIndexRange(IndexRangeTests, TestCase): AdptClass = AtomicStructureAdapter + # No need to do index tests for PeriodicStructureAdapter as it does not # override any of AtomicStructureAdapter site-access methods. # CrystalStructureAdapter overrides siteMultiplicity so we'll # test it here as well. + class TestCrystalAdapter(IndexRangeTests, TestCase): AdptClass = CrystalStructureAdapter def test_expandLatticeAtom(self): """Check CrystalStructureAdapter.expandLatticeAtom.""" - cdse = loadCrystalStructureAdapter('CdSe_cadmoselite.cif') + cdse = loadCrystalStructureAdapter("CdSe_cadmoselite.cif") a = Atom() a.xyz_cartn = (0.1, 0.13, 0.17) asymsites = cdse.expandLatticeAtom(a) @@ -387,18 +389,20 @@ def test_expandLatticeAtom(self): def test_getEquivalentAtoms(self): """Check CrystalStructureAdapter.getEquivalentAtoms.""" - cdse = loadCrystalStructureAdapter('CdSe_cadmoselite.cif') + cdse = loadCrystalStructureAdapter("CdSe_cadmoselite.cif") eqatoms0 = cdse.getEquivalentAtoms(0) eqatoms1 = cdse.getEquivalentAtoms(1) self.assertTrue(type(eqatoms1) is list) self.assertEqual(2, len(eqatoms0)) self.assertEqual(2, len(eqatoms1)) - self.assertTrue(all(a.atomtype == "Cd" for a in eqatoms0)) - self.assertTrue(all(a.atomtype == "Se" for a in eqatoms1)) + self.assertTrue(all(a.atomtype == "Cd" for a in eqatoms0)) + self.assertTrue(all(a.atomtype == "Se" for a in eqatoms1)) return + # ---------------------------------------------------------------------------- + class TestDerivedStructureAdapter(IndexRangeTests, TestCase): AdptClass = testutils.DerivedStructureAdapter @@ -409,121 +413,112 @@ def setUp(self): return def test_siteAtomType_valid(self): - """Check DerivedStructureAdapter.siteAtomType. - """ + """Check DerivedStructureAdapter.siteAtomType.""" adpt1 = self.adpt1 self.assertEqual("Cu", adpt1.siteAtomType(0)) self.assertEqual("", StructureAdapter.siteAtomType(adpt1, 0)) return def test_siteCartesianPosition_valid(self): - """Check DerivedStructureAdapter.siteCartesianPosition. - """ + """Check DerivedStructureAdapter.siteCartesianPosition.""" adpt1 = self.adpt1 xyz0 = adpt1.siteCartesianPosition(0) self.assertTrue(numpy.array_equal([1, 2, 3], xyz0)) return def test_siteMultiplicity_valid(self): - """Check DerivedStructureAdapter.siteMultiplicity. - """ + """Check DerivedStructureAdapter.siteMultiplicity.""" adpt1 = self.adpt1 self.assertEqual(2, adpt1.siteMultiplicity(0)) self.assertEqual(1, StructureAdapter.siteMultiplicity(adpt1, 0)) return def test_siteOccupancy_valid(self): - """Check DerivedStructureAdapter.siteOccupancy. - """ + """Check DerivedStructureAdapter.siteOccupancy.""" adpt1 = self.adpt1 self.assertEqual(0.5, adpt1.siteOccupancy(0)) self.assertEqual(1.0, StructureAdapter.siteOccupancy(adpt1, 0)) return def test_siteAnisotropy_valid(self): - """Check DerivedStructureAdapter.siteAnisotropy. - """ + """Check DerivedStructureAdapter.siteAnisotropy.""" adpt1 = self.adpt1 self.assertFalse(adpt1.siteAnisotropy(0)) return def test_siteCartesianUij_valid(self): - """Check DerivedStructureAdapter.siteCartesianUij. - """ + """Check DerivedStructureAdapter.siteCartesianUij.""" adpt1 = self.adpt1 uiso = 0.005 * numpy.identity(3) self.assertTrue(numpy.array_equal(uiso, adpt1.siteCartesianUij(0))) self.assertRaises(IndexError, adpt1.siteCartesianUij, 1) return + # End of class TestDerivedStructureAdapter # ---------------------------------------------------------------------------- + class TestStructureAdapter(unittest.TestCase): def setUp(self): self.adpt = StructureAdapter() return -# def test__customPQConfig(self): -# """check StructureAdapter._customPQConfig() -# """ -# return -# -# def test_countSites(self): -# """check StructureAdapter.countSites() -# """ -# return -# -# def test_createBondGenerator(self): -# """check StructureAdapter.createBondGenerator() -# """ -# return -# -# def test_numberDensity(self): -# """check StructureAdapter.numberDensity() -# """ -# return + # def test__customPQConfig(self): + # """check StructureAdapter._customPQConfig() + # """ + # return + # + # def test_countSites(self): + # """check StructureAdapter.countSites() + # """ + # return + # + # def test_createBondGenerator(self): + # """check StructureAdapter.createBondGenerator() + # """ + # return + # + # def test_numberDensity(self): + # """check StructureAdapter.numberDensity() + # """ + # return def test_siteAtomType(self): - """check StructureAdapter.siteAtomType() - """ + """check StructureAdapter.siteAtomType()""" self.assertEqual("", self.adpt.siteAtomType(0)) return def test_siteCartesianPosition(self): - """check StructureAdapter.siteCartesianPosition() - """ + """check StructureAdapter.siteCartesianPosition()""" self.assertRaises(RuntimeError, self.adpt.siteAnisotropy, 0) return def test_siteMultiplicity(self): - """check StructureAdapter.siteMultiplicity() - """ + """check StructureAdapter.siteMultiplicity()""" self.assertEqual(1, self.adpt.siteMultiplicity(0)) return def test_siteOccupancy(self): - """check StructureAdapter.siteOccupancy() - """ + """check StructureAdapter.siteOccupancy()""" # check if we use the C++ method that alwasy return 1. self.assertEqual(1.0, self.adpt.siteOccupancy(0)) self.assertEqual(1.0, self.adpt.siteOccupancy(99)) return def test_siteAnisotropy(self): - """check StructureAdapter.siteAnisotropy() - """ + """check StructureAdapter.siteAnisotropy()""" self.assertRaises(RuntimeError, self.adpt.siteAnisotropy, 0) return def test_siteCartesianUij(self): - """check StructureAdapter.siteCartesianUij() - """ + """check StructureAdapter.siteCartesianUij()""" self.assertRaises(RuntimeError, self.adpt.siteCartesianUij, 0) return + # def test_totalOccupancy(self): # """check StructureAdapter.totalOccupancy() # """ @@ -533,6 +528,7 @@ def test_siteCartesianUij(self): # ---------------------------------------------------------------------------- + class TestAtom(unittest.TestCase): def setUp(self): @@ -540,8 +536,7 @@ def setUp(self): return def test___init__copy(self): - '''check Atom copy constructor. - ''' + """check Atom copy constructor.""" self.a.xyz_cartn = (1, 2, 3) a1 = Atom(self.a) self.assertEqual(self.a, a1) @@ -549,18 +544,16 @@ def test___init__copy(self): return def test_equality(self): - '''check Atom equal and not equal operators. - ''' + """check Atom equal and not equal operators.""" self.assertEqual(self.a, Atom()) self.assertFalse(self.a != Atom()) a1 = Atom() - a1.atomtype = 'Na' + a1.atomtype = "Na" self.assertNotEqual(self.a, a1) return def test_pickling(self): - '''check pickling of Atom instances. - ''' + """check pickling of Atom instances.""" self.a.atomtype = "Na" a1 = pickle.loads(pickle.dumps(self.a)) self.assertEqual("Na", a1.atomtype) @@ -569,8 +562,7 @@ def test_pickling(self): return def test_xyz_cartn(self): - '''check Atom.xyz_cartn. - ''' + """check Atom.xyz_cartn.""" a = self.a a.xyz_cartn = 4, 5, 6 self.assertTrue(numpy.array_equal([4, 5, 6], a.xyz_cartn)) @@ -580,17 +572,15 @@ def test_xyz_cartn(self): return def test_uij_cartn(self): - '''check Atom.uij_cartn - ''' + """check Atom.uij_cartn""" a = self.a a.uij_cartn = numpy.identity(3) * 0.01 a.uc12 = 0.012 a.uc13 = 0.013 a.uc23 = 0.023 - self.assertTrue(numpy.array_equal(a.uij_cartn, [ - [0.01, 0.012, 0.013], - [0.012, 0.01, 0.023], - [0.013, 0.023, 0.01]])) + self.assertTrue( + numpy.array_equal(a.uij_cartn, [[0.01, 0.012, 0.013], [0.012, 0.01, 0.023], [0.013, 0.023, 0.01]]) + ) self.assertEqual(0.01, a.uc11) self.assertEqual(0.01, a.uc22) self.assertEqual(0.01, a.uc33) @@ -600,7 +590,7 @@ def test_uij_cartn(self): return def test_xc_yc_zc(self): - 'check Atom properties xc, yc, zc.' + "check Atom properties xc, yc, zc." a = self.a a.xc, a.yc, a.zc = numpy.arange(1, 4) self.assertEqual(1.0, a.xc) @@ -609,18 +599,18 @@ def test_xc_yc_zc(self): return def test_occupancy(self): - 'check Atom.occupancy' + "check Atom.occupancy" a = self.a - a.occupancy, = numpy.arange(1) + (a.occupancy,) = numpy.arange(1) self.assertEqual(0.0, a.occupancy) a.occupancy = numpy.float32(0.5) self.assertEqual(0.5, a.occupancy) return def test_anisotropy(self): - 'check Atom.anisotropy' + "check Atom.anisotropy" a = self.a - nptrue, npfalse = (numpy.arange(2) < 1) + nptrue, npfalse = numpy.arange(2) < 1 a.anisotropy = nptrue self.assertTrue(a.anisotropy) a.anisotropy = npfalse @@ -628,18 +618,19 @@ def test_anisotropy(self): return def test_ucij(self): - 'check Atom attributes u11, u22, etc.' + "check Atom attributes u11, u22, etc." a = self.a a.uc11, a.uc22, a.uc33, a.uc12, a.uc13, a.uc23 = numpy.arange(1, 7) uijexp = [[1, 4, 5], [4, 2, 6], [5, 6, 3]] self.assertTrue(numpy.array_equal(uijexp, a.uij_cartn)) return + # End of class TestAtom # ---------------------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() # End of file diff --git a/src/diffpy/srreal/tests/testutils.py b/src/diffpy/srreal/tests/testutils.py index 0cead96d..c16ae8dd 100644 --- a/src/diffpy/srreal/tests/testutils.py +++ b/src/diffpy/srreal/tests/testutils.py @@ -32,37 +32,42 @@ _msg_nopyobjcryst = "No module named 'pyobjcryst'" try: import pyobjcryst.crystal + convertObjCrystCrystal(pyobjcryst.crystal.Crystal()) has_pyobjcryst = True except ImportError: has_pyobjcryst = False - logger.warning('Cannot import pyobjcryst, pyobjcryst tests skipped.') + logger.warning("Cannot import pyobjcryst, pyobjcryst tests skipped.") except TypeError: has_pyobjcryst = False - logger.warning('Compiled without ObjCryst, pyobjcryst tests skipped.') + logger.warning("Compiled without ObjCryst, pyobjcryst tests skipped.") # periodictable _msg_noperiodictable = "No module named 'periodictable'" try: import periodictable + has_periodictable = True # silence the pyflakes syntax checker del periodictable except ImportError: has_periodictable = False - logger.warning('Cannot import periodictable, periodictable tests skipped.') + logger.warning("Cannot import periodictable, periodictable tests skipped.") # helper functions + def datafile(filename): from pkg_resources import resource_filename + rv = resource_filename(__name__, "testdata/" + filename) return rv def loadObjCrystCrystal(filename): from pyobjcryst import loadCrystal + fullpath = datafile(filename) crst = loadCrystal(fullpath) return crst @@ -76,8 +81,9 @@ def loadDiffPyStructure(filename): def loadCrystalStructureAdapter(filename): from diffpy.srreal.structureconverters import _fetchDiffPyStructureData + fullpath = datafile(filename) - pcif = getParser('cif') + pcif = getParser("cif") stru = pcif.parseFile(fullpath) asu = stru[:0] + pcif.asymmetric_unit adpt = CrystalStructureAdapter() @@ -95,6 +101,7 @@ def pickle_with_attr(obj, **attr): rv = pickle.dumps(obj) return rv + # helper class for testing overloading of StructureAdapter from diffpy.srreal.structureadapter import StructureAdapter @@ -102,6 +109,7 @@ def pickle_with_attr(obj, **attr): from diffpy.srreal.structureadapter import PeriodicStructureAdapter from diffpy.srreal.structureadapter import CrystalStructureAdapter + class HasCustomPQConfig(object): cpqcount = 0 @@ -117,17 +125,15 @@ def __init__(self): StructureAdapter.__init__(self) self.positions = [] - def clone(self): rv = DerivedStructureAdapter() rv.positions[:] = copy.deepcopy(self.positions) return rv - def createBondGenerator(self): from diffpy.srreal.structureadapter import BaseBondGenerator - return BaseBondGenerator(self) + return BaseBondGenerator(self) def countSites(self): return len(self.positions) @@ -139,16 +145,13 @@ def siteAtomType(self, idx): self._checkindex(idx) return "Cu" - def siteCartesianPosition(self, idx): return self.positions[idx] - def siteMultiplicity(self, idx): self._checkindex(idx) return 2 * StructureAdapter.siteMultiplicity(self, idx) - def siteOccupancy(self, idx): self._checkindex(idx) return 0.5 * StructureAdapter.siteOccupancy(self, idx) @@ -157,28 +160,28 @@ def siteAnisotropy(self, idx): self._checkindex(idx) return False - def siteCartesianUij(self, idx): self._checkindex(idx) return numpy.identity(3, dtype=float) * 0.005 - def _checkindex(self, idx): self.positions[idx] return + # End of class DerivedStructureAdapter -class DerivedAtomicStructureAdapter( - HasCustomPQConfig, AtomicStructureAdapter): + +class DerivedAtomicStructureAdapter(HasCustomPQConfig, AtomicStructureAdapter): pass -class DerivedPeriodicStructureAdapter( - HasCustomPQConfig, PeriodicStructureAdapter): + +class DerivedPeriodicStructureAdapter(HasCustomPQConfig, PeriodicStructureAdapter): pass -class DerivedCrystalStructureAdapter( - HasCustomPQConfig, CrystalStructureAdapter): + +class DerivedCrystalStructureAdapter(HasCustomPQConfig, CrystalStructureAdapter): pass + # End of file diff --git a/src/diffpy/srreal/version.py b/src/diffpy/srreal/version.py index 8d8feeba..a078d249 100644 --- a/src/diffpy/srreal/version.py +++ b/src/diffpy/srreal/version.py @@ -25,8 +25,7 @@ Use `libdiffpy_version_info.git_commit` instead. """ -__all__ = ['__date__', '__git_commit__', '__timestamp__', '__version__', - 'libdiffpy_version_info'] +__all__ = ["__date__", "__git_commit__", "__timestamp__", "__version__", "libdiffpy_version_info"] from diffpy.srreal._version_data import __version__ @@ -43,22 +42,24 @@ from diffpy.srreal.srreal_ext import _get_libdiffpy_version_info_dict libdiffpy_version_info = namedtuple( - 'libdiffpy_version_info', + "libdiffpy_version_info", "major minor micro patch version_number version date git_commit " + # TODO remove git_sha in version 1.4. - "git_sha") + "git_sha", +) vd = _get_libdiffpy_version_info_dict() libdiffpy_version_info = libdiffpy_version_info( - version = vd['version_str'], - version_number = vd['version'], - major = vd['major'], - minor = vd['minor'], - micro = vd['micro'], - patch = vd['patch'], - date = vd['date'], - git_commit = vd['git_commit'], - # TODO remove git_sha in version 1.4. - git_sha = vd['git_commit']) + version=vd["version_str"], + version_number=vd["version"], + major=vd["major"], + minor=vd["minor"], + micro=vd["micro"], + patch=vd["patch"], + date=vd["date"], + git_commit=vd["git_commit"], + # TODO remove git_sha in version 1.4. + git_sha=vd["git_commit"], +) del vd # End of file diff --git a/src/diffpy/srreal/wraputils.py b/src/diffpy/srreal/wraputils.py index 79261ec3..e9eb19e1 100644 --- a/src/diffpy/srreal/wraputils.py +++ b/src/diffpy/srreal/wraputils.py @@ -21,25 +21,29 @@ # Routines ------------------------------------------------------------------- + def propertyFromExtDoubleAttr(attrname, doc): - '''Create property wrapper to a DoubleAttr in C++ extension object. + """Create property wrapper to a DoubleAttr in C++ extension object. attrname -- string name of the double attribute doc -- docstring for the Python class property Return a property object. - ''' + """ + def fget(self): return self._getDoubleAttr(attrname) + def fset(self, value): self._setDoubleAttr(attrname, value) return + rv = property(fget, fset, doc=doc) return rv def setattrFromKeywordArguments(obj, **kwargs): - '''Set attributes of the obj according to keyword arguments. + """Set attributes of the obj according to keyword arguments. For example: setattrFromKeywordArguments(obj, qmax=24, scale=2) This is a shared helper function used by __init__ and __call__. @@ -47,7 +51,7 @@ def setattrFromKeywordArguments(obj, **kwargs): No return value. Raise TypeError for invalid keyword argument. - ''' + """ for n in kwargs: if not hasattr(obj, n): emsg = "Invalid keyword argument %r" % n @@ -58,7 +62,7 @@ def setattrFromKeywordArguments(obj, **kwargs): def _wrapAsRegisteredUnaryFunction(cls, regname, fnc, replace=False, **dbattrs): - '''Helper function for wrapping Python function as PDFBaseline or + """Helper function for wrapping Python function as PDFBaseline or PDFEnvelope functor. Not intended for direct usage, this function is rather called from makePDFBaseline or makePDFEnvelope wrappers. @@ -79,33 +83,31 @@ def _wrapAsRegisteredUnaryFunction(cls, regname, fnc, replace=False, **dbattrs): fnc(x, **dbattrs). Return an instance of the functor class. - ''' + """ + class RegisteredUnaryFunction(cls): def create(self): - '''Create new instance of the same type as self. - ''' + """Create new instance of the same type as self.""" return RegisteredUnaryFunction() def clone(self): - '''Return a new duplicate instance of self. - ''' + """Return a new duplicate instance of self.""" return copy.copy(self) def type(self): - '''Unique string identifier of this functor type. The string + """Unique string identifier of this functor type. The string is used for class registration and as an argument for the createByType function. Return string identifier. - ''' + """ return regname def __call__(self, x): - '''Evaluate this functor at x. - ''' + """Evaluate this functor at x.""" if dbattrs: - kw = {n : getattr(self, n) for n in dbattrs} + kw = {n: getattr(self, n) for n in dbattrs} rv = fnc(x, **kw) else: rv = fnc(x) @@ -126,7 +128,7 @@ def __reduce__(self): if replace: RegisteredUnaryFunction._deregisterType(regname) - RegisteredUnaryFunction.__name__ = 'User' + cls.__name__ + '_' + regname + RegisteredUnaryFunction.__name__ = "User" + cls.__name__ + "_" + regname RegisteredUnaryFunction.__getstate__ = _pickle_getstate RegisteredUnaryFunction.__setstate__ = _pickle_setstate RegisteredUnaryFunction()._registerThisType() @@ -134,21 +136,25 @@ def __reduce__(self): assert type(rv) is RegisteredUnaryFunction return rv + # pickling support functions + def _regunary_create(cls, tp): return cls.createByType(tp) + def _pickle_getstate(self): state = (self.__dict__,) return state + def _pickle_setstate(self, state): if len(state) != 1: - emsg = ("expected 1-item tuple in call to __setstate__, got " + - repr(state)) + emsg = "expected 1-item tuple in call to __setstate__, got " + repr(state) raise ValueError(emsg) self.__dict__.update(state[0]) return + # End of file