diff --git a/.codespell/ignore_lines.txt b/.codespell/ignore_lines.txt new file mode 100644 index 00000000..07fa7c8c --- /dev/null +++ b/.codespell/ignore_lines.txt @@ -0,0 +1,2 @@ +;; Please include filenames and explanations for each ignored line. +;; See https://docs.openverse.org/meta/codespell.html for docs. diff --git a/.codespell/ignore_words.txt b/.codespell/ignore_words.txt new file mode 100644 index 00000000..3b490070 --- /dev/null +++ b/.codespell/ignore_words.txt @@ -0,0 +1,29 @@ +;; Please include explanations for each ignored word (lowercase). +;; See https://docs.openverse.org/meta/codespell.html for docs. + +;; abbreviation for "materials" often used in a journal title +mater + +;; alternative use of socioeconomic +socio-economic + +;; Frobenius norm used in np.linalg.norm +fro + +;; abbreviation for "structure" +struc + +;; method name within JournalPanel class +onText + +;; a method name within JournalPanel class +delt + +;; structure file format +discus + +;; variable name within pdfbaseline module +aline + +;; variable name within TestSFAverageObjCryst class +fo diff --git a/.flake8 b/.flake8 new file mode 100644 index 00000000..04d2d0b0 --- /dev/null +++ b/.flake8 @@ -0,0 +1,13 @@ +# As of now, flake8 does not natively support configuration via pyproject.toml +# https://github.com/microsoft/vscode-flake8/issues/135 +[flake8] +exclude = + .git, + __pycache__, + build, + dist, + doc/source/conf.py +max-line-length = 115 +# Ignore some style 'errors' produced while formatting by 'black' +# https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#labels-why-pycodestyle-warnings +extend-ignore = E203 diff --git a/.isort.cfg b/.isort.cfg new file mode 100644 index 00000000..7ce0fb1f --- /dev/null +++ b/.isort.cfg @@ -0,0 +1,5 @@ +[settings] +# Keep import statement below line_length character limit +line_length = 115 +multi_line_output = 3 +include_trailing_comma = True diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..754e5329 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,67 @@ +default_language_version: + python: python3 +ci: + autofix_commit_msg: | + [pre-commit.ci] auto fixes from pre-commit hooks + autofix_prs: true + autoupdate_branch: "pre-commit-autoupdate" + autoupdate_commit_msg: "[pre-commit.ci] pre-commit autoupdate" + autoupdate_schedule: monthly + skip: [no-commit-to-branch] + submodules: false +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: check-yaml + exclude: ^conda-recipe/meta\.yaml$ + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-case-conflict + - id: check-merge-conflict + - id: check-toml + - id: check-added-large-files + - repo: https://github.com/psf/black + rev: 24.4.2 + hooks: + - id: black + - repo: https://github.com/pycqa/flake8 + rev: 7.0.0 + hooks: + - id: flake8 + - repo: https://github.com/pycqa/isort + rev: 5.13.2 + hooks: + - id: isort + args: ["--profile", "black"] + - repo: https://github.com/kynan/nbstripout + rev: 0.7.1 + hooks: + - id: nbstripout + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: no-commit-to-branch + name: Prevent Commit to Main Branch + args: ["--branch", "main"] + stages: [pre-commit] + - repo: https://github.com/codespell-project/codespell + rev: v2.3.0 + hooks: + - id: codespell + additional_dependencies: + - tomli + # prettier - multi formatter for .json, .yml, and .md files + - repo: https://github.com/pre-commit/mirrors-prettier + rev: f12edd9c7be1c20cfa42420fd0e6df71e42b51ea # frozen: v4.0.0-alpha.8 + hooks: + - id: prettier + additional_dependencies: + - "prettier@^3.2.4" + # docformatter - PEP 257 compliant docstring formatter + - repo: https://github.com/s-weigand/docformatter + rev: 5757c5190d95e5449f102ace83df92e7d3b06c6c + hooks: + - id: docformatter + additional_dependencies: [tomli] + args: [--in-place, --config, ./pyproject.toml] diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..7f39adde --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +/conda-recipe/* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index de49f467..00000000 --- a/.travis.yml +++ /dev/null @@ -1,130 +0,0 @@ -dist: xenial -language: generic - -os: - - linux - - osx - -env: - - MYUSEMC=true MYPYTHON_VERSION=2.7 - - MYUSEMC=true MYPYTHON_VERSION=3.5 - - MYUSEMC=true MYPYTHON_VERSION=3.6 - - MYUSEMC=true MYPYTHON_VERSION=3.7 - - MYUSEMC=false - -git: - depth: 999999 - -branches: - except: - - /^v[0-9]/ - - -before_install: - - MYNAME=diffpy.srreal - - MYCOMMIT="$(git rev-parse HEAD)" - - umask 022 - - git fetch origin --tags - - MYPYTHON=python; MYPIP=pip - - NOSYS=true; NOAPT=true; NOBREW=true; NOMC=true - - if ${MYUSEMC}; then - NOMC=false; - elif [[ ${TRAVIS_OS_NAME} == linux ]]; then - NOAPT=false; NOSYS=false; - MYPIPFLAGS="--user"; - elif [[ ${TRAVIS_OS_NAME} == osx ]]; then - NOBREW=false; NOSYS=false; - MYPYTHON=python3; - MYPIP=pip3; - MYPIPFLAGS="--user"; - fi - - MYMCREPO=https://repo.anaconda.com/miniconda - - case ${TRAVIS_OS_NAME} in - linux) - MYMCBUNDLE=Miniconda3-latest-Linux-x86_64.sh ;; - osx) - MYMCBUNDLE=Miniconda3-latest-MacOSX-x86_64.sh ;; - *) - echo "Unsupported operating system." >&2; - exit 2 ;; - esac - - MYRUNDIR=${PWD}/build/rundir - - - mkdir -p ~/pkgs - - mkdir -p ${MYRUNDIR} - - cp .coveragerc ${MYRUNDIR}/ - - - $NOMC || pushd ~/pkgs - - $NOMC || wget --timestamping ${MYMCREPO}/${MYMCBUNDLE} - - $NOMC || test -x ~/mc/bin/conda || bash ${MYMCBUNDLE} -b -f -p ~/mc - - $NOMC || popd - - $NOMC || source ~/mc/bin/activate base - - $NOMC || conda update --yes conda - - $NOMC || conda install --yes conda-build conda-verify jinja2 numpy - - $NOMC || conda create --name=testenv --yes python=${MYPYTHON_VERSION} coverage - - $NOMC || conda config --add channels diffpy - - - $NOAPT || test "${TRAVIS_OS_NAME}" = "linux" || exit $? - - $NOAPT || PATH="$(echo "$PATH" | sed 's,:/opt/pyenv/[^:]*,,g')" - - $NOAPT || test "$(which python)" = "/usr/bin/python" || ( - which python; exit 1) - - $NOAPT || sudo apt-get update -qq - - $NOAPT || sudo apt-get install -y - libgsl0-dev libboost-all-dev python-dev - python-setuptools python-numpy python-pyparsing - python-lxml python-pip build-essential scons - - - $NOBREW || test "${TRAVIS_OS_NAME}" = "osx" || exit $? - - $NOBREW || brew update - - $NOBREW || brew install gcc || brew link --overwrite gcc - - $NOBREW || brew install boost-python3 - - $NOBREW || brew install gsl - - $NOBREW || brew install scons - - - $NOSYS || devutils/makesdist - - $NOSYS || MYTARBUNDLE="$(ls -t "${PWD}"/dist/*.tar.gz | head -1)" - - $NOSYS || pushd ~/pkgs - - $NOSYS || git clone https://github.com/diffpy/libobjcryst.git - - $NOSYS || git clone https://github.com/diffpy/libdiffpy.git - - $NOSYS || popd - - -install: - - $NOMC || conda build --python=${MYPYTHON_VERSION} conda-recipe - - $NOMC || conda render --python=${MYPYTHON_VERSION} --output conda-recipe | - sed 's,.*/,,; s/[.]tar[.]bz2$//; s/-/=/g' > /tmp/mypackage.txt - - $NOMC || source activate testenv - - $NOMC || conda install --yes --use-local --file=/tmp/mypackage.txt - - - MYSUDO= - - $NOAPT || MYSUDO=sudo - - $NOSYS || $MYPIP install $MYPIPFLAGS coverage - - $NOSYS || $MYPIP install $MYPIPFLAGS periodictable - - $NOSYS || $MYPIP install $MYPIPFLAGS pycifrw - - $NOSYS || $MYPIP install $MYPIPFLAGS diffpy.structure - - - $NOSYS || $MYSUDO scons -C ~/pkgs/libobjcryst install - - $NOSYS || $MYPIP install $MYPIPFLAGS pyobjcryst - - $NOSYS || $MYSUDO scons -C ~/pkgs/libdiffpy install - - $NOSYS || $MYPIP install $MYPIPFLAGS "${MYTARBUNDLE}" - - - cd ${MYRUNDIR} - - MYGIT_REV=$($MYPYTHON -c "import ${MYNAME}.version as v; print(v.__git_commit__)") - - if [[ "${MYCOMMIT}" != "${MYGIT_REV}" ]]; then - echo "Version mismatch ${MYCOMMIT} vs ${MYGIT_REV}."; - exit 1; - fi - - -before_script: - - $NOBREW || USER_BASE="$(python3 -c 'import site; print(site.USER_BASE)')" - - $NOBREW || PATH="${USER_BASE}/bin:${PATH}" - - -script: - - coverage run --source ${MYNAME} -m ${MYNAME}.tests.run - - -after_success: - - $MYPIP install $MYPIPFLAGS codecov - - codecov diff --git a/README.rst b/README.rst index 3a87d0a5..f6388b27 100644 --- a/README.rst +++ b/README.rst @@ -114,7 +114,7 @@ parallel jobs (-j4) :: sudo scons -j4 install -See ``scons -h`` for decription of build targets and options. +See ``scons -h`` for description of build targets and options. DEVELOPMENT diff --git a/devutils/makesdist b/devutils/makesdist index 06e07d7c..10bba1ff 100755 --- a/devutils/makesdist +++ b/devutils/makesdist @@ -1,52 +1,56 @@ #!/usr/bin/env python -'''Create source distribution tar.gz archive, where each file belongs -to a root user and modification time is set to the git commit time. -''' +"""Create source distribution tar.gz archive, where each file belongs to a root +user and modification time is set to the git commit time.""" -import sys +import glob +import gzip import os import subprocess -import glob +import sys import tarfile -import gzip + +from setup import FALLBACK_VERSION, versiondata BASEDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.insert(0, BASEDIR) -from setup import versiondata, FALLBACK_VERSION -timestamp = versiondata.getint('DEFAULT', 'timestamp') +timestamp = versiondata.getint("DEFAULT", "timestamp") -vfb = versiondata.get('DEFAULT', 'version').split('.post')[0] + '.post0' +vfb = versiondata.get("DEFAULT", "version").split(".post")[0] + ".post0" emsg = "Invalid FALLBACK_VERSION. Expected %r got %r." assert vfb == FALLBACK_VERSION, emsg % (vfb, FALLBACK_VERSION) + def inform(s): sys.stdout.write(s) sys.stdout.flush() return + inform('Run "setup.py sdist --formats=tar" ') -cmd_sdist = ([sys.executable, '-Wignore:Cannot detect name suffix'] + - 'setup.py sdist --formats=tar'.split()) -ec = subprocess.call(cmd_sdist, cwd=BASEDIR, stdout=open(os.devnull, 'w')) -if ec: sys.exit(ec) +cmd_sdist = [sys.executable, "-Wignore:Cannot detect name suffix"] + "setup.py sdist --formats=tar".split() +ec = subprocess.call(cmd_sdist, cwd=BASEDIR, stdout=open(os.devnull, "w")) +if ec: + sys.exit(ec) inform("[done]\n") -tarname = max(glob.glob(BASEDIR + '/dist/*.tar'), key=os.path.getmtime) +tarname = max(glob.glob(BASEDIR + "/dist/*.tar"), key=os.path.getmtime) tfin = tarfile.open(tarname) -fpout = gzip.GzipFile(tarname + '.gz', 'w', mtime=0) -tfout = tarfile.open(fileobj=fpout, mode='w') +fpout = gzip.GzipFile(tarname + ".gz", "w", mtime=0) +tfout = tarfile.open(fileobj=fpout, mode="w") + def fixtarinfo(tinfo): tinfo.uid = tinfo.gid = 0 - tinfo.uname = tinfo.gname = 'root' + tinfo.uname = tinfo.gname = "root" tinfo.mtime = timestamp tinfo.mode &= ~0o022 return tinfo -inform('Filter %s --> %s.gz ' % (2 * (os.path.basename(tarname),))) + +inform("Filter %s --> %s.gz " % (2 * (os.path.basename(tarname),))) for ti in tfin: tfout.addfile(fixtarinfo(ti), tfin.extractfile(ti)) diff --git a/devutils/tunePeakPrecision.py b/devutils/tunePeakPrecision.py index e46c9616..c6f3cc94 100755 --- a/devutils/tunePeakPrecision.py +++ b/devutils/tunePeakPrecision.py @@ -1,11 +1,21 @@ #!/usr/bin/env python -"""Tune the peak precision parameter so that PDFCalculator -gives equivalent results to diffpy.pdffit2. +"""Tune the peak precision parameter so that PDFCalculator gives equivalent +results to diffpy.pdffit2. Usage: tunePeakPrecision.py [qmax] [peakprecision] [createplot] """ +# global imports +import sys +import time + +import numpy + +import diffpy.pdffit2 +from diffpy.srreal.pdf_ext import PDFCalculator +from diffpy.structure import Structure + # Results: # Qmax peakprecision CPU Notes # 15 3.2e-6 clear minimum @@ -21,16 +31,6 @@ peakprecision = None createplot = False -# global imports -import sys -import time - -import numpy - -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")) @@ -52,7 +52,7 @@ def Gpdffit2(qmax): - """Calculate reference nickel PDF using diffpy.pdffit2 + """Calculate reference nickel PDF using diffpy.pdffit2. qmax -- vawevector cutoff value in 1/A @@ -68,7 +68,7 @@ def Gpdffit2(qmax): def Gsrreal(qmax, peakprecision=None): - """Calculate nickel PDF using PDFCalculator from diffpy.srreal + """Calculate nickel PDF using PDFCalculator from diffpy.srreal. qmax -- vawevector cutoff value in 1/A peakprecision -- precision factor affecting peak cutoff, diff --git a/doc/manual/source/conf.py b/doc/manual/source/conf.py index 307ec098..326acdd8 100644 --- a/doc/manual/source/conf.py +++ b/doc/manual/source/conf.py @@ -12,10 +12,12 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys import os +import sys import time +from setup import versiondata + # 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. @@ -61,7 +63,6 @@ # 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") # The short X.Y version. diff --git a/examples/compareC60PDFs.py b/examples/compareC60PDFs.py index 03311ec1..844cd7a6 100755 --- a/examples/compareC60PDFs.py +++ b/examples/compareC60PDFs.py @@ -1,14 +1,17 @@ #!/usr/bin/env python """Plot C60 PDFs calculated with PDFCalculator and DebyePDFCalculator. + The C60 molecule is held in a diffpy Structure object. """ -import sys import os -from matplotlib.pyplot import plot, show, clf +import sys + +from matplotlib.pyplot import clf, plot, show + +from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator from diffpy.structure import Structure -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") diff --git a/examples/compareC60PDFs_objcryst.py b/examples/compareC60PDFs_objcryst.py index 69c9143a..62e705d0 100755 --- a/examples/compareC60PDFs_objcryst.py +++ b/examples/compareC60PDFs_objcryst.py @@ -1,15 +1,17 @@ #!/usr/bin/env python """Plot C60 PDFs calculated with PDFCalculator and DebyePDFCalculator. + The C60 molecule are stored in a pyobjcryst object. """ -from matplotlib.pyplot import plot, show, clf -from diffpy.structure import Structure +from matplotlib.pyplot import clf, plot, show from pyobjcryst.crystal import Crystal from pyobjcryst.molecule import Molecule from pyobjcryst.scatteringpower import ScatteringPowerAtom -from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator + +from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator +from diffpy.structure import Structure # load C60 molecule as a diffpy.structure object bucky_diffpy = Structure(filename="datafiles/C60bucky.stru") diff --git a/examples/datafiles/menthol.cif b/examples/datafiles/menthol.cif index c8c7e6e2..1ff0ca8b 100644 --- a/examples/datafiles/menthol.cif +++ b/examples/datafiles/menthol.cif @@ -2,26 +2,26 @@ ########################################################################### # # Cambridge Crystallographic Data Centre -# CCDC -# +# CCDC +# ########################################################################### # # This CIF contains data generated directly from one or more entries in -# the Cambridge Structural Database and will include bibliographic, +# the Cambridge Structural Database and will include bibliographic, # chemical, crystal, experimental, refinement, and atomic coordinate data, # as available. -# +# # Copyright 2008 The Cambridge Crystallographic Data Centre -# -# This CIF is provided on the understanding that it is used for bona fide +# +# This CIF is provided on the understanding that it is used for bona fide # research purposes only. It may contain copyright material of the CCDC -# or of third parties, and may not be copied or further disseminated in -# any form, whether machine-readable or not, except for the purpose of +# or of third parties, and may not be copied or further disseminated in +# any form, whether machine-readable or not, except for the purpose of # generating routine backup copies on your local computer system. -# -# For further information about the CCDC, data deposition and data -# retrieval see . Bona fide researchers may freely -# download Mercury and enCIFer from this site to visualise CIF-encoded +# +# For further information about the CCDC, data deposition and data +# retrieval see . Bona fide researchers may freely +# download Mercury and enCIFer from this site to visualise CIF-encoded # structures and to carry out CIF format checking respectively. # ########################################################################### diff --git a/examples/distanceprinter.py b/examples/distanceprinter.py index c28409b0..a4b95984 100755 --- a/examples/distanceprinter.py +++ b/examples/distanceprinter.py @@ -1,17 +1,15 @@ #!/usr/bin/env python -"""Demonstration of using PairQuantity class for a printout -of pair distances in periodic and non-periodic structures. -""" +"""Demonstration of using PairQuantity class for a printout of pair distances +in periodic and non-periodic structures.""" from diffpy.srreal.pairquantity import PairQuantity from diffpy.structure import Structure class DistancePrinter(PairQuantity): - """This PairQuantity class simply prints the visited pair distances - and the indices of the contributing atoms. - """ + """This PairQuantity class simply prints the visited pair distances and the + indices of the contributing atoms.""" def _resetValue(self): self.count = 0 diff --git a/examples/lennardjones/ljcalculator.py b/examples/lennardjones/ljcalculator.py index e4a43f29..5dc5d852 100755 --- a/examples/lennardjones/ljcalculator.py +++ b/examples/lennardjones/ljcalculator.py @@ -1,12 +1,13 @@ #!/usr/bin/env python -"""Demonstration of using PairQuantity class for calculation -of Lennard Jones potential. +"""Demonstration of using PairQuantity class for calculation of Lennard Jones +potential. Vij = 4 * ( rij ** -12 - rij ** -6 ) """ import sys + from diffpy.srreal.pairquantity import PairQuantity from diffpy.structure import Structure @@ -20,7 +21,7 @@ def __init__(self): 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] diff --git a/examples/parallelPDF.py b/examples/parallelPDF.py index 89a62f37..30516398 100755 --- a/examples/parallelPDF.py +++ b/examples/parallelPDF.py @@ -1,19 +1,23 @@ #!/usr/bin/env python -"""Demonstration of parallel PDF calculation using the multiprocessing -package. A PDF of menthol structure is first calculated on a single core -and then on all computer CPUs. The script then compares both results -and prints elapsed time per each calculation. +"""Demonstration of parallel PDF calculation using the multiprocessing package. + +A PDF of menthol structure is first calculated on a single core and then +on all computer CPUs. The script then compares both results and prints +elapsed time per each calculation. """ +import multiprocessing +import optparse import os import sys -import optparse import time -import multiprocessing -from diffpy.structure import Structure -from diffpy.srreal.pdfcalculator import PDFCalculator + +from matplotlib.pyplot import clf, plot, show + from diffpy.srreal.parallel import createParallelCalculator +from diffpy.srreal.pdfcalculator import PDFCalculator +from diffpy.structure import Structure mydir = os.path.dirname(os.path.abspath(__file__)) mentholcif = os.path.join(mydir, "datafiles", "menthol.cif") @@ -28,8 +32,8 @@ # load menthol structure and make sure Uiso values are non-zero if opts.pyobjcryst: # use pyobjcryst if requested by the user - from pyobjcryst import loadCrystal from numpy import pi + from pyobjcryst import loadCrystal menthol = loadCrystal(mentholcif) for sc in menthol.GetScatteringComponentList(): @@ -62,7 +66,7 @@ pool = multiprocessing.Pool(processes=ncpu) t1 = time.time() -# create a proxy parrallel calculator to PDFCalculator pc0, +# create a proxy parallel calculator to PDFCalculator pc0, # that uses ncpu parallel jobs submitted via pool.imap_unordered pc1 = createParallelCalculator(pc0, ncpu, pool.imap_unordered) r1, g1 = pc1(menthol) @@ -71,7 +75,6 @@ print("Time ratio: %g" % (t0 / t1)) # plot both results and the difference curve -from matplotlib.pyplot import plot, show, clf clf() gd = g0 - g1 diff --git a/requirements/build.txt b/requirements/build.txt index f72d870d..b050e013 100644 --- a/requirements/build.txt +++ b/requirements/build.txt @@ -1,2 +1,3 @@ python -setuptools +boost +numpy diff --git a/requirements/conda.txt b/requirements/conda.txt index 5e7d3831..af3f87d8 100644 --- a/requirements/conda.txt +++ b/requirements/conda.txt @@ -1,3 +1,5 @@ -numpy boost +numpy +setuptools diffpy.structure +periodictable diff --git a/setup.py b/setup.py index 5611ed7f..ea931a64 100644 --- a/setup.py +++ b/setup.py @@ -6,12 +6,13 @@ Packages: diffpy.srreal """ -import numpy -import sys import glob -from setuptools import setup, Extension +import sys from ctypes.util import find_library +import numpy +from setuptools import Extension, setup + def get_boost_libraries(): base_lib = "boost_python" diff --git a/src/diffpy/__init__.py b/src/diffpy/__init__.py index bb399140..e8b7ec78 100644 --- a/src/diffpy/__init__.py +++ b/src/diffpy/__init__.py @@ -12,7 +12,6 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """diffpy - tools for structure analysis by diffraction. Blank namespace package. diff --git a/src/diffpy/srreal/__init__.py b/src/diffpy/srreal/__init__.py index 1d3d7206..7c62d5f3 100644 --- a/src/diffpy/srreal/__init__.py +++ b/src/diffpy/srreal/__init__.py @@ -12,9 +12,7 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""Tools for real space structure analysis. -""" +"""Tools for real space structure analysis.""" # package version from diffpy.srreal._version_data import __version__ diff --git a/src/diffpy/srreal/_cleanup.py b/src/diffpy/srreal/_cleanup.py index 1e7cc517..19fdffd2 100644 --- a/src/diffpy/srreal/_cleanup.py +++ b/src/diffpy/srreal/_cleanup.py @@ -12,9 +12,7 @@ # See LICENSE.txt for license information. # ############################################################################## - -""" -Cancel registration of Python-extended C++ classes when Python exits. +"""Cancel registration of Python-extended C++ classes when Python exits. Note ---- @@ -30,7 +28,6 @@ class prototypes is implemented in libdiffpy. Any Python-extended classes import atexit import weakref - # Routine to be used from srreal_ext module ---------------------------------- diff --git a/src/diffpy/srreal/_docstrings.py b/src/diffpy/srreal/_docstrings.py index fee8ab07..ab2cb889 100644 --- a/src/diffpy/srreal/_docstrings.py +++ b/src/diffpy/srreal/_docstrings.py @@ -12,10 +12,7 @@ # See LICENSE.txt for license information. # ############################################################################## - -""" -Docstrings for classes and functions in srreal_ext module. -""" +"""Docstrings for classes and functions in srreal_ext module.""" # Shared docstrings for classes derived from HasClassRegistry ---------------- diff --git a/src/diffpy/srreal/_final_imports.py b/src/diffpy/srreal/_final_imports.py index 236eaf57..273f106f 100644 --- a/src/diffpy/srreal/_final_imports.py +++ b/src/diffpy/srreal/_final_imports.py @@ -12,9 +12,7 @@ # See LICENSE.txt for license information. # ############################################################################## - -""" -Finalize tweak of classes from the extension module srreal_ext. +"""Finalize tweak of classes from the extension module srreal_ext. This private module handles loading of Python-level tweaks of the extension-defined classes. Any client that imports this module @@ -27,9 +25,7 @@ def import_now(): - """ - Import all Python modules that tweak extension-defined classes. - """ + """Import all Python modules that tweak extension-defined classes.""" global _import_now_called if _import_now_called: return diff --git a/src/diffpy/srreal/_version_data.py b/src/diffpy/srreal/_version_data.py index 8c1a4f46..b3828e8d 100644 --- a/src/diffpy/srreal/_version_data.py +++ b/src/diffpy/srreal/_version_data.py @@ -12,9 +12,7 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -""" -Extraction of version data for diffpy.srreal package +"""Extraction of version data for diffpy.srreal package. Does not import any extension module unlike the `version` module. """ @@ -25,7 +23,6 @@ from pkg_resources import resource_filename - # obtain version information from the version.cfg file cp = dict(version="", date="", commit="", timestamp="0") fcfg = resource_filename(__name__, "version.cfg") diff --git a/src/diffpy/srreal/atomradiitable.py b/src/diffpy/srreal/atomradiitable.py index fe5016aa..9d1f03fa 100644 --- a/src/diffpy/srreal/atomradiitable.py +++ b/src/diffpy/srreal/atomradiitable.py @@ -12,9 +12,7 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""class AtomRadiiTable -- storage of empirical atom radii. -""" +"""Class AtomRadiiTable -- storage of empirical atom radii.""" # exported items, these also makes them show in pydoc. @@ -27,6 +25,7 @@ class CovalentRadiiTable(AtomRadiiTable): """Covalent radii from Cordero et al., 2008, doi:10.1039/b801115j. + Instantiation of this class requires the periodictable module. """ @@ -64,9 +63,9 @@ def clone(self): return copy.copy(self) def type(self): - """Unique string identifier of the CovalentRadiiTable type. - This is used for class registration and as an argument for the - createByType function. + """Unique string identifier of the CovalentRadiiTable type. This is + used for class registration and as an argument for the createByType + function. Return string. """ diff --git a/src/diffpy/srreal/attributes.py b/src/diffpy/srreal/attributes.py index ad0452d6..e0326a92 100644 --- a/src/diffpy/srreal/attributes.py +++ b/src/diffpy/srreal/attributes.py @@ -12,7 +12,6 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """class Attributes -- wrapper to C++ class diffpy::Attributes A base to PairQuantity and quite a few other classes. """ @@ -54,12 +53,16 @@ def _setattr(self, name, value): def _pyattrgetter(name): - f = lambda obj: object.__getattribute__(obj, name) + def f(obj): + return object.__getattribute__(obj, name) + return f def _pyattrsetter(name): - f = lambda obj, value: object.__setattr__(obj, name, value) + def f(obj, value): + object.__setattr__(obj, name, value) + return f diff --git a/src/diffpy/srreal/bondcalculator.py b/src/diffpy/srreal/bondcalculator.py index d7f410cd..2d9a68de 100644 --- a/src/diffpy/srreal/bondcalculator.py +++ b/src/diffpy/srreal/bondcalculator.py @@ -12,17 +12,14 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""class BondCalculator -- distances between atoms in the structure. -""" +"""Class BondCalculator -- distances between atoms in the structure.""" # exported items, these also makes them show in pydoc. __all__ = ["BondCalculator"] -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr -from diffpy.srreal.wraputils import setattrFromKeywordArguments from diffpy.srreal.srreal_ext import BondCalculator +from diffpy.srreal.wraputils import propertyFromExtDoubleAttr, setattrFromKeywordArguments # property wrappers to C++ double attributes @@ -43,9 +40,8 @@ def _init_kwargs(self, **kwargs): - """Create a new instance of BondCalculator. - Keyword arguments can be used to configure - calculator properties, for example: + """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) diff --git a/src/diffpy/srreal/bvparameterstable.py b/src/diffpy/srreal/bvparameterstable.py index 9d963fca..6d6d9242 100644 --- a/src/diffpy/srreal/bvparameterstable.py +++ b/src/diffpy/srreal/bvparameterstable.py @@ -12,10 +12,8 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""class BVParametersTable -- storage of bond valence parameters -class BVParam -- bond valence data associated with specific cation-anion pair -""" +"""Class BVParametersTable -- storage of bond valence parameters class BVParam +-- bond valence data associated with specific cation-anion pair.""" # exported items, these also makes them show in pydoc. diff --git a/src/diffpy/srreal/bvscalculator.py b/src/diffpy/srreal/bvscalculator.py index 2e1cb1c1..7cc1bced 100644 --- a/src/diffpy/srreal/bvscalculator.py +++ b/src/diffpy/srreal/bvscalculator.py @@ -12,17 +12,14 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""class BVSCalculator -- bond valence sums calculator -""" +"""Class BVSCalculator -- bond valence sums calculator.""" # exported items __all__ = ["BVSCalculator"] from diffpy.srreal.srreal_ext import BVSCalculator -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr -from diffpy.srreal.wraputils import setattrFromKeywordArguments +from diffpy.srreal.wraputils import propertyFromExtDoubleAttr, setattrFromKeywordArguments # Property wrappers to C++ double attributes diff --git a/src/diffpy/srreal/eventticker.py b/src/diffpy/srreal/eventticker.py index ecec69ac..35b74877 100644 --- a/src/diffpy/srreal/eventticker.py +++ b/src/diffpy/srreal/eventticker.py @@ -12,10 +12,7 @@ # See LICENSE.txt for license information. # ############################################################################## - -""" -class EventTicker -- storage of modification times of dependent objects -""" +"""Class EventTicker -- storage of modification times of dependent objects.""" # exported items diff --git a/src/diffpy/srreal/overlapcalculator.py b/src/diffpy/srreal/overlapcalculator.py index c99aed61..9747a221 100644 --- a/src/diffpy/srreal/overlapcalculator.py +++ b/src/diffpy/srreal/overlapcalculator.py @@ -12,17 +12,14 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""class OverlapCalculator -- calculator of atom overlaps in a structure. -""" +"""Class OverlapCalculator -- calculator of atom overlaps in a structure.""" # exported items, these also makes them show in pydoc. __all__ = ["OverlapCalculator"] -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr -from diffpy.srreal.wraputils import setattrFromKeywordArguments from diffpy.srreal.srreal_ext import OverlapCalculator +from diffpy.srreal.wraputils import propertyFromExtDoubleAttr, setattrFromKeywordArguments # property wrappers to C++ double attributes @@ -50,9 +47,8 @@ def _init_kwargs(self, **kwargs): - """Create a new instance of OverlapCalculator. - Keyword arguments can be used to configure - calculator properties, for example: + """Create a new instance of OverlapCalculator. Keyword arguments can be + used to configure calculator properties, for example: olc = OverlapCalculator(rmax=2.5) diff --git a/src/diffpy/srreal/pairquantity.py b/src/diffpy/srreal/pairquantity.py index bba56c6b..a8eaa058 100644 --- a/src/diffpy/srreal/pairquantity.py +++ b/src/diffpy/srreal/pairquantity.py @@ -12,10 +12,7 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -""" -class PairQuantity -- base class for Python defined calculators. -""" +"""Class PairQuantity -- base class for Python defined calculators.""" # exported items diff --git a/src/diffpy/srreal/parallel.py b/src/diffpy/srreal/parallel.py index 413836a0..5ab113ee 100644 --- a/src/diffpy/srreal/parallel.py +++ b/src/diffpy/srreal/parallel.py @@ -12,7 +12,6 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """ParallelPairQuantity -- proxy class for converting PairQuantity types into parallel calculators. """ @@ -23,6 +22,7 @@ import copy import inspect + from diffpy.srreal.attributes import Attributes # ---------------------------------------------------------------------------- @@ -43,8 +43,8 @@ def createParallelCalculator(pqobj, ncpu, pmap): """ class ParallelPairQuantity(Attributes): - """Class for running parallel calculations. This is a proxy class - to the wrapper PairQuantity type with the same interface. + """Class for running parallel calculations. This is a proxy class to + the wrapper PairQuantity type with the same interface. Instance data: @@ -100,8 +100,8 @@ def eval(self, stru=None): def __call__(self, *args, **kwargs): """Call the wrapped calculator using parallel evaluation. - The arguments and return value are the same as for the wrapped - PairQuantity calculator. + The arguments and return value are the same as for the + wrapped PairQuantity calculator. """ savedeval = self.pqobj.__dict__.get("eval") @@ -175,19 +175,25 @@ def _make_proxyproperty(prop): fget = fset = fdel = None if prop.fget: - def fget(self): + def _fget(self): return prop.fget(self.pqobj) + fget = _fget + if prop.fset: - def fset(self, value): + def _fset(self, value): return prop.fset(self.pqobj, value) + fset = _fset + if prop.fdel: - def fdel(self): + def _fdel(self): return prop.fdel(self.pqobj) + fdel = _fdel + return property(fget, fset, fdel, prop.__doc__) for n, p in inspect.getmembers(pqtype, lambda x: type(x) is property): diff --git a/src/diffpy/srreal/pdfbaseline.py b/src/diffpy/srreal/pdfbaseline.py index dc8581cc..22ced38b 100644 --- a/src/diffpy/srreal/pdfbaseline.py +++ b/src/diffpy/srreal/pdfbaseline.py @@ -12,7 +12,6 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """ Classes for configuring PDF baseline: PDFBaseline, ZeroBaseline, LinearBaseline @@ -27,8 +26,7 @@ """.split() from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import PDFBaseline -from diffpy.srreal.srreal_ext import ZeroBaseline, LinearBaseline +from diffpy.srreal.srreal_ext import LinearBaseline, PDFBaseline, ZeroBaseline from diffpy.srreal.wraputils import propertyFromExtDoubleAttr # class PDFBaseline ---------------------------------------------------------- @@ -50,8 +48,8 @@ def makePDFBaseline(name, fnc, replace=False, **dbattrs): - """Helper function for registering Python function as a PDFBaseline. - This is required for using Python function as PDFCalculator.baseline. + """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 global registry of PDFBaseline types. This will be the diff --git a/src/diffpy/srreal/pdfcalculator.py b/src/diffpy/srreal/pdfcalculator.py index 5c30cf16..b1c9d125 100644 --- a/src/diffpy/srreal/pdfcalculator.py +++ b/src/diffpy/srreal/pdfcalculator.py @@ -12,13 +12,14 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """ Top-level classes for PDF calculation: DebyePDFCalculator -- simulate PDF by evaluating Debye sum in Q-space PDFCalculator -- calculate PDF by peak summation in real space """ +from diffpy.srreal.srreal_ext import DebyePDFCalculator, PDFCalculator, fftftog, fftgtof +from diffpy.srreal.wraputils import propertyFromExtDoubleAttr, setattrFromKeywordArguments # exported items __all__ = """ @@ -26,27 +27,21 @@ fftftog fftgtof """.split() -from diffpy.srreal.srreal_ext import DebyePDFCalculator -from diffpy.srreal.srreal_ext import PDFCalculator -from diffpy.srreal.srreal_ext import fftftog, fftgtof -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr -from diffpy.srreal.wraputils import setattrFromKeywordArguments - -# silence the pyflakes syntax checker -assert all((fftftog, fftgtof)) - # imports for backward compatibility -from diffpy.srreal.pdfbaseline import PDFBaseline, makePDFBaseline, ZeroBaseline, LinearBaseline +from diffpy.srreal.pdfbaseline import LinearBaseline, PDFBaseline, ZeroBaseline, makePDFBaseline from diffpy.srreal.pdfenvelope import ( PDFEnvelope, - makePDFEnvelope, QResolutionEnvelope, ScaleEnvelope, SphericalShapeEnvelope, StepCutEnvelope, + makePDFEnvelope, ) from diffpy.srreal.peakprofile import PeakProfile -from diffpy.srreal.peakwidthmodel import PeakWidthModel, ConstantPeakWidth, DebyeWallerPeakWidth, JeongPeakWidth +from diffpy.srreal.peakwidthmodel import ConstantPeakWidth, DebyeWallerPeakWidth, JeongPeakWidth, PeakWidthModel + +# silence the pyflakes syntax checker +assert all((fftftog, fftgtof)) # silence the pyflakes syntax checker assert all( @@ -148,10 +143,10 @@ def _defineCommonInterface(cls): ) def _call_kwargs(self, structure=None, **kwargs): - """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. + """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. structure -- a structure object to be evaluated. Reuse the last structure when None. diff --git a/src/diffpy/srreal/pdfenvelope.py b/src/diffpy/srreal/pdfenvelope.py index e43a345a..594e80d9 100644 --- a/src/diffpy/srreal/pdfenvelope.py +++ b/src/diffpy/srreal/pdfenvelope.py @@ -12,7 +12,6 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """ Classes for configuring PDF scaling envelope: PDFEnvelope, ScaleEnvelope, QResolutionEnvelope, @@ -30,9 +29,13 @@ """.split() from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import PDFEnvelope -from diffpy.srreal.srreal_ext import ScaleEnvelope, QResolutionEnvelope -from diffpy.srreal.srreal_ext import SphericalShapeEnvelope, StepCutEnvelope +from diffpy.srreal.srreal_ext import ( + PDFEnvelope, + QResolutionEnvelope, + ScaleEnvelope, + SphericalShapeEnvelope, + StepCutEnvelope, +) from diffpy.srreal.wraputils import propertyFromExtDoubleAttr # class PDFEnvelope ---------------------------------------------------------- @@ -74,8 +77,8 @@ def makePDFEnvelope(name, fnc, replace=False, **dbattrs): - """Helper function for registering Python function as a PDFEnvelope. - This is required for using Python function as PDFCalculator envelope. + """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 global registry of PDFEnvelope types. This will be the diff --git a/src/diffpy/srreal/peakprofile.py b/src/diffpy/srreal/peakprofile.py index d082ac89..ff1044f7 100644 --- a/src/diffpy/srreal/peakprofile.py +++ b/src/diffpy/srreal/peakprofile.py @@ -12,7 +12,6 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """ Class for configuring PDF profile function: PeakProfile @@ -24,8 +23,7 @@ __all__ = ["PeakProfile", "GaussianProfile", "CroppedGaussianProfile"] from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import PeakProfile -from diffpy.srreal.srreal_ext import GaussianProfile, CroppedGaussianProfile +from diffpy.srreal.srreal_ext import CroppedGaussianProfile, GaussianProfile, PeakProfile from diffpy.srreal.wraputils import propertyFromExtDoubleAttr # class PeakProfile ---------------------------------------------------------- diff --git a/src/diffpy/srreal/peakwidthmodel.py b/src/diffpy/srreal/peakwidthmodel.py index 75610987..cb0acb9b 100644 --- a/src/diffpy/srreal/peakwidthmodel.py +++ b/src/diffpy/srreal/peakwidthmodel.py @@ -12,7 +12,6 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - """ Classes for configuring peak width evaluation in PDF calculations: PeakWidthModel, @@ -24,8 +23,7 @@ __all__ = ["PeakWidthModel", "ConstantPeakWidth", "DebyeWallerPeakWidth", "JeongPeakWidth"] from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import PeakWidthModel, ConstantPeakWidth -from diffpy.srreal.srreal_ext import DebyeWallerPeakWidth, JeongPeakWidth +from diffpy.srreal.srreal_ext import ConstantPeakWidth, DebyeWallerPeakWidth, JeongPeakWidth, PeakWidthModel from diffpy.srreal.wraputils import propertyFromExtDoubleAttr # class PeakWidthModel ------------------------------------------------------- diff --git a/src/diffpy/srreal/scatteringfactortable.py b/src/diffpy/srreal/scatteringfactortable.py index 26f2ed3e..a53ce546 100644 --- a/src/diffpy/srreal/scatteringfactortable.py +++ b/src/diffpy/srreal/scatteringfactortable.py @@ -12,21 +12,15 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -""" -class ScatteringFactorTable -- scattering factors for atoms, ions and isotopes. -""" +"""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"] -from diffpy.srreal.srreal_ext import ScatteringFactorTable -from diffpy.srreal.srreal_ext import SFTXray -from diffpy.srreal.srreal_ext import SFTElectron -from diffpy.srreal.srreal_ext import SFTNeutron -from diffpy.srreal.srreal_ext import SFTElectronNumber from diffpy.srreal.sfaverage import SFAverage +from diffpy.srreal.srreal_ext import ScatteringFactorTable, SFTElectron, SFTElectronNumber, SFTNeutron, SFTXray # Pickling Support ----------------------------------------------------------- diff --git a/src/diffpy/srreal/sfaverage.py b/src/diffpy/srreal/sfaverage.py index 46c61b12..5a1dde4d 100644 --- a/src/diffpy/srreal/sfaverage.py +++ b/src/diffpy/srreal/sfaverage.py @@ -12,10 +12,7 @@ # See LICENSE.txt for license information. # ############################################################################## - -""" -Compositional averaging of atom scattering factors. - +"""Compositional averaging of atom scattering factors. Examples -------- @@ -41,8 +38,7 @@ class SFAverage(object): - """\ - Calculate compositional statistics of atom scattering factors. + """Calculate compositional statistics of atom scattering factors. Compositional averages can be calculated for an array of Q-values. Results are stored in the class attributes. @@ -65,7 +61,7 @@ class SFAverage(object): Compositional average of squared scattering factors. Float or NumPy array. composition : - Dictionary of atom symbols and their total abundancies. + Dictionary of atom symbols and their total abundance. """ f1sum = 0 @@ -77,8 +73,7 @@ class SFAverage(object): @classmethod def fromStructure(cls, stru, sftb, q=0): - """\ - Calculate average scattering factors from a structure object. + """Calculate average scattering factors from a structure object. Parameters ---------- @@ -121,8 +116,7 @@ def fromStructure(cls, stru, sftb, q=0): @classmethod def fromComposition(cls, composition, sftb, q=0): - """\ - Calculate average scattering factors from atom concentrations. + """Calculate average scattering factors from atom concentrations. Parameters ---------- @@ -150,7 +144,7 @@ def fromComposition(cls, composition, sftb, q=0): sfa.composition.update(composition) else: for smbl, cnt in composition: - if not smbl in sfa.composition: + if smbl not in sfa.composition: sfa.composition[smbl] = 0 sfa.composition[smbl] += cnt sfa.f1sum = 0.0 * q diff --git a/src/diffpy/srreal/structureadapter.py b/src/diffpy/srreal/structureadapter.py index dc9fdc30..3abd19a0 100644 --- a/src/diffpy/srreal/structureadapter.py +++ b/src/diffpy/srreal/structureadapter.py @@ -12,9 +12,8 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""class StructureAdapter -- adapter of any structure object to the interface - expected by srreal PairQuantity calculators +"""Class StructureAdapter -- adapter of any structure object to the interface +expected by srreal PairQuantity calculators. Routines: @@ -29,10 +28,25 @@ EMPTY -- singleton instance of an empty structure. """ +# import of srreal_ext calls RegisterStructureAdapter, therefore it has +# to be at the end of this module. + +from diffpy.srreal.srreal_ext import ( + Atom, + AtomicStructureAdapter, + BaseBondGenerator, + CrystalStructureAdapter, + PeriodicStructureAdapter, + StructureAdapter, + StructureDifference, + _emptyStructureAdapter, + nometa, + nosymmetry, +) + def createStructureAdapter(stru): - """ - Create StructureAdapter from a Python object. + """Create StructureAdapter from a Python object. stru -- an object that is convertible to StructureAdapter, i.e., it has a registered factory that converts Python structure object to @@ -49,7 +63,7 @@ def createStructureAdapter(stru): 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: + if fqn not in _adapter_converters_registry: continue factory = _adapter_converters_registry[fqn] return factory(stru) @@ -59,10 +73,10 @@ def createStructureAdapter(stru): def RegisterStructureAdapter(fqname, fnc=None): - """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 + """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 diffpy.srreal structure type. fqname -- fully qualified class name for the convertible objects. @@ -92,18 +106,6 @@ def __wrapper(fnc): _adapter_converters_registry = {} -# import of srreal_ext calls RegisterStructureAdapter, therefore it has -# to be at the end of this module. - -from diffpy.srreal.srreal_ext import StructureAdapter -from diffpy.srreal.srreal_ext import Atom, AtomicStructureAdapter -from diffpy.srreal.srreal_ext import PeriodicStructureAdapter -from diffpy.srreal.srreal_ext import CrystalStructureAdapter -from diffpy.srreal.srreal_ext import StructureDifference -from diffpy.srreal.srreal_ext import nometa, nosymmetry -from diffpy.srreal.srreal_ext import _emptyStructureAdapter -from diffpy.srreal.srreal_ext import BaseBondGenerator - EMPTY = _emptyStructureAdapter() del _emptyStructureAdapter diff --git a/src/diffpy/srreal/structureconverters.py b/src/diffpy/srreal/structureconverters.py index 210a2bbb..c9b844d8 100644 --- a/src/diffpy/srreal/structureconverters.py +++ b/src/diffpy/srreal/structureconverters.py @@ -12,15 +12,22 @@ # See LICENSE.txt for license information. # ############################################################################## +"""Converters from other structure representations in Python to diffpy.srreal +StructureAdapter classes.""" + +from diffpy.srreal.srreal_ext import ( + AtomicStructureAdapter, + PeriodicStructureAdapter, + convertObjCrystCrystal, + convertObjCrystMolecule, +) +from diffpy.srreal.structureadapter import RegisterStructureAdapter + +# Converters for Molecule and Crystal from pyobjcryst ------------------------ -""" -Converters from other structure representations in Python to diffpy.srreal -StructureAdapter classes. -""" -from diffpy.srreal.structureadapter import RegisterStructureAdapter -from diffpy.srreal.srreal_ext import AtomicStructureAdapter -from diffpy.srreal.srreal_ext import PeriodicStructureAdapter +RegisterStructureAdapter("pyobjcryst._pyobjcryst.Molecule", convertObjCrystMolecule) +RegisterStructureAdapter("pyobjcryst._pyobjcryst.Crystal", convertObjCrystCrystal) # Converter for Structure class from diffpy.structure ------------------------ @@ -48,21 +55,10 @@ def convertDiffPyStructure(stru): return adpt -# Converters for Molecule and Crystal from pyobjcryst ------------------------ - -from diffpy.srreal.srreal_ext import convertObjCrystMolecule - -RegisterStructureAdapter("pyobjcryst._pyobjcryst.Molecule", convertObjCrystMolecule) - -from diffpy.srreal.srreal_ext import 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." pdffit = None @@ -76,7 +72,7 @@ def hasMetadata(stru): def _customPQConfig(self, pqobj): """Apply PDF-related metadata if defined in PDFFit structure format.""" pqname = type(pqobj).__name__ - if not pqname in ("PDFCalculator", "DebyePDFCalculator"): + if pqname not in ("PDFCalculator", "DebyePDFCalculator"): return if not self.pdffit: return @@ -87,12 +83,12 @@ def _customPQConfig(self, pqobj): pqobj.scale = self.pdffit["scale"] # spdiameter if "spdiameter" in self.pdffit: - if not "sphericalshape" in envtps: + if "sphericalshape" not in envtps: pqobj.addEnvelope("sphericalshape") pqobj.spdiameter = self.pdffit["spdiameter"] # stepcut if "stepcut" in self.pdffit: - if not "stepcut" in envtps: + if "stepcut" not in envtps: pqobj.addEnvelope("stepcut") pqobj.stepcut = self.pdffit["stepcut"] # delta1, delta2 - set these only when using JeongPeakWidth model @@ -102,7 +98,7 @@ def _customPQConfig(self, pqobj): return def _fetchMetadata(self, stru): - """Copy data from the pdffit attribute of diffpy Structure object + """Copy data from the pdffit attribute of diffpy Structure object. stru -- instance of Structure class from diffpy.structure diff --git a/src/diffpy/srreal/tests/__init__.py b/src/diffpy/srreal/tests/__init__.py index 8f9447cf..c4e942b5 100644 --- a/src/diffpy/srreal/tests/__init__.py +++ b/src/diffpy/srreal/tests/__init__.py @@ -12,12 +12,10 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## +"""Unit tests for diffpy.srreal.""" -"""Unit tests for diffpy.srreal. -""" - -import unittest import logging +import unittest # create logger instance for the tests subpackage logging.basicConfig() @@ -41,8 +39,9 @@ def testsuite(pattern=""): The TestSuite object containing the matching tests. """ import re - from os.path import dirname from itertools import chain + from os.path import dirname + from pkg_resources import resource_filename loader = unittest.defaultTestLoader diff --git a/src/diffpy/srreal/tests/debug.py b/src/diffpy/srreal/tests/debug.py index eb48ae31..47197f9c 100644 --- a/src/diffpy/srreal/tests/debug.py +++ b/src/diffpy/srreal/tests/debug.py @@ -12,9 +12,7 @@ # See LICENSE.txt for license information. # ############################################################################## - -""" -Convenience module for debugging the unit tests using +"""Convenience module for debugging the unit tests using. python -m diffpy.srreal.tests.debug @@ -24,6 +22,7 @@ if __name__ == "__main__": import sys + from diffpy.srreal.tests import testsuite pattern = sys.argv[1] if len(sys.argv) > 1 else "" diff --git a/src/diffpy/srreal/tests/run.py b/src/diffpy/srreal/tests/run.py index efbe2456..9d107059 100644 --- a/src/diffpy/srreal/tests/run.py +++ b/src/diffpy/srreal/tests/run.py @@ -12,8 +12,7 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""Convenience module for executing all unit tests with +"""Convenience module for executing all unit tests with. python -m diffpy.srreal.tests.run """ @@ -24,7 +23,8 @@ # show warnings by default if not sys.warnoptions: - import os, warnings + import os + import warnings warnings.simplefilter("default") # also affect subprocesses diff --git a/src/diffpy/srreal/tests/testatomradiitable.py b/src/diffpy/srreal/tests/testatomradiitable.py index d9e7ee98..f5c2265e 100644 --- a/src/diffpy/srreal/tests/testatomradiitable.py +++ b/src/diffpy/srreal/tests/testatomradiitable.py @@ -1,14 +1,13 @@ #!/usr/bin/env python -"""Unit tests for the AtomRadiiTable class. -""" +"""Unit tests for the AtomRadiiTable class.""" -import unittest import pickle -from diffpy.srreal.tests.testutils import has_periodictable, _msg_noperiodictable -from diffpy.srreal.atomradiitable import AtomRadiiTable, CovalentRadiiTable -from diffpy.srreal.atomradiitable import ConstantRadiiTable +import unittest + +from diffpy.srreal.atomradiitable import AtomRadiiTable, ConstantRadiiTable, CovalentRadiiTable +from diffpy.srreal.tests.testutils import _msg_noperiodictable, has_periodictable # ---------------------------------------------------------------------------- @@ -24,7 +23,7 @@ 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()) @@ -38,7 +37,7 @@ def test_pickling(self): return def test__standardLookup(self): - """check AtomRadiiTable._standardLookup()""" + """Check AtomRadiiTable._standardLookup()""" self.assertRaises(RuntimeError, self.rtb._standardLookup, "anything") self.assertEqual(0.0, self.ctb._standardLookup("anything")) self.ctb.setDefault(7.3) @@ -46,7 +45,7 @@ def test__standardLookup(self): return def test_fromString(self): - """check AtomRadiiTable.fromString()""" + """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") @@ -60,12 +59,12 @@ def test_fromString(self): return def test_getAllCustom(self): - """check AtomRadiiTable.getAllCustom()""" + """Check AtomRadiiTable.getAllCustom()""" self.assertEqual({}, self.rtb.getAllCustom()) return def test_lookup(self): - """check AtomRadiiTable.lookup()""" + """Check AtomRadiiTable.lookup()""" self.assertRaises(RuntimeError, self.rtb.lookup, "C") self.assertEqual(0.0, self.ctb.lookup("C")) self.rtb.setCustom("C", 1.23) @@ -73,7 +72,7 @@ def test_lookup(self): return def test_resetCustom(self): - """check AtomRadiiTable.resetCustom()""" + """Check AtomRadiiTable.resetCustom()""" self.rtb.setCustom("C", 1.23) self.assertTrue(self.rtb.getAllCustom()) self.rtb.resetAll() @@ -81,7 +80,7 @@ def test_resetCustom(self): return def test_setCustom(self): - """check AtomRadiiTable.setCustom()""" + """Check AtomRadiiTable.setCustom()""" self.rtb.setCustom("C", 1.23) self.assertEqual(1.23, self.rtb.lookup("C")) self.rtb.setCustom("C", 3.3) @@ -89,7 +88,7 @@ def test_setCustom(self): return def test_toString(self): - """check AtomRadiiTable.toString()""" + """Check AtomRadiiTable.toString()""" rtb = self.rtb self.assertEqual("", rtb.toString()) self.assertEqual("", rtb.toString("; ")) @@ -115,7 +114,7 @@ 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()) @@ -127,12 +126,12 @@ def test_pickling(self): return def test__standardLookup(self): - """check CovalentRadiiTable._standardLookup()""" + """Check CovalentRadiiTable._standardLookup()""" self.assertEqual(1.22, self.rtb._standardLookup("Ga")) return def test_create(self): - """check CovalentRadiiTable.create()""" + """Check CovalentRadiiTable.create()""" self.rtb.setCustom("Na", 1.3) rtb2 = self.rtb.create() self.assertTrue(isinstance(rtb2, CovalentRadiiTable)) @@ -141,7 +140,7 @@ def test_create(self): return def test_clone(self): - """check CovalentRadiiTable.clone()""" + """Check CovalentRadiiTable.clone()""" self.rtb.setCustom("Na", 1.3) rtb2 = self.rtb.clone() self.assertTrue(isinstance(rtb2, CovalentRadiiTable)) @@ -150,25 +149,25 @@ def test_clone(self): return def test_fromString(self): - """check CovalentRadiiTable.fromString()""" + """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()""" + """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()""" + """Check CovalentRadiiTable.resetCustom()""" self.rtb.fromString("B:2.33, Ga:2.22") self.rtb.resetCustom("B") self.rtb.resetCustom("nada") @@ -178,14 +177,14 @@ def test_resetCustom(self): return def test_setCustom(self): - """check CovalentRadiiTable.setCustom()""" + """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()""" + """Check CovalentRadiiTable.toString()""" self.assertEqual("", self.rtb.toString(";---")) return diff --git a/src/diffpy/srreal/tests/testattributes.py b/src/diffpy/srreal/tests/testattributes.py index cb4f2243..573ccf8d 100644 --- a/src/diffpy/srreal/tests/testattributes.py +++ b/src/diffpy/srreal/tests/testattributes.py @@ -4,9 +4,9 @@ """ +import gc import unittest import weakref -import gc from diffpy.srreal.attributes import Attributes from diffpy.srreal.pairquantity import PairQuantity @@ -23,7 +23,7 @@ def tearDown(self): return def test___setattr__(self): - """check Attributes.__setattr__()""" + """Check Attributes.__setattr__()""" # normal attribute a = Attributes() a.x = 45 @@ -39,7 +39,7 @@ def test___setattr__(self): return def test___getattr__(self): - """check Attributes.__getattr__()""" + """Check Attributes.__getattr__()""" a = Attributes() self.assertRaises(AttributeError, getattr, a, "invalid") a.x = 11 @@ -50,7 +50,7 @@ def test___getattr__(self): 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) @@ -63,7 +63,7 @@ def test_garbage_collection(self): return def test__getDoubleAttr(self): - """check Attributes._getDoubleAttr()""" + """Check Attributes._getDoubleAttr()""" pdfc = PDFCalculator() pdfc.foo = 11 self.assertRaises(AttributeError, pdfc._getDoubleAttr, "foo") @@ -77,7 +77,7 @@ def test__getDoubleAttr(self): return def test__hasDoubleAttr(self): - """check Attributes._hasDoubleAttr()""" + """Check Attributes._hasDoubleAttr()""" a = Attributes() a.foo = 45 self.assertFalse(a._hasDoubleAttr("foo")) @@ -86,7 +86,7 @@ def test__hasDoubleAttr(self): return def test__namesOfDoubleAttributes(self): - """check Attributes._namesOfDoubleAttributes()""" + """Check Attributes._namesOfDoubleAttributes()""" a = Attributes() self.assertEqual(0, len(a._namesOfDoubleAttributes())) pq = PairQuantity() @@ -97,7 +97,7 @@ def test__namesOfDoubleAttributes(self): 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) @@ -114,7 +114,7 @@ def test__namesOfWritableDoubleAttributes(self): return def test__registerDoubleAttribute(self): - """check Attributes._registerDoubleAttribute()""" + """Check Attributes._registerDoubleAttribute()""" d = {"g_called": False, "s_called": False, "value": 0} def g(obj): @@ -154,7 +154,7 @@ def s(obj, value): return def test__setDoubleAttr(self): - """check Attributes._setDoubleAttr()""" + """Check Attributes._setDoubleAttr()""" pdfc = PDFCalculator() pdfc._setDoubleAttr("scale", 1.23) self.assertFalse("scale" in pdfc.__dict__) diff --git a/src/diffpy/srreal/tests/testbondcalculator.py b/src/diffpy/srreal/tests/testbondcalculator.py index 76164a2a..cbbe6090 100644 --- a/src/diffpy/srreal/tests/testbondcalculator.py +++ b/src/diffpy/srreal/tests/testbondcalculator.py @@ -1,18 +1,21 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.bondcalculator -""" +"""Unit tests for diffpy.srreal.bondcalculator.""" -import unittest import pickle +import unittest + import numpy -from diffpy.srreal.tests.testutils import has_pyobjcryst, _msg_nopyobjcryst -from diffpy.srreal.tests.testutils import loadDiffPyStructure -from diffpy.srreal.tests.testutils import loadObjCrystCrystal -from diffpy.srreal.tests.testutils import pickle_with_attr from diffpy.srreal.bondcalculator import BondCalculator +from diffpy.srreal.tests.testutils import ( + _msg_nopyobjcryst, + has_pyobjcryst, + loadDiffPyStructure, + loadObjCrystCrystal, + pickle_with_attr, +) # ---------------------------------------------------------------------------- @@ -33,7 +36,7 @@ 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)) @@ -44,7 +47,7 @@ def test___init__(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))) @@ -59,7 +62,7 @@ def test___call__(self): 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 @@ -77,7 +80,7 @@ def test_pickling(self): 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 @@ -94,7 +97,7 @@ def test_pickling_derived_structure(self): 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))) @@ -115,7 +118,7 @@ def test_distances(self): 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)) @@ -123,7 +126,7 @@ def test_directions(self): 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)) @@ -144,7 +147,7 @@ def test_sites(self): 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)) @@ -163,7 +166,7 @@ def test_types(self): 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))) @@ -181,7 +184,7 @@ def test_filterCone(self): return def test_filterOff(self): - """check BondCalculator.filterOff()""" + """Check BondCalculator.filterOff()""" bdc = self.bdc bdc.rmax = 2.5 bdc.filterCone([1, 2, 3], -1) @@ -191,7 +194,7 @@ def test_filterOff(self): return def test_setPairMask(self): - """check different setPairMask arguments.""" + """Check different setPairMask arguments.""" bdc = self.bdc dall = bdc(self.nickel) bdc.maskAllPairs(False) @@ -220,7 +223,7 @@ def test_setPairMask(self): 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) @@ -261,7 +264,7 @@ 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())) @@ -272,7 +275,7 @@ def test___call__(self): 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)) @@ -293,7 +296,7 @@ def test_sites(self): 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)) @@ -312,7 +315,7 @@ def test_types(self): 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) @@ -329,7 +332,7 @@ def test_filterCone(self): return def test_filterOff(self): - """check BondCalculator.filterOff()""" + """Check BondCalculator.filterOff()""" bdc = self.bdc bdc.rmax = 2.5 bdc.filterCone([1, 2, 3], -1) diff --git a/src/diffpy/srreal/tests/testbvscalculator.py b/src/diffpy/srreal/tests/testbvscalculator.py index 62efd7dd..aceac210 100644 --- a/src/diffpy/srreal/tests/testbvscalculator.py +++ b/src/diffpy/srreal/tests/testbvscalculator.py @@ -1,15 +1,13 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.bvscalculator -""" +"""Unit tests for diffpy.srreal.bvscalculator.""" -import unittest import pickle +import unittest from diffpy.srreal.bvscalculator import BVSCalculator -from diffpy.srreal.tests.testutils import loadDiffPyStructure -from diffpy.srreal.tests.testutils import pickle_with_attr +from diffpy.srreal.tests.testutils import loadDiffPyStructure, pickle_with_attr ############################################################################## @@ -29,14 +27,14 @@ 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)) @@ -49,7 +47,7 @@ def test___call__(self): 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 @@ -58,14 +56,14 @@ def test_bvdiff(self): 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) @@ -85,24 +83,24 @@ def test_bvrmsdiff(self): 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)) 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 @@ -140,7 +138,7 @@ def test_table_pickling(self): 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 @@ -157,7 +155,7 @@ def test_pickling_derived_structure(self): 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: diff --git a/src/diffpy/srreal/tests/testdata/Ni.stru b/src/diffpy/srreal/tests/testdata/Ni.stru index 5d39b959..e13f2693 100644 --- a/src/diffpy/srreal/tests/testdata/Ni.stru +++ b/src/diffpy/srreal/tests/testdata/Ni.stru @@ -2,11 +2,11 @@ title structure Ni FCC format pdffit scale 1.000000 sharp 0.000000, 0.000000, 1.000000, 0.000000 -spcgr Fm-3m +spcgr Fm-3m cell 3.520000, 3.520000, 3.520000, 90.000000, 90.000000, 90.000000 dcell 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000 ncell 1, 1, 1, 4 -atoms +atoms NI 0.00000000 0.00000000 0.00000000 1.0000 0.00000000 0.00000000 0.00000000 0.0000 0.00126651 0.00126651 0.00126651 diff --git a/src/diffpy/srreal/tests/testdebyepdfcalculator.py b/src/diffpy/srreal/tests/testdebyepdfcalculator.py index 9268613f..fd8c07d4 100644 --- a/src/diffpy/srreal/tests/testdebyepdfcalculator.py +++ b/src/diffpy/srreal/tests/testdebyepdfcalculator.py @@ -1,17 +1,16 @@ #!/usr/bin/env python -"""Unit tests for pdfcalculator.py -""" +"""Unit tests for pdfcalculator.py.""" -import unittest import pickle +import unittest + import numpy from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator -from diffpy.srreal.tests.testutils import loadDiffPyStructure -from diffpy.srreal.tests.testutils import pickle_with_attr from diffpy.srreal.tests.testpdfcalculator import _maxNormDiff +from diffpy.srreal.tests.testutils import loadDiffPyStructure, pickle_with_attr ############################################################################## @@ -42,21 +41,21 @@ def setUp(self): # 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.assertEqual(1.23, self.dpdfc.qmin) return def test___setattr__(self): - """check DebyePDFCalculator.__setattr__()""" + """Check DebyePDFCalculator.__setattr__()""" self.assertNotEqual(1.23, self.dpdfc._getDoubleAttr("rmin")) self.dpdfc.rmin = 1.23 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")) @@ -64,19 +63,19 @@ def test__getDoubleAttr(self): return def test__hasDoubleAttr(self): - """check DebyePDFCalculator._hasDoubleAttr()""" + """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()) 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")) @@ -85,7 +84,7 @@ def test__setDoubleAttr(self): 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) @@ -140,7 +139,7 @@ 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) @@ -188,7 +187,8 @@ def test_mask_pickling(self): 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 diff --git a/src/diffpy/srreal/tests/testoverlapcalculator.py b/src/diffpy/srreal/tests/testoverlapcalculator.py index 09881233..aabda0e6 100644 --- a/src/diffpy/srreal/tests/testoverlapcalculator.py +++ b/src/diffpy/srreal/tests/testoverlapcalculator.py @@ -1,20 +1,23 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.overlapcalculator -""" +"""Unit tests for diffpy.srreal.overlapcalculator.""" -import unittest -import pickle import copy +import pickle +import unittest + import numpy -from diffpy.srreal.tests.testutils import has_pyobjcryst, _msg_nopyobjcryst -from diffpy.srreal.tests.testutils import loadDiffPyStructure -from diffpy.srreal.tests.testutils import loadObjCrystCrystal -from diffpy.srreal.tests.testutils import pickle_with_attr -from diffpy.srreal.overlapcalculator import OverlapCalculator from diffpy.srreal.atomradiitable import CovalentRadiiTable +from diffpy.srreal.overlapcalculator import OverlapCalculator +from diffpy.srreal.tests.testutils import ( + _msg_nopyobjcryst, + has_pyobjcryst, + loadDiffPyStructure, + loadObjCrystCrystal, + pickle_with_attr, +) # ---------------------------------------------------------------------------- @@ -41,7 +44,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,7 +52,7 @@ 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)) @@ -66,7 +69,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() @@ -77,7 +80,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 @@ -94,7 +97,8 @@ def test_pickling(self): 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) @@ -112,7 +116,7 @@ def test_pickling_artb(self): 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 @@ -129,8 +133,9 @@ 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 @@ -149,7 +154,7 @@ def test_parallel(self): return def test_distances(self): - """check OverlapCalculator.distances""" + """Check OverlapCalculator.distances.""" olc = self.olc olc(self.nickel) self.assertEqual(0, len(olc.distances)) @@ -166,7 +171,7 @@ def test_distances(self): return def test_directions(self): - """check OverlapCalculator.directions""" + """Check OverlapCalculator.directions.""" olc = self.olc olc(self.nickel) self.assertEqual([], olc.directions.tolist()) @@ -179,7 +184,7 @@ 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(self.rutile) @@ -197,7 +202,7 @@ 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) @@ -209,7 +214,7 @@ def test_sitesquareoverlaps(self): return def test_totalsquareoverlap(self): - """check OverlapCalculator.totalsquareoverlap""" + """Check OverlapCalculator.totalsquareoverlap.""" olc = self.olc self.assertEqual(0.0, olc.totalsquareoverlap) olc(self.rutile) @@ -220,7 +225,7 @@ def test_totalsquareoverlap(self): return def test_meansquareoverlap(self): - """check OverlapCalculator.meansquareoverlap""" + """Check OverlapCalculator.meansquareoverlap.""" olc = self.olc self.assertEqual(0.0, olc.meansquareoverlap) olc(self.nickel) @@ -238,7 +243,7 @@ def test_meansquareoverlap(self): return def test_flipDiffTotal(self): - """check OverlapCalculator.flipDiffTotal""" + """Check OverlapCalculator.flipDiffTotal.""" olc = self.olc olc.atomradiitable.fromString("Ti:1.6, O:0.66") olc(self.rutile) @@ -259,7 +264,7 @@ 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)) @@ -276,7 +281,7 @@ def test_getNeighborSites(self): return def test_coordinations(self): - """check OverlapCalculator.coordinations""" + """Check OverlapCalculator.coordinations.""" olc = self.olc self.assertEqual(0, len(olc.coordinations)) olc(self.rutile) @@ -288,7 +293,7 @@ def test_coordinations(self): return def test_coordinationByTypes(self): - """check OverlapCalculator.coordinationByTypes""" + """Check OverlapCalculator.coordinationByTypes.""" olc = self.olc olc(self.rutile) self.assertEqual({}, olc.coordinationByTypes(0)) @@ -306,7 +311,7 @@ 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) @@ -342,7 +347,7 @@ 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) @@ -353,7 +358,7 @@ def test_totalsquareoverlap(self): 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) @@ -364,7 +369,7 @@ def test_meansquareoverlap(self): 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)) @@ -379,7 +384,7 @@ def test_flipDiffTotal(self): 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)) @@ -397,7 +402,7 @@ 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)) @@ -409,7 +414,7 @@ def test_getNeighborSites(self): 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) @@ -421,7 +426,8 @@ def test_coordinations(self): 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)) @@ -435,7 +441,7 @@ def test_coordinationByTypes(self): 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) diff --git a/src/diffpy/srreal/tests/testpairquantity.py b/src/diffpy/srreal/tests/testpairquantity.py index 3fa96c80..c07da95c 100644 --- a/src/diffpy/srreal/tests/testpairquantity.py +++ b/src/diffpy/srreal/tests/testpairquantity.py @@ -1,18 +1,17 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.pairquantity -""" +"""Unit tests for diffpy.srreal.pairquantity.""" -import unittest import pickle +import unittest + import numpy from diffpy.srreal.pairquantity import PairQuantity -from diffpy.srreal.srreal_ext import BasePairQuantity from diffpy.srreal.pdfcalculator import PDFCalculator +from diffpy.srreal.srreal_ext import BasePairQuantity from diffpy.srreal.tests.testutils import mod_structure - # ---------------------------------------------------------------------------- @@ -40,7 +39,7 @@ def setUp(self): 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" @@ -60,7 +59,7 @@ def test_evaluatortype(self): 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 @@ -76,7 +75,7 @@ def test_setStructure(self): 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) @@ -90,13 +89,13 @@ def test_setPairMask_args(self): 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()) @@ -107,7 +106,7 @@ def test_ticker(self): 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() @@ -142,9 +141,14 @@ def test_optimized_evaluation(self): 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] + def eval_as(evtp, pq, stru): + setattr(pq, "evaluatortype", evtp) + pq.eval(stru) + return pq.eval() + eval_as("BASIC", pqd, c8) self.assertEqual("BASIC", pqd.evaluatortype) # pqd does not support OPTIMIZED evaluation. Its use will @@ -164,7 +168,7 @@ def test_optimized_evaluation(self): 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() diff --git a/src/diffpy/srreal/tests/testparallel.py b/src/diffpy/srreal/tests/testparallel.py index 6924ab8a..e6ae9c12 100644 --- a/src/diffpy/srreal/tests/testparallel.py +++ b/src/diffpy/srreal/tests/testparallel.py @@ -1,14 +1,15 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.parallel -""" +"""Unit tests for diffpy.srreal.parallel.""" -import unittest import multiprocessing +import unittest + import numpy -from diffpy.srreal.tests.testutils import loadDiffPyStructure + from diffpy.srreal.parallel import createParallelCalculator +from diffpy.srreal.tests.testutils import loadDiffPyStructure ############################################################################## @@ -44,7 +45,7 @@ def pool(self): 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() @@ -57,7 +58,7 @@ def test_parallel_evaluatortype(self): return def test_parallel_pdf(self): - """check parallel PDFCalculator""" + """Check parallel PDFCalculator.""" from diffpy.srreal.pdfcalculator import PDFCalculator pdfc = PDFCalculator() @@ -84,7 +85,7 @@ def test_parallel_pdf(self): return def test_parallel_bonds(self): - """check parallel BondCalculator""" + """Check parallel BondCalculator.""" from diffpy.srreal.bondcalculator import BondCalculator nickel = self.nickel diff --git a/src/diffpy/srreal/tests/testpdfbaseline.py b/src/diffpy/srreal/tests/testpdfbaseline.py index d3fd8277..152119e7 100644 --- a/src/diffpy/srreal/tests/testpdfbaseline.py +++ b/src/diffpy/srreal/tests/testpdfbaseline.py @@ -1,17 +1,16 @@ #!/usr/bin/env python -"""Unit tests for the PDFBaseline class from diffpy.srreal.pdfcalculator -""" +"""Unit tests for the PDFBaseline class from diffpy.srreal.pdfcalculator.""" -import unittest import pickle +import unittest + import numpy -from diffpy.srreal.tests.testutils import pickle_with_attr -from diffpy.srreal.pdfbaseline import PDFBaseline, makePDFBaseline -from diffpy.srreal.pdfbaseline import ZeroBaseline, LinearBaseline +from diffpy.srreal.pdfbaseline import LinearBaseline, PDFBaseline, ZeroBaseline, makePDFBaseline from diffpy.srreal.pdfcalculator import PDFCalculator +from diffpy.srreal.tests.testutils import pickle_with_attr # ---------------------------------------------------------------------------- @@ -31,14 +30,14 @@ def tearDown(self): 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.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)) @@ -56,7 +55,7 @@ def test___call__(self): 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 @@ -67,7 +66,7 @@ def test_clone(self): 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()) @@ -77,7 +76,7 @@ def test_create(self): 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()) @@ -87,7 +86,7 @@ def test_type(self): 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") @@ -104,7 +103,7 @@ def test__aliasType(self): 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")) @@ -113,12 +112,12 @@ def test__deregisterType(self): return def test_createByType(self): - """check PDFBaseline.createByType()""" + """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") @@ -126,7 +125,7 @@ def test_isRegisteredType(self): return def test_getAliasedTypes(self): - """check PDFBaseline.getAliasedTypes()""" + """Check PDFBaseline.getAliasedTypes()""" self.assertEqual({}, PDFBaseline.getAliasedTypes()) PDFBaseline._aliasType("linear", "foo") PDFBaseline._aliasType("linear", "bar") @@ -136,7 +135,7 @@ def test_getAliasedTypes(self): return def test_getRegisteredTypes(self): - """check PDFBaseline.getRegisteredTypes""" + """Check PDFBaseline.getRegisteredTypes.""" regtypes = PDFBaseline.getRegisteredTypes() self.assertTrue(2 <= len(regtypes)) self.assertTrue("linear" in regtypes) @@ -144,7 +143,7 @@ def test_getRegisteredTypes(self): 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)) @@ -156,7 +155,7 @@ def test_pickling(self): return def test_makePDFBaseline(self): - """check the makePDFBaseline wrapper.""" + """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)) @@ -191,7 +190,7 @@ def test_makePDFBaseline(self): return def test_picking_owned(self): - """verify pickling of PDFBaseline owned by PDF calculators.""" + """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" diff --git a/src/diffpy/srreal/tests/testpdfcalcobjcryst.py b/src/diffpy/srreal/tests/testpdfcalcobjcryst.py index 4f5960a7..01ef21b8 100644 --- a/src/diffpy/srreal/tests/testpdfcalcobjcryst.py +++ b/src/diffpy/srreal/tests/testpdfcalcobjcryst.py @@ -1,19 +1,16 @@ #!/usr/bin/env python -"""Unit tests for pdfcalculator.py on ObjCryst crystal structures -""" +"""Unit tests for pdfcalculator.py on ObjCryst crystal structures.""" import re import unittest import numpy -from diffpy.srreal.pdfcalculator import PDFCalculator -from diffpy.srreal.tests.testutils import has_pyobjcryst, _msg_nopyobjcryst -from diffpy.srreal.tests.testutils import loadObjCrystCrystal -from diffpy.srreal.tests.testutils import datafile +from diffpy.srreal.pdfcalculator import PDFCalculator from diffpy.srreal.tests.testpdfcalculator import _maxNormDiff +from diffpy.srreal.tests.testutils import _msg_nopyobjcryst, datafile, has_pyobjcryst, loadObjCrystCrystal # helper functions @@ -41,7 +38,8 @@ def _loadExpectedPDF(basefilename): def _makePDFCalculator(crst, cfgdict): - """Return a PDFCalculator object evaluated for a pyobjcryst.Crystal crst.""" + """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: @@ -81,19 +79,19 @@ def setself(**kwtoset): return def test_CdSeN(self): - """check PDFCalculator on ObjCryst loaded CIF, neutrons""" + """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""" + """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""" + """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 diff --git a/src/diffpy/srreal/tests/testpdfcalculator.py b/src/diffpy/srreal/tests/testpdfcalculator.py index 7c1e2645..5b790032 100644 --- a/src/diffpy/srreal/tests/testpdfcalculator.py +++ b/src/diffpy/srreal/tests/testpdfcalculator.py @@ -1,24 +1,21 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.pdfcalculator -""" +"""Unit tests for diffpy.srreal.pdfcalculator.""" -import unittest import pickle +import unittest import numpy -from diffpy.srreal.tests.testutils import loadDiffPyStructure -from diffpy.srreal.tests.testutils import datafile -from diffpy.srreal.tests.testutils import pickle_with_attr -from diffpy.srreal.pdfcalculator import PDFCalculator -from diffpy.srreal.pdfcalculator import fftgtof, fftftog + +from diffpy.srreal.pdfcalculator import PDFCalculator, fftftog, fftgtof +from diffpy.srreal.tests.testutils import datafile, loadDiffPyStructure, pickle_with_attr # 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 @@ -46,7 +43,7 @@ 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) @@ -73,7 +70,7 @@ 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")) @@ -81,19 +78,19 @@ def test__getDoubleAttr(self): return def test__hasDoubleAttr(self): - """check PDFCalculator._hasDoubleAttr()""" + """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()) 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")) @@ -102,7 +99,7 @@ def test__setDoubleAttr(self): return def test_eval_nickel(self): - """check PDFCalculator.eval() on simple Nickel data""" + """Check PDFCalculator.eval() on simple Nickel data.""" fnipf2 = datafile("Ni-fit.fgr") gpf2 = numpy.loadtxt(fnipf2, usecols=(1,)) self.pdfcalc._setDoubleAttr("rmax", 10.0001) @@ -112,7 +109,7 @@ def test_eval_nickel(self): return def test_eval_rutile(self): - """check PDFCalculator.eval() on anisotropic rutile data""" + """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 @@ -231,7 +228,7 @@ 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) @@ -276,7 +273,7 @@ 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 diff --git a/src/diffpy/srreal/tests/testpdfenvelope.py b/src/diffpy/srreal/tests/testpdfenvelope.py index 7adb1060..cf840554 100644 --- a/src/diffpy/srreal/tests/testpdfenvelope.py +++ b/src/diffpy/srreal/tests/testpdfenvelope.py @@ -1,18 +1,23 @@ #!/usr/bin/env python -"""Unit tests for the PDFEnvelope class from diffpy.srreal.pdfcalculator -""" +"""Unit tests for the PDFEnvelope class from diffpy.srreal.pdfcalculator.""" -import unittest import pickle +import unittest + import numpy +from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator +from diffpy.srreal.pdfenvelope import ( + PDFEnvelope, + QResolutionEnvelope, + ScaleEnvelope, + SphericalShapeEnvelope, + StepCutEnvelope, + makePDFEnvelope, +) from diffpy.srreal.tests.testutils import pickle_with_attr -from diffpy.srreal.pdfenvelope import PDFEnvelope, makePDFEnvelope -from diffpy.srreal.pdfenvelope import QResolutionEnvelope, ScaleEnvelope -from diffpy.srreal.pdfenvelope import SphericalShapeEnvelope, StepCutEnvelope -from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator # ---------------------------------------------------------------------------- @@ -30,14 +35,14 @@ def tearDown(self): 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.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) @@ -56,7 +61,7 @@ def test___call__(self): 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 @@ -67,7 +72,7 @@ def test_clone(self): 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()) @@ -77,7 +82,7 @@ def test_create(self): 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()) @@ -85,12 +90,12 @@ def test_type(self): return def test_createByType(self): - """check PDFEnvelope.createByType()""" + """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) @@ -98,7 +103,7 @@ def test_getRegisteredTypes(self): 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)) @@ -108,7 +113,7 @@ def test_pickling(self): return def test_makePDFEnvelope(self): - """check the makePDFEnvelope wrapper.""" + """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)) @@ -132,7 +137,7 @@ def test_makePDFEnvelope(self): return def test_picking_owned(self): - """verify pickling of envelopes owned by PDF calculators.""" + """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" diff --git a/src/diffpy/srreal/tests/testpeakprofile.py b/src/diffpy/srreal/tests/testpeakprofile.py index d187e969..56e3943e 100644 --- a/src/diffpy/srreal/tests/testpeakprofile.py +++ b/src/diffpy/srreal/tests/testpeakprofile.py @@ -1,17 +1,16 @@ #!/usr/bin/env python -"""Unit tests for the PeakProfile classes from diffpy.srreal.peakprofile -""" +"""Unit tests for the PeakProfile classes from diffpy.srreal.peakprofile.""" -import unittest import pickle +import unittest + import numpy -from diffpy.srreal.tests.testutils import pickle_with_attr -from diffpy.srreal.tests.testutils import mod_structure -from diffpy.srreal.peakprofile import PeakProfile from diffpy.srreal.pdfcalculator import PDFCalculator +from diffpy.srreal.peakprofile import PeakProfile +from diffpy.srreal.tests.testutils import mod_structure, pickle_with_attr # ---------------------------------------------------------------------------- @@ -27,7 +26,7 @@ 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) @@ -35,7 +34,7 @@ def test___init__(self): 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()) @@ -44,7 +43,7 @@ def test_create(self): 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 @@ -55,14 +54,14 @@ def test_clone(self): 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()) 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) @@ -73,7 +72,7 @@ def test___call__(self): return def test_ticker(self): - """check PeakProfile.ticker()""" + """Check PeakProfile.ticker()""" from diffpy.srreal.eventticker import EventTicker et0 = EventTicker(self.pkgauss.ticker()) @@ -84,7 +83,7 @@ def test_ticker(self): 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() @@ -103,14 +102,14 @@ def test_ticker_override(self): 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"])) 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)) diff --git a/src/diffpy/srreal/tests/testpeakwidthmodel.py b/src/diffpy/srreal/tests/testpeakwidthmodel.py index 18a00465..0ba053f7 100644 --- a/src/diffpy/srreal/tests/testpeakwidthmodel.py +++ b/src/diffpy/srreal/tests/testpeakwidthmodel.py @@ -1,15 +1,14 @@ #!/usr/bin/env python -"""Unit tests for the PeakWidthModel classes from diffpy.srreal.peakwidthmodel -""" +"""Unit tests for the PeakWidthModel classes from +diffpy.srreal.peakwidthmodel.""" -import unittest import pickle +import unittest -from diffpy.srreal.peakwidthmodel import PeakWidthModel -from diffpy.srreal.peakwidthmodel import DebyeWallerPeakWidth, JeongPeakWidth from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator +from diffpy.srreal.peakwidthmodel import DebyeWallerPeakWidth, JeongPeakWidth, PeakWidthModel from diffpy.srreal.structureadapter import createStructureAdapter from diffpy.srreal.tests.testutils import loadDiffPyStructure @@ -41,14 +40,14 @@ def _genbonds(self, rmin, rmax): 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.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()) @@ -57,7 +56,7 @@ def test_create(self): 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 @@ -68,14 +67,14 @@ def test_clone(self): 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()) return def test_calculate(self): - """check PeakWidthModel.calculate()""" + """Check PeakWidthModel.calculate()""" pwm = PeakWidthModel() bnds = self._genbonds(1, 2) self.assertRaises(RuntimeError, pwm.calculate, bnds) @@ -83,7 +82,7 @@ def test_calculate(self): return def test_isowidths(self): - """check ConstantPeakWidth properties bisowidth, uisowidth.""" + """Check ConstantPeakWidth properties bisowidth, uisowidth.""" from numpy import pi cnpw = self.pwconst @@ -96,14 +95,14 @@ def test_isowidths(self): return def test_maxWidth(self): - """check PeakWidthModel.maxWidth()""" + """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()) @@ -114,7 +113,7 @@ def test_ticker(self): 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() @@ -133,14 +132,14 @@ def test_ticker_override(self): 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"])) 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)) @@ -160,13 +159,13 @@ def setUp(self): return def test_type(self): - """check DebyeWallerPeakWidth.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.""" + """Check pickling of DebyeWallerPeakWidth class.""" self.assertEqual("debye-waller", self.pwm.type()) pwm = self.pwm pwm2 = pickle.loads(pickle.dumps(pwm)) @@ -184,7 +183,7 @@ def setUp(self): return def test_type(self): - """check JeongPeakWidth.type""" + """Check JeongPeakWidth.type.""" self.assertEqual("jeong", self.pwm.type()) self.assertTrue(hasattr(self.pwm, "delta1")) self.assertTrue(hasattr(self.pwm, "delta2")) @@ -192,7 +191,7 @@ def test_type(self): 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 diff --git a/src/diffpy/srreal/tests/testscatteringfactortable.py b/src/diffpy/srreal/tests/testscatteringfactortable.py index ba4dbebc..e4c95be6 100644 --- a/src/diffpy/srreal/tests/testscatteringfactortable.py +++ b/src/diffpy/srreal/tests/testscatteringfactortable.py @@ -1,18 +1,22 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.scatteringfactortable -""" +"""Unit tests for diffpy.srreal.scatteringfactortable.""" -import unittest import pickle +import unittest + import numpy +from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator +from diffpy.srreal.scatteringfactortable import ( + ScatteringFactorTable, + SFTElectron, + SFTElectronNumber, + SFTNeutron, + SFTXray, +) from diffpy.srreal.tests.testutils import pickle_with_attr -from diffpy.srreal.scatteringfactortable import ScatteringFactorTable -from diffpy.srreal.scatteringfactortable import SFTXray, SFTElectron -from diffpy.srreal.scatteringfactortable import SFTNeutron, SFTElectronNumber -from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator # ---------------------------------------------------------------------------- @@ -58,7 +62,7 @@ def tearDown(self): return def test_class_registry(self): - """check if instances are aliased by radiationType().""" + """Check if instances are aliased by radiationType().""" ltb = ScatteringFactorTable.createByType("LTB") self.assertTrue(type(ltb) is LocalTable) ltb2 = ScatteringFactorTable.createByType("localtable") @@ -66,7 +70,7 @@ def test_class_registry(self): return def test_ticker(self): - """check ScatteringFactorTable.ticker()""" + """Check ScatteringFactorTable.ticker()""" from diffpy.srreal.eventticker import EventTicker et0 = EventTicker(self.sftx.ticker()) @@ -77,7 +81,7 @@ def test_ticker(self): 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() @@ -98,7 +102,7 @@ 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") @@ -116,7 +120,7 @@ def test_pickling(self): 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() @@ -137,7 +141,7 @@ def test_picking_owned(self): 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(set(), lsft.getCustomSymbols()) diff --git a/src/diffpy/srreal/tests/testsfaverage.py b/src/diffpy/srreal/tests/testsfaverage.py index b23cb8a6..6efaa981 100644 --- a/src/diffpy/srreal/tests/testsfaverage.py +++ b/src/diffpy/srreal/tests/testsfaverage.py @@ -1,17 +1,20 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.sfaverage -""" +"""Unit tests for diffpy.srreal.sfaverage.""" import unittest + import numpy -from diffpy.srreal.sfaverage import SFAverage from diffpy.srreal.scatteringfactortable import ScatteringFactorTable -from diffpy.srreal.tests.testutils import loadDiffPyStructure -from diffpy.srreal.tests.testutils import has_pyobjcryst, _msg_nopyobjcryst -from diffpy.srreal.tests.testutils import loadObjCrystCrystal +from diffpy.srreal.sfaverage import SFAverage +from diffpy.srreal.tests.testutils import ( + _msg_nopyobjcryst, + has_pyobjcryst, + loadDiffPyStructure, + loadObjCrystCrystal, +) # ---------------------------------------------------------------------------- @@ -27,7 +30,7 @@ def tearDown(self): return def test_fromStructure_CdSe(self): - """check SFAverage.fromStructure() for CdSe""" + """Check SFAverage.fromStructure() for CdSe.""" cdse = loadDiffPyStructure("CdSe_cadmoselite.cif") sfavg = SFAverage.fromStructure(cdse, self.sftx) fcd = self.sftx.lookup("Cd") @@ -55,7 +58,7 @@ def test_fromStructure_CdSe(self): return def test_fromComposition(self): - """check SFAverage.fromComposition()""" + """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]) @@ -86,7 +89,7 @@ def tearDown(self): return def test_from_rutile(self): - """check SFAverage.fromStructure for pyobjcryst Crystal of rutile.""" + """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) diff --git a/src/diffpy/srreal/tests/teststructureadapter.py b/src/diffpy/srreal/tests/teststructureadapter.py index 932a4ddc..55a3604c 100644 --- a/src/diffpy/srreal/tests/teststructureadapter.py +++ b/src/diffpy/srreal/tests/teststructureadapter.py @@ -1,28 +1,32 @@ #!/usr/bin/env python -"""Unit tests for diffpy.srreal.structureadapter -""" +"""Unit tests for diffpy.srreal.structureadapter.""" -import unittest import pickle +import unittest + import numpy + +import diffpy.srreal.tests.testutils as testutils from diffpy.srreal.pdfcalculator import PDFCalculator -from diffpy.srreal.tests.testutils import has_pyobjcryst, _msg_nopyobjcryst -from diffpy.srreal.tests.testutils import loadObjCrystCrystal -from diffpy.srreal.tests.testutils import loadDiffPyStructure -from diffpy.srreal.tests.testutils import loadCrystalStructureAdapter from diffpy.srreal.structureadapter import ( + Atom, + AtomicStructureAdapter, + CrystalStructureAdapter, + PeriodicStructureAdapter, + StructureAdapter, createStructureAdapter, nometa, nosymmetry, - StructureAdapter, - AtomicStructureAdapter, - Atom, - PeriodicStructureAdapter, - CrystalStructureAdapter, ) -import diffpy.srreal.tests.testutils as testutils +from diffpy.srreal.tests.testutils import ( + _msg_nopyobjcryst, + has_pyobjcryst, + loadCrystalStructureAdapter, + loadDiffPyStructure, + loadObjCrystCrystal, +) # ---------------------------------------------------------------------------- @@ -34,7 +38,7 @@ def setUp(self): 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)) @@ -74,7 +78,7 @@ 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) @@ -113,7 +117,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) @@ -123,7 +127,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)) @@ -162,7 +166,7 @@ def setUp(self): return def test_nometa(self): - """check NoMetaStructureAdapter.""" + """Check NoMetaStructureAdapter.""" r0, g0 = PDFCalculator()(self.nickel) ni1 = self.nickel.copy() ni1.pdffit["scale"] = 2.0 @@ -188,7 +192,7 @@ 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 @@ -200,7 +204,7 @@ 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) @@ -218,7 +222,7 @@ def setUp(self): return def test_nosymmetry(self): - """check NoSymmetryStructureAdapter.""" + """Check NoSymmetryStructureAdapter.""" pdfc0 = PDFCalculator() r0, g0 = pdfc0(self.nickel) rdf0 = pdfc0.rdf @@ -242,13 +246,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)) @@ -273,7 +277,7 @@ def setUp(self): 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)) @@ -289,7 +293,7 @@ def test_objcryst_adapter(self): 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) @@ -487,34 +491,34 @@ def setUp(self): # 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 if we use the C++ method that alwasy return 1. + """Check StructureAdapter.siteOccupancy()""" + # check if we use the C++ method that always 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 @@ -536,7 +540,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) @@ -544,7 +548,7 @@ 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() @@ -553,7 +557,7 @@ def test_equality(self): 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) @@ -562,7 +566,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)) @@ -572,7 +576,7 @@ 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 diff --git a/src/diffpy/srreal/tests/testutils.py b/src/diffpy/srreal/tests/testutils.py index c16ae8dd..8cbb3ecc 100644 --- a/src/diffpy/srreal/tests/testutils.py +++ b/src/diffpy/srreal/tests/testutils.py @@ -1,13 +1,19 @@ #!/usr/bin/env python -"""Helper routines for running other unit tests. -""" +"""Helper routines for running other unit tests.""" import copy -import numpy import pickle +import numpy + +from diffpy.srreal.structureadapter import ( + AtomicStructureAdapter, + CrystalStructureAdapter, + PeriodicStructureAdapter, + StructureAdapter, +) from diffpy.srreal.structureconverters import convertObjCrystCrystal from diffpy.srreal.tests import logger @@ -104,11 +110,6 @@ def pickle_with_attr(obj, **attr): # helper class for testing overloading of StructureAdapter -from diffpy.srreal.structureadapter import StructureAdapter -from diffpy.srreal.structureadapter import AtomicStructureAdapter -from diffpy.srreal.structureadapter import PeriodicStructureAdapter -from diffpy.srreal.structureadapter import CrystalStructureAdapter - class HasCustomPQConfig(object): diff --git a/src/diffpy/srreal/version.py b/src/diffpy/srreal/version.py index a078d249..67596f6b 100644 --- a/src/diffpy/srreal/version.py +++ b/src/diffpy/srreal/version.py @@ -12,9 +12,7 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -""" -Definitions of version-related constants and of libdiffpy_version_info. +"""Definitions of version-related constants and of libdiffpy_version_info. Notes ----- @@ -28,10 +26,7 @@ __all__ = ["__date__", "__git_commit__", "__timestamp__", "__version__", "libdiffpy_version_info"] -from diffpy.srreal._version_data import __version__ -from diffpy.srreal._version_data import __date__ -from diffpy.srreal._version_data import __git_commit__ -from diffpy.srreal._version_data import __timestamp__ +from diffpy.srreal._version_data import __date__, __git_commit__, __timestamp__, __version__ # TODO remove deprecated __gitsha__ in version 1.4. __gitsha__ = __git_commit__ @@ -39,6 +34,7 @@ # version information on the active libdiffpy shared library ----------------- from collections import namedtuple + from diffpy.srreal.srreal_ext import _get_libdiffpy_version_info_dict libdiffpy_version_info = namedtuple( diff --git a/src/diffpy/srreal/wraputils.py b/src/diffpy/srreal/wraputils.py index e9eb19e1..a026edd3 100644 --- a/src/diffpy/srreal/wraputils.py +++ b/src/diffpy/srreal/wraputils.py @@ -12,9 +12,7 @@ # See LICENSE_DANSE.txt for license information. # ############################################################################## - -"""Local utilities helpful for tweaking interfaces to boost python classes. -""" +"""Local utilities helpful for tweaking interfaces to boost python classes.""" import copy @@ -63,8 +61,8 @@ def setattrFromKeywordArguments(obj, **kwargs): def _wrapAsRegisteredUnaryFunction(cls, regname, fnc, replace=False, **dbattrs): """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. + PDFEnvelope functor. Not intended for direct usage, this function is + rather called from makePDFBaseline or makePDFEnvelope wrappers. cls -- the functor class for wrapping the Python function regname -- string name for registering the function in the global @@ -96,9 +94,9 @@ def clone(self): return copy.copy(self) def type(self): - """Unique string identifier of this functor type. The string - is used for class registration and as an argument for the - createByType function. + """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. """