diff --git a/.codecov.yml b/.codecov.yml deleted file mode 100644 index 4af5eb24..00000000 --- a/.codecov.yml +++ /dev/null @@ -1,14 +0,0 @@ -coverage: - status: - project: # more options at https://docs.codecov.com/docs/commit-status - default: - target: auto # use the coverage from the base commit, fail if coverage is lower - threshold: 0% # allow the coverage to drop by - -comment: - layout: " diff, flags, files" - behavior: default - require_changes: false - require_base: false # [true :: must have a base report to post] - require_head: false # [true :: must have a head report to post] - hide_project_coverage: false # [true :: only show coverage on the git diff aka patch coverage] diff --git a/.codespell/ignore_lines.txt b/.codespell/ignore_lines.txt deleted file mode 100644 index 07fa7c8c..00000000 --- a/.codespell/ignore_lines.txt +++ /dev/null @@ -1,2 +0,0 @@ -;; 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 deleted file mode 100644 index 7ca2aeac..00000000 --- a/.codespell/ignore_words.txt +++ /dev/null @@ -1,17 +0,0 @@ -;; 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 - -;; Frobenius norm used in np.linalg.norm -fro - -;; structure file format -discus - -;; variable name within pdfbaseline module -aline - -;; variable name within TestSFAverageObjCryst class -fo diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 88077af0..00000000 --- a/.flake8 +++ /dev/null @@ -1,13 +0,0 @@ -# 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, - docs/source/conf.py -max-line-length = 79 -# 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/.github/ISSUE_TEMPLATE/bug_feature.md b/.github/ISSUE_TEMPLATE/bug_feature.md deleted file mode 100644 index b3454deb..00000000 --- a/.github/ISSUE_TEMPLATE/bug_feature.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: Bug Report or Feature Request -about: Report a bug or suggest a new feature! -title: "" -labels: "" -assignees: "" ---- - -### Problem - - - -### Proposed solution diff --git a/.github/ISSUE_TEMPLATE/release_checklist.md b/.github/ISSUE_TEMPLATE/release_checklist.md deleted file mode 100644 index 6107962c..00000000 --- a/.github/ISSUE_TEMPLATE/release_checklist.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -name: Release -about: Checklist and communication channel for PyPI and GitHub release -title: "Ready for PyPI/GitHub release" -labels: "release" -assignees: "" ---- - -### PyPI/GitHub rc-release preparation checklist: - -- [ ] All PRs/issues attached to the release are merged. -- [ ] All the badges on the README are passing. -- [ ] License information is verified as correct. If you are unsure, please comment below. -- [ ] Locally rendered documentation contains all appropriate pages, including API references (check no modules are - missing), tutorials, and other human-written text is up-to-date with any changes in the code. -- [ ] Installation instructions in the README, documentation, and the website are updated. -- [ ] Successfully run any tutorial examples or do functional testing with the latest Python version. -- [ ] Grammar and writing quality are checked (no typos). -- [ ] Install `pip install build twine`, run `python -m build` and `twine check dist/*` to ensure that the package can be built and is correctly formatted for PyPI release. - -Please tag the maintainer (e.g., @username) in the comment here when you are ready for the PyPI/GitHub release. Include any additional comments necessary, such as version information and details about the pre-release here: - -### PyPI/GitHub full-release preparation checklist: - -- [ ] Create a new conda environment and install the rc from PyPI (`pip install ==??`) -- [ ] License information on PyPI is correct. -- [ ] Docs are deployed successfully to `https:///`. -- [ ] Successfully run all tests, tutorial examples or do functional testing. - -Please let the maintainer know that all checks are done and the package is ready for full release. - -### conda-forge release preparation checklist: - - - -- [ ] Ensure that the full release has appeared on PyPI successfully. -- [ ] New package dependencies listed in `conda.txt` and `test.txt` are added to `meta.yaml` in the feedstock. -- [ ] Close any open issues on the feedstock. Reach out to the maintainer if you have questions. -- [ ] Tag the maintainer for conda-forge release. - -### Post-release checklist - - - -- [ ] Run tutorial examples and conduct functional testing using the installation guide in the README. Attach screenshots/results as comments. -- [ ] Documentation (README, tutorials, API references, and websites) is deployed without broken links or missing figures. diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md deleted file mode 100644 index 1099d862..00000000 --- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md +++ /dev/null @@ -1,15 +0,0 @@ -### What problem does this PR address? - - - -### What should the reviewer(s) do? - - - - diff --git a/.github/workflows/build-wheel-release-upload.yml b/.github/workflows/build-wheel-release-upload.yml deleted file mode 100644 index caaf5a0a..00000000 --- a/.github/workflows/build-wheel-release-upload.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Release (GitHub/PyPI) and Deploy Docs - -on: - workflow_dispatch: - push: - tags: - - "*" # Trigger on all tags initially, but tag and release privilege are verified in _build-wheel-release-upload.yml - -jobs: - release: - uses: scikit-package/release-scripts/.github/workflows/_build-wheel-release-upload.yml@v0 - with: - project: diffpy.srreal - c_extension: true - maintainer_GITHUB_username: sbillinge - secrets: - PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} - PAT_TOKEN: ${{ secrets.PAT_TOKEN }} diff --git a/.github/workflows/check-news-item.yml b/.github/workflows/check-news-item.yml deleted file mode 100644 index 88908d6f..00000000 --- a/.github/workflows/check-news-item.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: Check for News - -on: - pull_request_target: - branches: - - main - -jobs: - check-news-item: - uses: scikit-package/release-scripts/.github/workflows/_check-news-item.yml@v0 - with: - project: diffpy.srreal diff --git a/.github/workflows/matrix-and-codecov-on-merge-to-main.yml b/.github/workflows/matrix-and-codecov-on-merge-to-main.yml deleted file mode 100644 index 9d2881b3..00000000 --- a/.github/workflows/matrix-and-codecov-on-merge-to-main.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: CI - -on: - push: - branches: - - main - release: - types: - - prereleased - - published - workflow_dispatch: - -jobs: - matrix-coverage: - uses: scikit-package/release-scripts/.github/workflows/_matrix-and-codecov-on-merge-to-main.yml@v0 - with: - project: diffpy.srreal - c_extension: true - headless: false - secrets: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/publish-docs-on-release.yml b/.github/workflows/publish-docs-on-release.yml deleted file mode 100644 index 108cc184..00000000 --- a/.github/workflows/publish-docs-on-release.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: Deploy Documentation on Release - -on: - workflow_dispatch: - -jobs: - docs: - uses: scikit-package/release-scripts/.github/workflows/_publish-docs-on-release.yml@v0 - with: - project: diffpy.srreal - c_extension: true - headless: false diff --git a/.github/workflows/tests-on-pr.yml b/.github/workflows/tests-on-pr.yml deleted file mode 100644 index 3deb95d2..00000000 --- a/.github/workflows/tests-on-pr.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Tests on PR - -on: - pull_request: - workflow_dispatch: - -jobs: - tests-on-pr: - uses: scikit-package/release-scripts/.github/workflows/_tests-on-pr.yml@v0 - with: - project: diffpy.srreal - c_extension: true - headless: false - secrets: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 099e2948..00000000 --- a/.gitignore +++ /dev/null @@ -1,93 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -_build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -venv/ -*.egg-info/ -.installed.cfg -*.egg -bin/ -temp/ -tags/ -errors.err - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt -MANIFEST - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Mr Developer -.mr.developer.cfg -.project -.pydevproject - -# Django stuff: -*.log - -# Sphinx documentation -docs/build/ -docs/source/generated/ - -# pytest -.pytest_cache/ - -# PyBuilder -target/ - -# Editor files -# mac -.DS_Store -*~ - -# vim -*.swp -*.swo - -# pycharm -.idea/ - -# VSCode -.vscode/ - -# Ipython Notebook -.ipynb_checkpoints diff --git a/.isort.cfg b/.isort.cfg deleted file mode 100644 index 86f162b8..00000000 --- a/.isort.cfg +++ /dev/null @@ -1,5 +0,0 @@ -[settings] -# Keep import statement below line_length character limit -line_length = 79 -multi_line_output = 3 -include_trailing_comma = True diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 0e4a84d1..00000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,66 +0,0 @@ -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 - - 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/.readthedocs.yaml b/.readthedocs.yaml deleted file mode 100644 index aaa88895..00000000 --- a/.readthedocs.yaml +++ /dev/null @@ -1,13 +0,0 @@ -version: 2 - -build: - os: "ubuntu-22.04" - tools: - python: "latest" - -python: - install: - - requirements: requirements/docs.txt - -sphinx: - configuration: docs/source/conf.py diff --git a/AUTHORS.rst b/AUTHORS.rst deleted file mode 100644 index ad15dbc7..00000000 --- a/AUTHORS.rst +++ /dev/null @@ -1,12 +0,0 @@ -Authors -======= - -Pavol Juhas, -Chris Farrow, -Simon J.L. Billinge - -Contributors ------------- - -For a list of contributors, visit -https://github.com/diffpy/diffpy.srreal/graphs/contributors diff --git a/CHANGELOG.rst b/CHANGELOG.rst deleted file mode 100644 index 8b0a830a..00000000 --- a/CHANGELOG.rst +++ /dev/null @@ -1,65 +0,0 @@ -============= -Release notes -============= - -.. current developments - -1.4.0 -===== - -**Added:** - -* Update linelength to sk-package standard of 79 characters. - -**Changed:** - -* Renamed CODE_OF_CONDUCTS.rst to CODE-OF-CONDUCTS.rst, doc folder to docs, and requirements/test.txt to requirements/tests.txt - -**Fixed:** - -* Configure ``black`` to have a linelength requirement of 79 characters. -* Update requirements to use full release `libdiffpy` and remove wrong build dependencies. -* Support ``scikit-package`` Level 5 standard (https://scikit-package.github.io/scikit-package/). - - - -Version 1.3.0 2019-03-13 -========================= - -Main differences from version 1.2. - -**Added:** - -* Support for Python 3.7, 3.6, 3.5 in addition to 2.7. -* Validation of compiler options from `python-config`. -* Make scons scripts compatible with Python 3 and Python 2. -* `ConstantPeakWidth` attributes `uisowidth`, `bisowidth` to ease - PDF simulation with uniform isotropic atom displacements. - -**Changed:** - -* Require libdiffpy 1.4 or later. -* Build Anaconda package with Anaconda C++ compiler. -* Allow language standard c++11. -* Pickle format for `PDFCalculator`, `DebyePDFCalculator`, - `OverlapCalculator`, `PeakWidthModel`, `PeakProfile`, `PDFEnvelope`, - `PDFBaseline`, and `ScatteringFactorTable` objects. - -**Deprecated:** - -* Variable `__gitsha__` in the `version` module renamed to `__git_commit__`. -* `libdiffpy_version_info` attribute `git_sha` renamed to `git_commit`. - -**Removed** - -* Unused method `BVParam.__hash__`. -* Disable pickling of `BasePairQuantity` as it is in effect abstract. -* Pickling of Python-added attributes to exported C++ classes. -* Function `get_libdiffpy_version_info` from the `version` module. - -**Fixed** - -* Return value conversion of `CrystalStructureAdapter` methods - `expandLatticeAtom` and `getEquivalentAtoms` methods. - Make them return a `list` of `Atom` objects. -* Name suffix resolution of `boost_python` shared library. diff --git a/CODE-OF-CONDUCT.rst b/CODE-OF-CONDUCT.rst deleted file mode 100644 index e8199ca5..00000000 --- a/CODE-OF-CONDUCT.rst +++ /dev/null @@ -1,133 +0,0 @@ -===================================== - Contributor Covenant Code of Conduct -===================================== - -Our Pledge ----------- - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socioeconomic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -Our Standards -------------- - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or advances of - any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -Enforcement Responsibilities ----------------------------- - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -Scope ------ - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official email address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -Enforcement ------------ - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -sb2896@columbia.edu. All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -Enforcement Guidelines ----------------------- - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -1. Correction -**************** - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -2. Warning -************* - -**Community Impact**: A violation through a single incident or series of -actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. - -3. Temporary Ban -****************** - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -4. Permanent Ban -****************** - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the -community. - -Attribution ------------ - -This Code of Conduct is adapted from the `Contributor Covenant `_. - -Community Impact Guidelines were inspired by `Mozilla's code of conduct enforcement ladder `_. - -For answers to common questions about this code of conduct, see the `FAQ `_. `Translations are available `_ diff --git a/LICENSE.rst b/LICENSE.rst deleted file mode 100644 index c983d73f..00000000 --- a/LICENSE.rst +++ /dev/null @@ -1,142 +0,0 @@ -OPEN SOURCE LICENSE AGREEMENT -============================= - -Copyright (c) 2009-2011, University of Tennessee - -Copyright (c) 1989, 1991 Free Software Foundation, Inc. - -Copyright (c) 2006, The Regents of the University of California through Lawrence Berkeley National Laboratory - -Copyright (c) 2014, Australian Synchrotron Research Program Inc., ("ASRP") - -Copyright (c) 2006-2007, Board of Trustees of Michigan State University - -Copyright (c) 2008-2012, The Trustees of Columbia University in the City of New York - -Copyright (c) 2014-2019, Brookhaven Science Associates, Brookhaven National Laboratory - -Copyright (c) 2024, The Trustees of Columbia University in the City of New York. -All rights reserved. - -The "DiffPy-CMI" is distributed subject to the following license conditions: - -.. code-block:: text - - SOFTWARE LICENSE AGREEMENT - - Software: DiffPy-CMI - - - (1) The "Software", below, refers to the aforementioned DiffPy-CMI (in either - source code, or binary form and accompanying documentation). - - Part of the software was derived from the DANSE, ObjCryst++ (with permission), - PyCifRW, Python periodictable, CCTBX, and SasView open source projects, of - which the original Copyrights are contained in each individual file. - - Each licensee is addressed as "you" or "Licensee." - - - (2) The copyright holders shown above and their third-party Licensors hereby - grant licensee a royalty-free nonexclusive license, subject to the limitations - stated herein and U.S. Government license rights. - - - (3) You may modify and make a copy or copies of the software for use within - your organization, if you meet the following conditions: - - (a) Copies in source code must include the copyright notice and this - software license agreement. - - (b) Copies in binary form must include the copyright notice and this - Software License Agreement in the documentation and/or other materials - provided with the copy. - - - (4) You may modify a copy or copies of the Software or any portion of it, thus - forming a work based on the Software, and distribute copies of such work - outside your organization, if you meet all of the following conditions: - - (a) Copies in source code must include the copyright notice and this - Software License Agreement; - - (b) Copies in binary form must include the copyright notice and this - Software License Agreement in the documentation and/or other materials - provided with the copy; - - (c) Modified copies and works based on the Software must carry prominent - notices stating that you changed specified portions of the Software. - - (d) Neither the name of Brookhaven Science Associates or Brookhaven - National Laboratory nor the names of its contributors may be used to - endorse or promote products derived from this software without specific - written permission. - - - (5) Portions of the Software resulted from work developed under a U.S. - Government contract and are subject to the following license: - The Government is granted for itself and others acting on its behalf a - paid-up, nonexclusive, irrevocable worldwide license in this computer software - to reproduce, prepare derivative works, and perform publicly and display - publicly. - - - (6) WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT - WARRANTY OF ANY KIND. THE COPYRIGHT HOLDERS, THEIR THIRD PARTY - LICENSORS, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND - THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR IMPLIED, INCLUDING - BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - PARTICULAR PURPOSE, TITLE OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL - LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR USEFULNESS OF - THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF THE SOFTWARE WOULD NOT INFRINGE - PRIVATELY OWNED RIGHTS, (4) DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION - UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL BE CORRECTED. - - - (7) LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT HOLDERS, THEIR - THIRD PARTY LICENSORS, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF - ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, INCIDENTAL, - CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF ANY KIND OR NATURE, INCLUDING - BUT NOT LIMITED TO LOSS OF PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, - WHETHER SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT (INCLUDING - NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE, EVEN IF ANY OF SAID PARTIES HAS - BEEN WARNED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGES. - - -Brookhaven National Laboratory Notice -===================================== - -Acknowledgment of sponsorship ------------------------------ - -This software was produced by the Brookhaven National Laboratory, under -Contract DE-AC02-98CH10886 with the Department of Energy. - - -Government disclaimer of liability ----------------------------------- - -Neither the United States nor the United States Department of Energy, nor -any of their employees, makes any warranty, express or implied, or assumes -any legal liability or responsibility for the accuracy, completeness, or -usefulness of any data, apparatus, product, or process disclosed, or -represents that its use would not infringe privately owned rights. - - -Brookhaven disclaimer of liability ----------------------------------- - -Brookhaven National Laboratory makes no representations or warranties, -express or implied, nor assumes any liability for the use of this software. - - -Maintenance of notice ---------------------- - -In the interest of clarity regarding the origin and status of this -software, Brookhaven National Laboratory requests that any recipient of it -maintain this notice affixed to any distribution by the recipient that -contains a copy or derivative of this software. - - -END OF LICENSE diff --git a/LICENSE_DANSE.rst b/LICENSE_DANSE.rst deleted file mode 100644 index 1c0ab5db..00000000 --- a/LICENSE_DANSE.rst +++ /dev/null @@ -1,42 +0,0 @@ -LICENSE -======= - -This program is part of the DiffPy and DANSE open-source projects -and is available subject to the conditions and terms laid out below. - -Copyright (c) 2008-2012, The Trustees of Columbia University in the City of New York. -All rights reserved. - -Copyright (c) 2024, The Trustees of Columbia University in the City of New York. -All rights reserved. - -For more information please visit the project web-page at - - http://www.diffpy.org - -or email Prof. Simon Billinge at sb2896@columbia.edu. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -- Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -- Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index f1a78eec..00000000 --- a/MANIFEST.in +++ /dev/null @@ -1,12 +0,0 @@ -graft src -graft tests -graft requirements - -include AUTHORS.rst LICENSE*.rst README.rst - -# Exclude all bytecode files and __pycache__ directories -global-exclude *.py[cod] # Exclude all .pyc, .pyo, and .pyd files. -global-exclude .DS_Store # Exclude Mac filesystem artifacts. -global-exclude __pycache__ # Exclude Python cache directories. -global-exclude .git* # Exclude git files and directories. -global-exclude .idea # Exclude PyCharm project settings. diff --git a/README.rst b/README.rst deleted file mode 100644 index e73ac143..00000000 --- a/README.rst +++ /dev/null @@ -1,157 +0,0 @@ -|Icon| |title|_ -=============== - -.. |title| replace:: diffpy.srreal -.. _title: https://diffpy.github.io/diffpy.srreal - -.. |Icon| image:: https://avatars.githubusercontent.com/diffpy - :target: https://diffpy.github.io/diffpy.srreal - :height: 100px - -|PyPI| |Forge| |PythonVersion| |PR| - -|CI| |Codecov| |Black| |Tracking| - -.. |Black| image:: https://img.shields.io/badge/code_style-black-black - :target: https://github.com/psf/black - -.. |CI| image:: https://github.com/diffpy/diffpy.srreal/actions/workflows/matrix-and-codecov-on-merge-to-main.yml/badge.svg - :target: https://github.com/diffpy/diffpy.srreal/actions/workflows/matrix-and-codecov-on-merge-to-main.yml - -.. |Codecov| image:: https://codecov.io/gh/diffpy/diffpy.srreal/branch/main/graph/badge.svg - :target: https://codecov.io/gh/diffpy/diffpy.srreal - -.. |Forge| image:: https://img.shields.io/conda/vn/conda-forge/diffpy.srreal - :target: https://anaconda.org/conda-forge/diffpy.srreal - -.. |PR| image:: https://img.shields.io/badge/PR-Welcome-29ab47ff - -.. |PyPI| image:: https://img.shields.io/pypi/v/diffpy.srreal - :target: https://pypi.org/project/diffpy.srreal/ - -.. |PythonVersion| image:: https://img.shields.io/pypi/pyversions/diffpy.srreal - :target: https://pypi.org/project/diffpy.srreal/ - -.. |Tracking| image:: https://img.shields.io/badge/issue_tracking-github-blue - :target: https://github.com/diffpy/diffpy.srreal/issues - -Calculators for PDF, bond valence sum, and other quantities based on atom pair interaction. - -The diffpy.srreal package provides calculators for atomic pair distribution -function (PDF), bond valence sums (BVS), atom overlaps for a hard-sphere -model, bond distances and directions up to specified maximum distance. The -atomic structure models are represented with internal classes as non-periodic, -periodic or structures with space group symmetries. The package provides -implicit adapters from diffpy.structure classes or from Crystal or Molecule -objects from pyobjcryst. Adapters can be easily defined for any other -structure representations in Python allowing their direct use with the -calculators. Calculators support two evaluation models - BASIC, which -performs a full pair-summation every time, and OPTIMIZED, which updates only -pair contributions that have changed since the last evaluation. Calculations -can be split among parallel jobs using Python multiprocessing package or any -other library that provides parallel map function. PDF calculations can -be done in two modes - either as a real-space summation of peak profiles -(PDFCalculator) or as a reciprocal-space Debye summation and Fourier -transform of the total scattering structure function (DebyePDFCalculator). - -The diffpy.srreal package is a Python binding to the C++ library libdiffpy -(https://github.com/diffpy/libdiffpy). Calculators are created as -objects of a given calculator type and so multiple instances of the same -calculator type can exist with different configurations. Calculators are -composed of other objects that perform lower-level tasks, such as calculating -peak profile or looking up atom scattering factors. These objects can be -re-assigned at runtime allowing to easily customize the calculation procedure. -New classes can be defined using object inheritance either in Python or in C++ -and used with the existing calculators; as an example, this allows to -calculate PDF with a user-defined profile function. A new calculator class -can be also defined for any quantity that is obtained by iteration over atom -pairs, by defining only the function that processes atom-pair contributions. - -For more information about the diffpy.srreal library, please consult our `online documentation `_. - -Citation --------- - -If you use diffpy.srreal in a scientific publication, we would like you to cite this package as - - Juhás, P.; Farrow, C. L.; Yang, X.; Knox, K. R.; Billinge, S. J. L. Complex Modeling: A Strategy and Software Program for Combining Multiple Information Sources to Solve Ill Posed Structure and Nanostructure Inverse Problems. Acta Crystallogr A Found Adv 2015, 71 (6), 562–568. https://doi.org/10.1107/S2053273315014473. - -Installation ------------- - -The preferred method is to use `Miniconda Python -`_ -and install from the "conda-forge" channel of Conda packages. - -To add "conda-forge" to the conda channels, run the following in a terminal. :: - - conda config --add channels conda-forge - -We want to install our packages in a suitable conda environment. -The following creates and activates a new environment named ``diffpy.srreal_env`` :: - - conda create -n diffpy.srreal_env diffpy.srreal - conda activate diffpy.srreal_env - -To confirm that the installation was successful, type :: - - python -c "import diffpy.srreal; print(diffpy.srreal.__version__)" - -The output should print the latest version displayed on the badges above. - -If the above does not work, you can use ``pip`` to download and install the latest release from -`Python Package Index `_. -To install using ``pip`` into your ``diffpy.srreal_env`` environment, type :: - - pip install diffpy.srreal - -If you prefer to install from sources, after installing the dependencies, obtain the source archive from -`GitHub `_. Once installed, ``cd`` into your ``diffpy.srreal`` directory -and run the following :: - - pip install . - -Getting Started ---------------- - -You may consult our `online documentation `_ for tutorials and API references. - -Support and Contribute ----------------------- - -`Diffpy user group `_ is the discussion forum for general questions and discussions about the use of diffpy.srreal. Please join the diffpy.srreal users community by joining the Google group. The diffpy.srreal project welcomes your expertise and enthusiasm! - -If you see a bug or want to request a feature, please `report it as an issue `_ and/or `submit a fix as a PR `_. You can also post it to the `Diffpy user group `_. - -Feel free to fork the project and contribute. To install diffpy.srreal -in a development mode, with its sources being directly used by Python -rather than copied to a package directory, use the following in the root -directory :: - - pip install -e . - -To ensure code quality and to prevent accidental commits into the default branch, please set up the use of our pre-commit -hooks. - -1. Install pre-commit in your working environment by running ``conda install pre-commit``. - -2. Initialize pre-commit (one time only) ``pre-commit install``. - -Thereafter your code will be linted by black and isort and checked against flake8 before you can commit. -If it fails by black or isort, just rerun and it should pass (black and isort will modify the files so should -pass after they are modified). If the flake8 test fails please see the error messages and fix them manually before -trying to commit again. - -Improvements and fixes are always appreciated. - -Before contributing, please read our `Code of Conduct `_. - -Contact -------- - -For more information on diffpy.srreal please visit the project `web-page `_ or email Simon Billinge at sb2896@columbia.edu. - -Acknowledgements ----------------- - -``diffpy.srreal`` is built and maintained with `scikit-package `_. diff --git a/devutils/README.md b/devutils/README.md deleted file mode 100644 index 9ae092c8..00000000 --- a/devutils/README.md +++ /dev/null @@ -1 +0,0 @@ -A collection of scripts for development testing. Not meant to be user facing. diff --git a/devutils/tunePeakPrecision.py b/devutils/tunePeakPrecision.py deleted file mode 100755 index f9f0683a..00000000 --- a/devutils/tunePeakPrecision.py +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env python - -"""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 -# 15 3.2e-6 clear minimum -# 20 3.2e-6 clear minimum -# 25 0.45e-6 flat shape - -# PDF calculation parameters -qmax = 0.0 -rmin = 0.01 -rmax = 50.0 -rstep = 0.01 -peakprecision = None -createplot = False - -# make PdfFit silent -diffpy.pdffit2.redirect_stdout(open("/dev/null", "w")) - -# define nickel structure data -nickel_discus_data = """ -title Ni -spcgr P1 -cell 3.523870, 3.523870, 3.523870, 90.000000, 90.000000, 90.000000 -ncell 1, 1, 1, 4 -atoms -NI 0.00000000 0.00000000 0.00000000 0.1000 -NI 0.00000000 0.50000000 0.50000000 0.1000 -NI 0.50000000 0.00000000 0.50000000 0.1000 -NI 0.50000000 0.50000000 0.00000000 0.1000 -""" - -nickel = Structure() -nickel.readStr(nickel_discus_data, format="discus") - - -def Gpdffit2(qmax): - """Calculate reference nickel PDF using diffpy.pdffit2. - - Attributes - ---------- - qmax - vawevector cutoff value in 1/A - - Return numpy array of (r, g). - """ - # calculate reference data using pdffit2 - pf2 = diffpy.pdffit2.PdfFit() - pf2.alloc("X", qmax, 0.0, rmin, rmax, int((rmax - rmin) / rstep + 1)) - pf2.add_structure(nickel) - pf2.calc() - rg = numpy.array((pf2.getR(), pf2.getpdf_fit())) - return rg - - -def Gsrreal(qmax, peakprecision=None): - """Calculate nickel PDF using PDFCalculator from diffpy.srreal. - - Attributes - ---------- - qmax - vawevector cutoff value in 1/A - peakprecision - precision factor affecting peak cutoff, - keep at default value when None. - - Return numpy array of (r, g). - """ - pdfcalc = PDFCalculator() - pdfcalc._setDoubleAttr("qmax", qmax) - pdfcalc._setDoubleAttr("rmin", rmin) - pdfcalc._setDoubleAttr("rmax", rmax + rstep * 1e-4) - pdfcalc._setDoubleAttr("rstep", rstep) - if peakprecision is not None: - pdfcalc._setDoubleAttr("peakprecision", peakprecision) - pdfcalc.eval(nickel) - rg = numpy.array([pdfcalc.rgrid, pdfcalc.pdf]) - return rg - - -def comparePDFCalculators(qmax, peakprecision=None): - """Compare Ni PDF calculations with pdffit2 and PDFCalculator. - - Attributes - ---------- - qmax - vawevector cutoff value in 1/A - peakprecision - precision factor affecting peak cutoff, - keep at default value when None. - - Return a dictionary of benchmark results with the following keys: - - Attributes - ---------- - qmax - vawevector cutoff value - peakprecision - actual peak precision used in PDFCalculator - r - common r-grid for the PDF arrays - g0, g1 -- calculated PDF curves from pdffit2 and PDFCalculator - gdiff - PDF difference equal (g0 - g1) - grmsd - root mean square value of PDF curves difference - t0, t1 -- CPU times used by pdffit2 and PDFCalculator calls - """ - rv = {} - rv["qmax"] = qmax - rv["peakprecision"] = ( - peakprecision is None - and PDFCalculator()._getDoubleAttr("peakprecision") - or peakprecision - ) - ttic = time.clock() - rg0 = Gpdffit2(qmax) - ttoc = time.clock() - rv["r"] = rg0[0] - rv["g0"] = rg0[1] - rv["t0"] = ttoc - ttic - ttic = time.clock() - rg1 = Gsrreal(qmax, peakprecision) - ttoc = time.clock() - assert numpy.all(rv["r"] == rg1[0]) - rv["g1"] = rg1[1] - rv["t1"] = ttoc - ttic - rv["gdiff"] = rv["g0"] - rv["g1"] - rv["grmsd"] = numpy.sqrt(numpy.mean(rv["gdiff"] ** 2)) - return rv - - -def processCommandLineArguments(): - global qmax, peakprecision, createplot - argc = len(sys.argv) - if set(["-h", "--help"]).intersection(sys.argv): - print(__doc__) - sys.exit() - if argc > 1: - qmax = float(sys.argv[1]) - if argc > 2: - peakprecision = float(sys.argv[2]) - if argc > 3: - createplot = sys.argv[3].lower() in ("y", "yes", "1", "true") - return - - -def plotComparison(cmpdata): - """Plot comparison of PDF curves. - - Attributes - ---------- - cmpdata - dictionary returned from comparePDFCalculators - - No return value. - """ - import pylab - - pylab.clf() - pylab.subplot(211) - pylab.title("qmax=%(qmax)g peakprecision=%(peakprecision)g" % cmpdata) - pylab.ylabel("G") - r = cmpdata["r"] - g0 = cmpdata["g0"] - g1 = cmpdata["g1"] - gdiff = cmpdata["gdiff"] - pylab.plot(r, g0, r, g1) - pylab.subplot(212) - pylab.plot(r, gdiff, "r") - slope = numpy.sum(r * gdiff) / numpy.sum(r**2) - pylab.plot(r, slope * r, "--") - pylab.xlabel("r") - pylab.ylabel("Gdiff") - pylab.title("slope = %g" % slope) - pylab.draw() - return - - -def main(): - processCommandLineArguments() - cmpdata = comparePDFCalculators(qmax, peakprecision) - print( - ( - "qmax = %(qmax)g pkprec = %(peakprecision)g " - + "grmsd = %(grmsd)g t0 = %(t0).3f t1 = %(t1).3f" - ) - % cmpdata - ) - if createplot: - plotComparison(cmpdata) - import pylab - - pylab.show() - return - - -if __name__ == "__main__": - main() diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index 0c241efa..00000000 --- a/docs/Makefile +++ /dev/null @@ -1,194 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = build -BASENAME = $(subst .,,$(subst $() $(),,diffpy.srreal)) - -# User-friendly check for sphinx-build -ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) -$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) -endif - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/$(BASENAME).qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/$(BASENAME).qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/$(BASENAME)" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/$(BASENAME)" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -# Manual publishing to the gh-pages branch - -GITREPOPATH = $(shell cd $(CURDIR) && git rev-parse --git-dir) -GITREMOTE = origin -GITREMOTEURL = $(shell git config --get remote.$(GITREMOTE).url) -GITLASTCOMMIT = $(shell git rev-parse --short HEAD) - -publish: - @test -d build/html || \ - ( echo >&2 "Run 'make html' first!"; false ) - git show-ref --verify --quiet refs/heads/gh-pages || \ - git branch --track gh-pages $(GITREMOTE)/gh-pages - test -d build/gh-pages || \ - git clone -s -b gh-pages $(GITREPOPATH) build/gh-pages - cd build/gh-pages && \ - git pull $(GITREMOTEURL) gh-pages - rsync -acv --delete --exclude=.git --exclude=.rsync-exclude \ - --exclude-from=build/gh-pages/.rsync-exclude \ - --link-dest=$(CURDIR)/build/html build/html/ build/gh-pages/ - cd build/gh-pages && \ - git add --all . && \ - git diff --cached --quiet || \ - git commit -m "Sync with the source at $(GITLASTCOMMIT)." - cd build/gh-pages && \ - git push origin gh-pages diff --git a/docs/examples/compareC60PDFs.py b/docs/examples/compareC60PDFs.py deleted file mode 100755 index 844cd7a6..00000000 --- a/docs/examples/compareC60PDFs.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python - -"""Plot C60 PDFs calculated with PDFCalculator and DebyePDFCalculator. - -The C60 molecule is held in a diffpy Structure object. -""" - -import os -import sys - -from matplotlib.pyplot import clf, plot, show - -from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator -from diffpy.structure import Structure - -mydir = os.path.dirname(os.path.abspath(sys.argv[0])) -buckyfile = os.path.join(mydir, "datafiles", "C60bucky.stru") - -# load C60 molecule as a diffpy.structure object -bucky = Structure(filename=buckyfile) -cfg = { - "qmax": 25, - "rmin": 0, - "rmax": 10.001, -} - -# calculate PDF by real-space summation -pc0 = PDFCalculator(**cfg) -r0, g0 = pc0(bucky) - -# calculate PDF using Debye formula -pc1 = DebyePDFCalculator(**cfg) -r1, g1 = pc1(bucky) -gd = g0 - g1 - -# plot both results and the difference curve -clf() -plot(r0, g0, r1, g1, r0, gd - 1) -show() diff --git a/docs/examples/compareC60PDFs_objcryst.py b/docs/examples/compareC60PDFs_objcryst.py deleted file mode 100755 index 62e705d0..00000000 --- a/docs/examples/compareC60PDFs_objcryst.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/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 clf, plot, show -from pyobjcryst.crystal import Crystal -from pyobjcryst.molecule import Molecule -from pyobjcryst.scatteringpower import ScatteringPowerAtom - -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") - -# convert to an ObjCryst molecule -c60 = Crystal(1, 1, 1, "P1") -mc60 = Molecule(c60, "C60") -c60.AddScatterer(mc60) -# Create the scattering power object for the carbon atoms -sp = ScatteringPowerAtom("C", "C") -sp.SetBiso(bucky_diffpy[0].Bisoequiv) -for i, a in enumerate(bucky_diffpy): - cname = "C%i" % (i + 1) - mc60.AddAtom(a.xyz_cartn[0], a.xyz_cartn[1], a.xyz_cartn[2], sp, cname) - -# PDF configuration -cfg = { - "qmax": 25, - "rmin": 0, - "rmax": 10.001, - "rstep": 0.05, -} - -# calculate PDF by real-space summation -pc0 = PDFCalculator(**cfg) -r0, g0 = pc0(c60) - -# calculate PDF using Debye formula -pc1 = DebyePDFCalculator(**cfg) -r1, g1 = pc1(c60) -gd = g0 - g1 - -# plot both results and the difference curve -clf() -plot(r0, g0, r1, g1, r0, gd - 1) -show() diff --git a/docs/examples/datafiles/C60bucky.stru b/docs/examples/datafiles/C60bucky.stru deleted file mode 100644 index 7a9d9225..00000000 --- a/docs/examples/datafiles/C60bucky.stru +++ /dev/null @@ -1,65 +0,0 @@ -title Matlab generated C60 bucky ball -spcgr P1 -cell 1.000000, 1.000000, 1.000000, 90.000000, 90.000000, 90.000000 -ncell 1, 1, 1, 60 -atoms -C 1.22493716 0.00000000 3.35151135 0.25 -C 0.37852640 1.16498447 3.35151135 0.25 -C -0.99099498 0.72000000 3.35151135 0.25 -C -0.99099498 -0.72000000 3.35151135 0.25 -C 0.37852640 -1.16498447 3.35151135 0.25 -C 2.44987433 0.00000000 2.59445855 0.25 -C 2.82840073 -1.16498447 1.83740575 0.25 -C 3.44086931 -0.72000000 0.61246858 0.25 -C 3.44086931 0.72000000 0.61246858 0.25 -C 2.82840073 1.16498447 1.83740575 0.25 -C 0.75705280 2.32996894 2.59445855 0.25 -C 1.98198996 2.32996894 1.83740575 0.25 -C 1.74804778 3.04996894 0.61246858 0.25 -C 0.37852640 3.49495342 0.61246858 0.25 -C -0.23394218 3.04996894 1.83740575 0.25 -C -1.98198996 1.44000000 2.59445855 0.25 -C -1.60346356 2.60498447 1.83740575 0.25 -C -2.36051637 2.60498447 0.61246858 0.25 -C -3.20692713 1.44000000 0.61246858 0.25 -C -2.97298495 0.72000000 1.83740575 0.25 -C -1.98198996 -1.44000000 2.59445855 0.25 -C -2.97298495 -0.72000000 1.83740575 0.25 -C -3.20692713 -1.44000000 0.61246858 0.25 -C -2.36051637 -2.60498447 0.61246858 0.25 -C -1.60346356 -2.60498447 1.83740575 0.25 -C 0.75705280 -2.32996894 2.59445855 0.25 -C -0.23394218 -3.04996894 1.83740575 0.25 -C 0.37852640 -3.49495342 0.61246858 0.25 -C 1.74804778 -3.04996894 0.61246858 0.25 -C 1.98198996 -2.32996894 1.83740575 0.25 -C -1.98198996 2.32996894 -1.83740575 0.25 -C -1.74804778 3.04996894 -0.61246858 0.25 -C -0.37852640 3.49495342 -0.61246858 0.25 -C 0.23394218 3.04996894 -1.83740575 0.25 -C -0.75705280 2.32996894 -2.59445855 0.25 -C 1.60346356 2.60498447 -1.83740575 0.25 -C 2.36051637 2.60498447 -0.61246858 0.25 -C 3.20692713 1.44000000 -0.61246858 0.25 -C 2.97298495 0.72000000 -1.83740575 0.25 -C 1.98198996 1.44000000 -2.59445855 0.25 -C 2.97298495 -0.72000000 -1.83740575 0.25 -C 3.20692713 -1.44000000 -0.61246858 0.25 -C 2.36051637 -2.60498447 -0.61246858 0.25 -C 1.60346356 -2.60498447 -1.83740575 0.25 -C 1.98198996 -1.44000000 -2.59445855 0.25 -C 0.23394218 -3.04996894 -1.83740575 0.25 -C -0.37852640 -3.49495342 -0.61246858 0.25 -C -1.74804778 -3.04996894 -0.61246858 0.25 -C -1.98198996 -2.32996894 -1.83740575 0.25 -C -0.75705280 -2.32996894 -2.59445855 0.25 -C -2.82840073 -1.16498447 -1.83740575 0.25 -C -3.44086931 -0.72000000 -0.61246858 0.25 -C -3.44086931 0.72000000 -0.61246858 0.25 -C -2.82840073 1.16498447 -1.83740575 0.25 -C -2.44987433 0.00000000 -2.59445855 0.25 -C -0.37852640 1.16498447 -3.35151135 0.25 -C 0.99099498 0.72000000 -3.35151135 0.25 -C 0.99099498 -0.72000000 -3.35151135 0.25 -C -0.37852640 -1.16498447 -3.35151135 0.25 -C -1.22493716 0.00000000 -3.35151135 0.25 diff --git a/docs/examples/datafiles/menthol.cif b/docs/examples/datafiles/menthol.cif deleted file mode 100644 index 1ff0ca8b..00000000 --- a/docs/examples/datafiles/menthol.cif +++ /dev/null @@ -1,197 +0,0 @@ - -########################################################################### -# -# Cambridge Crystallographic Data Centre -# CCDC -# -########################################################################### -# -# This CIF contains data generated directly from one or more entries in -# 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 -# 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 -# 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 -# structures and to carry out CIF format checking respectively. -# -########################################################################### - -data_CSD_CIF_BAVLOZ -_audit_creation_date 1999-11-09 -_audit_creation_method CSD-ConQuest-V1 -_database_code_CSD BAVLOZ -_database_code_depnum_ccdc_archive 'CCDC 112473' -_chemical_formula_sum 'C10 H20 O1' -_chemical_formula_moiety -; -C10 H20 O1 -; -_journal_coden_Cambridge 643 -_journal_volume 214 -_journal_year 1999 -_journal_page_first 420 -_journal_name_full 'Z.Kristallogr. ' -loop_ -_publ_author_name -"R.Bombicz" -"J.Bushmann" -"P.Luger" -"Nguyen Xuan Dung" -"Chu Ba Nam" -_chemical_name_systematic -; -(1R,2S,5R)-2-Isopropyl-5-methyl-cyclohexanol -; -_chemical_name_common -; -(-)-Menthol -; -_cell_volume 2342.774 -_exptl_crystal_colour 'colorless' -_exptl_crystal_density_diffrn 0.997 -_exptl_crystal_description 'spherical' -_exptl_crystal_preparation 'sublimation' -_diffrn_ambient_temperature 143 -#These two values have been output from a single CSD field. -_refine_ls_R_factor_gt 0.0493 -_refine_ls_wR_factor_gt 0.0493 -_chemical_compound_source -; -Mentha arvensis Linner -; -loop_ -_citation_database_id_CSD -_citation_special_details -ZZZVKO "is a stereoisomer of this entry" -_symmetry_cell_setting hexagonal -_symmetry_space_group_name_H-M 'P 31' -_symmetry_Int_Tables_number 144 -loop_ -_symmetry_equiv_pos_site_id -_symmetry_equiv_pos_as_xyz -1 x,y,z -2 -y,x-y,1/3+z -3 -x+y,-x,-1/3+z -_cell_length_a 21.262(10) -_cell_length_b 21.262(10) -_cell_length_c 5.984(5) -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 120 -_cell_formula_units_Z 9 -loop_ -_atom_type_symbol -_atom_type_radius_bond -C 0.68 -H 0.23 -O 0.68 -loop_ -_atom_site_label -_atom_site_type_symbol -_atom_site_fract_x -_atom_site_fract_y -_atom_site_fract_z -O1 O 0.37146(10) 0.65092(10) 0.9395(4) -H1 H 0.3443(14) 0.6420(5) 0.808(7) -C1 C 0.38031(14) 0.58919(14) 0.9644(5) -H2 H 0.38138(14) 0.5718(7) 0.816(5) -C2 C 0.45365(14) 0.61401(14) 1.0766(5) -H3 H 0.4483(2) 0.6320(5) 1.231(4) -C3 C 0.46333(16) 0.54821(16) 1.1125(6) -H4 H 0.5104(11) 0.5641(4) 1.201(2) -H5 H 0.46270(16) 0.5285(5) 0.958(4) -C4 C 0.40047(16) 0.48765(16) 1.2387(6) -H6 H 0.4063(2) 0.4416(10) 1.2448(6) -H7 H 0.4067(2) 0.5026(3) 1.385(3) -C5 C 0.32861(15) 0.46470(14) 1.1311(6) -H8 H 0.32875(15) 0.4500(6) 0.983(6) -C6 C 0.31921(15) 0.53020(15) 1.0946(6) -H9 H 0.2670(11) 0.5201(2) 1.0326(13) -H10 H 0.31573(17) 0.5487(4) 1.250(3) -C7 C 0.51699(14) 0.67640(15) 0.9526(5) -H11 H 0.4983(6) 0.7097(10) 0.9530(5) -C8 C 0.5294(2) 0.65836(19) 0.7184(6) -H12 H 0.5427(3) 0.6226(7) 0.7176(6) -H13 H 0.4954(7) 0.6395(4) 0.6332(19) -H14 H 0.5726(9) 0.7006(8) 0.6318(19) -C9 C 0.58688(16) 0.70847(18) 1.0852(6) -H15 H 0.6033(4) 0.6810(6) 1.1258(11) -H16 H 0.58179(17) 0.7161(3) 1.243(3) -H17 H 0.6217(8) 0.7521(9) 1.0279(13) -C10 C 0.26618(18) 0.40587(17) 1.2654(8) -H18 H 0.2618(2) 0.4197(3) 1.425(3) -H19 H 0.2742(2) 0.3603(9) 1.3113(12) -H20 H 0.2199(9) 0.3936(3) 1.2146(12) -O2 O 0.61871(10) 0.33263(10) 1.7282(4) -H21 H 0.63150 0.31570 1.83440 -C11 C 0.54132(14) 0.29096(15) 1.7029(5) -H22 H 0.5188(9) 0.2770(6) 1.866(7) -C12 C 0.51694(15) 0.34008(15) 1.5954(5) -H23 H 0.5394(10) 0.3566(7) 1.452(6) -C13 C 0.43570(15) 0.29649(17) 1.5465(6) -H24 H 0.4285(3) 0.334(1) 1.454(2) -H25 H 0.4081(7) 0.2797(4) 1.676(3) -C14 C 0.41487(16) 0.22984(17) 1.4121(6) -H26 H 0.3571(13) 0.2006(7) 1.3632(13) -H27 H 0.4391(6) 0.2457(4) 1.261(3) -C15 C 0.43777(17) 0.18004(16) 1.5254(7) -H28 H 0.4155(9) 0.1730(3) 1.663(6) -C16 C 0.51935(17) 0.22355(16) 1.5667(6) -H29 H 0.5415(6) 0.1972(6) 1.6466(19) -H30 H 0.5426(6) 0.2344(3) 1.437(3) -C17 C 0.54148(18) 0.41027(17) 1.7278(5) -H31 H 0.5978(17) 0.4393(9) 1.7558(10) -C18 C 0.5068(2) 0.3969(2) 1.9590(6) -H32 H 0.5178(3) 0.4416(9) 2.0213(15) -H33 H 0.5180(3) 0.3608(8) 2.0168(14) -H34 H 0.4478(13) 0.3713(6) 1.9417(7) -C19 C 0.5299(2) 0.46466(19) 1.6000(6) -H35 H 0.5600(6) 0.5153(11) 1.6679(15) -H36 H 0.4873(9) 0.4615(2) 1.5956(7) -H37 H 0.5533(5) 0.4684(2) 1.429(4) -C20 C 0.4163(2) 0.11125(19) 1.3898(10) -H38 H 0.4343(4) 0.0733(8) 1.495(2) -H39 H 0.3666(10) 0.0970(4) 1.3422(15) -H40 H 0.4397(5) 0.1270(4) 1.229(3) -O3 O 0.95934(13) 0.01303(10) 1.0155(4) -H41 H 0.9928(19) 0.0231(6) 0.933(5) -C21 C 0.94181(14) 0.06935(15) 1.0332(5) -H42 H 0.94005(16) 0.0879(6) 0.880(5) -C22 C 0.86769(15) 0.03840(15) 1.1368(5) -H43 H 0.8718(2) 0.0201(6) 1.290(5) -C23 C 0.84879(17) 0.09790(17) 1.1709(6) -H44 H 0.8062(12) 0.0806(5) 1.256(2) -H45 H 0.84817(18) 0.1221(7) 1.031(4) -C24 C 0.90666(17) 0.16171(17) 1.3016(7) -H46 H 0.8883(5) 0.1945(8) 1.3127(8) -H47 H 0.9141(2) 0.1434(5) 1.455(4) -C25 C 0.98112(18) 0.19258(17) 1.1951(8) -H48 H 0.9836(2) 0.2127(9) 1.050(7) -C26 C 0.99937(17) 0.13232(16) 1.1660(6) -H49 H 1.0457(11) 0.1472(4) 1.077(2) -H50 H 0.99482(18) 0.1107(5) 1.336(4) -C27 C 0.80878(15) -0.02745(16) 1.0092(6) -H51 H 0.8255(6) -0.0657(13) 0.9962(7) -C28 C 0.7978(2) -0.0092(2) 0.7705(7) -H52 H 0.8510(12) 0.0059(4) 0.7203(14) -H53 H 0.7781(5) 0.0343(10) 0.8111(10) -H54 H 0.7690(7) -0.0565(11) 0.6991(18) -C29 C 0.73654(19) -0.0649(2) 1.1288(7) -H55 H 0.7011(7) -0.1084(9) 1.0480(17) -H56 H 0.7471(3) -0.0731(3) 1.292(3) -H57 H 0.7214(4) -0.0217(9) 1.1442(7) -C30 C 1.0374(2) 0.2554(2) 1.3337(11) -H58 H 1.0663(9) 0.2628(3) 1.262(3) -H59 H 1.0249(4) 0.2953(12) 1.3559(12) -H60 H 1.0457(4) 0.2370(5) 1.449(3) -#END diff --git a/docs/examples/datafiles/sphalerite.cif b/docs/examples/datafiles/sphalerite.cif deleted file mode 100644 index 99e395e4..00000000 --- a/docs/examples/datafiles/sphalerite.cif +++ /dev/null @@ -1,128 +0,0 @@ -data_9000107 -_chemical_name 'Sphalerite' -loop_ -_publ_author_name -'Skinner B J' -_journal_name_full "American Mineralogist" -_journal_volume 46 -_journal_year 1961 -_journal_page_first 1399 -_journal_page_last 1411 -_publ_section_title -; - Unit-cell edges of natural and synthetic sphalerites -; -_chemical_formula_sum 'Zn S' -_cell_length_a 5.4093 -_cell_length_b 5.4093 -_cell_length_c 5.4093 -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 90 -_cell_volume 158.279 -_symmetry_space_group_name_H-M 'F -4 3 m' -loop_ -_symmetry_equiv_pos_as_xyz - 'x,y,z' - 'x,1/2+y,1/2+z' - '1/2+x,y,1/2+z' - '1/2+x,1/2+y,z' - '-z,x,-y' - '-z,1/2+x,1/2-y' - '1/2-z,x,1/2-y' - '1/2-z,1/2+x,-y' - '-y,z,-x' - '-y,1/2+z,1/2-x' - '1/2-y,z,1/2-x' - '1/2-y,1/2+z,-x' - '-x,y,-z' - '-x,1/2+y,1/2-z' - '1/2-x,y,1/2-z' - '1/2-x,1/2+y,-z' - 'x,-z,-y' - 'x,1/2-z,1/2-y' - '1/2+x,-z,1/2-y' - '1/2+x,1/2-z,-y' - 'z,-y,-x' - 'z,1/2-y,1/2-x' - '1/2+z,-y,1/2-x' - '1/2+z,1/2-y,-x' - 'y,-x,-z' - 'y,1/2-x,1/2-z' - '1/2+y,-x,1/2-z' - '1/2+y,1/2-x,-z' - 'x,z,y' - 'x,1/2+z,1/2+y' - '1/2+x,z,1/2+y' - '1/2+x,1/2+z,y' - 'z,y,x' - 'z,1/2+y,1/2+x' - '1/2+z,y,1/2+x' - '1/2+z,1/2+y,x' - 'y,x,z' - 'y,1/2+x,1/2+z' - '1/2+y,x,1/2+z' - '1/2+y,1/2+x,z' - '-z,-x,y' - '-z,1/2-x,1/2+y' - '1/2-z,-x,1/2+y' - '1/2-z,1/2-x,y' - '-y,-z,x' - '-y,1/2-z,1/2+x' - '1/2-y,-z,1/2+x' - '1/2-y,1/2-z,x' - '-x,-y,z' - '-x,1/2-y,1/2+z' - '1/2-x,-y,1/2+z' - '1/2-x,1/2-y,z' - 'z,-x,-y' - 'z,1/2-x,1/2-y' - '1/2+z,-x,1/2-y' - '1/2+z,1/2-x,-y' - 'y,-z,-x' - 'y,1/2-z,1/2-x' - '1/2+y,-z,1/2-x' - '1/2+y,1/2-z,-x' - 'x,-y,-z' - 'x,1/2-y,1/2-z' - '1/2+x,-y,1/2-z' - '1/2+x,1/2-y,-z' - '-x,z,-y' - '-x,1/2+z,1/2-y' - '1/2-x,z,1/2-y' - '1/2-x,1/2+z,-y' - '-z,y,-x' - '-z,1/2+y,1/2-x' - '1/2-z,y,1/2-x' - '1/2-z,1/2+y,-x' - '-y,x,-z' - '-y,1/2+x,1/2-z' - '1/2-y,x,1/2-z' - '1/2-y,1/2+x,-z' - '-x,-z,y' - '-x,1/2-z,1/2+y' - '1/2-x,-z,1/2+y' - '1/2-x,1/2-z,y' - '-z,-y,x' - '-z,1/2-y,1/2+x' - '1/2-z,-y,1/2+x' - '1/2-z,1/2-y,x' - '-y,-x,z' - '-y,1/2-x,1/2+z' - '1/2-y,-x,1/2+z' - '1/2-y,1/2-x,z' - 'z,x,y' - 'z,1/2+x,1/2+y' - '1/2+z,x,1/2+y' - '1/2+z,1/2+x,y' - 'y,z,x' - 'y,1/2+z,1/2+x' - '1/2+y,z,1/2+x' - '1/2+y,1/2+z,x' -loop_ -_atom_site_label -_atom_site_fract_x -_atom_site_fract_y -_atom_site_fract_z -Zn 0.00000 0.00000 0.00000 -S 0.25000 0.25000 0.25000 diff --git a/docs/examples/distanceprinter.py b/docs/examples/distanceprinter.py deleted file mode 100755 index 356f1123..00000000 --- a/docs/examples/distanceprinter.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python - -"""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.""" - - def _resetValue(self): - self.count = 0 - - def _addPairContribution(self, bnds, sumscale): - self.count += bnds.multiplicity() * sumscale / 2.0 - print( - "%i %g %i %i" - % (self.count, bnds.distance(), bnds.site0(), bnds.site1()) - ) - return - - -# class DistancePrinter - -# define nickel structure data -nickel_discus_data = """ -title Ni -spcgr P1 -cell 3.523870, 3.523870, 3.523870, 90.000000, 90.000000, 90.000000 -ncell 1, 1, 1, 4 -atoms -NI 0.00000000 0.00000000 0.00000000 0.1000 -NI 0.00000000 0.50000000 0.50000000 0.1000 -NI 0.50000000 0.00000000 0.50000000 0.1000 -NI 0.50000000 0.50000000 0.00000000 0.1000 -""" - -nickel = Structure() -nickel.readStr(nickel_discus_data, format="discus") - -bucky = Structure(filename="datafiles/C60bucky.stru", format="discus") -distprint = DistancePrinter() -distprint._setDoubleAttr("rmax", 10) - - -def get_pyobjcryst_sphalerite(): - from pyobjcryst.crystal import create_crystal_from_cif - - crst = create_crystal_from_cif("datafiles/sphalerite.cif") - return crst - - -def main(): - s = input("Enter rmin: ") - if s.strip(): - distprint.rmin = float(s) - print("rmin = %g" % distprint.rmin) - s = input("Enter rmax: ") - if s.strip(): - distprint.rmax = float(s) - print("rmax = %g" % distprint.rmax) - print() - linesep = 78 * "-" - # C60bucky - print(linesep) - input("Press enter for distances in C60 molecule.") - distprint.eval(bucky) - # nickel - print(linesep) - input("Press enter for distances in a nickel crystal.") - distprint.eval(nickel) - # objcryst sphalerite - print(linesep) - input("Press enter for distances in objcryst loaded sphalerite.cif.") - crst = get_pyobjcryst_sphalerite() - distprint.eval(crst) - print(linesep) - input("Press enter for distances in diffpy.structure sphalerite.cif.") - crst = Structure(filename="datafiles/sphalerite.cif") - distprint.eval(crst) - return - - -if __name__ == "__main__": - main() diff --git a/docs/examples/lennardjones/Makefile b/docs/examples/lennardjones/Makefile deleted file mode 100644 index e5fd4057..00000000 --- a/docs/examples/lennardjones/Makefile +++ /dev/null @@ -1,6 +0,0 @@ -LDLIBS = -ldiffpy - -ljcalculator : ljcalculator.cpp - -clean: - rm -f ljcalculator diff --git a/docs/examples/lennardjones/README.txt b/docs/examples/lennardjones/README.txt deleted file mode 100644 index d0f35f2e..00000000 --- a/docs/examples/lennardjones/README.txt +++ /dev/null @@ -1,11 +0,0 @@ -This example shows how to use the PairQuantity base class to create -a calculator Lennard-Jones (LJ) potential. The LJ calculator is -defined by inheriting from the PairQuantity base class and overloading -its addPairContribution method. This can be done at both the Python -and C++ levels as shown by example files. - -ljcalculator.py -- definition of LJ calculator in Python -ljcalculator.cpp -- definition of LJ calculator in C++. Use "make" to compile. -lj50.xyz -- 50-atom structure with minimum LJ potential - -Ref: http://www-wales.ch.cam.ac.uk/~jon/structures/LJ/tables.150.html diff --git a/docs/examples/lennardjones/lj50.xyz b/docs/examples/lennardjones/lj50.xyz deleted file mode 100644 index 830390d8..00000000 --- a/docs/examples/lennardjones/lj50.xyz +++ /dev/null @@ -1,50 +0,0 @@ - -1.3808175201 1.4634869133 -0.1706674149 - 1.3411851830 1.3093016470 -1.1374800579 - -0.0065162676 0.4212925565 2.1515991923 - -1.9763535646 -0.2141737563 -0.8676353832 - 1.8590365149 0.5113502208 0.8997988169 - -0.0955937784 -0.1300118685 -2.1002793074 - -1.4337062656 -1.0117038491 1.1653995920 - 1.5920765242 -0.8886453122 -0.8332970864 - 0.7693137385 -1.4307692500 1.1746649755 - -0.4364301991 -1.8213530422 -0.6705695416 - 0.1702912130 1.2896012443 1.4591364811 - 0.8579602018 1.7427103037 -0.2191251117 - -0.8714202568 0.8070485621 1.5477706947 - 0.2427509753 1.5411834638 -1.1713752046 - -1.4499097613 0.7620601467 -1.0358092905 - -1.8775327946 0.4802962931 0.0078095589 - 1.1025675279 1.3384685272 0.8131467496 - -0.4936238601 0.8146981818 -1.6450507034 - -1.5918138779 0.0910928984 1.0350941350 - 1.6121844699 0.9160849963 -0.1175217301 - 0.9349103091 0.4698250317 1.5353724703 - 0.6256144804 0.5921681149 -1.6313351128 - -0.7267316110 -0.2989020783 1.6690804222 - -1.0414338739 -0.1741721861 -1.4953862474 - -1.7161900474 -0.6187739658 0.1513639391 - 1.4724859879 0.2113896368 -0.9893172021 - 0.3828853545 -0.5065553448 1.6698650412 - -1.2109310364 -1.0204202765 -0.7716797232 - -0.9396087196 -1.4247350862 0.2483786523 - -0.2672239364 -0.9816958516 -1.3925843338 - 1.3214998964 -0.4629116005 1.0428857879 - 1.7352042611 -0.1903191519 0.0332356891 - -0.3335726554 -1.2281785309 1.1764068601 - 0.7526855445 -0.5124353647 -1.4746188257 - 1.1877652581 -1.1656602954 0.1719737062 - 0.5809005092 -1.3628076832 -0.7566434391 - 0.1669678838 -1.6355507790 0.2535640330 - 0.1076585966 1.1860492665 0.3643310390 - -0.4766892594 0.9805946704 -0.5619499483 - -0.8936915860 0.7058289229 0.4557489028 - -0.0712678990 0.1918164539 0.0225859320 - -0.0388438733 0.3017030383 1.0646190329 - 0.6210158850 0.7364889064 -0.5457753906 - -1.0040138099 -0.0048995195 -0.4127176530 - 0.8757807709 0.3452642543 0.4520683327 - -0.0821281481 0.0308613809 -1.0186234008 - -0.7381728362 -0.4014111524 0.5824611222 - 0.7457776892 -0.3444280877 -0.3973258674 - 0.3429471378 -0.6098558508 0.5857866160 - -0.2472484749 -0.8002957486 -0.3173797990 diff --git a/docs/examples/lennardjones/ljcalculator.cpp b/docs/examples/lennardjones/ljcalculator.cpp deleted file mode 100644 index 669d37b4..00000000 --- a/docs/examples/lennardjones/ljcalculator.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include -#include -#include -#include -#include - -using namespace diffpy::srreal; -using namespace std; - -class LennardJonesCalculator : public PairQuantity -{ - public: - // Constructor - the size of the results array is always one, - // because LJ potential is a scalar - LennardJonesCalculator() - { - this->resizeValue(1); - } - - // convenience template method. This allows using an instantiated - // LennardJonesCalculator as a function. T must be a type for which - // a createStructureAdapter(const T&) function exists. - template - double operator()(const T& stru) - { - this->eval(stru); - return this->value()[0]; - } - - protected: - - // define contribution from a pair of atoms. mvalue is a reference - // to the internal array of result values. - void addPairContribution(const BaseBondGenerator& bnds, int sumscale) - { - double rij = bnds.distance(); - double ljij = 4 * (pow(rij, -12) - pow(rij, -6)); - mvalue[0] += sumscale * ljij / 2.0; - } - -}; - - -// helper function that loads a simple list of xyz coordinates -VR3Structure loadVR3Structure(string filename) -{ - VR3Structure rv; - ifstream fp(filename.c_str()); - double x, y, z; - while (fp >> x >> y >> z) - { - rv.push_back(R3::Vector(x, y, z)); - } - return rv; -} - - -int main(int argc, char* argv[]) -{ - using namespace std; - string filename; - filename = (argc > 1) ? argv[1] : "lj50.xyz"; - LennardJonesCalculator ljcalc; - VR3Structure stru = loadVR3Structure(filename); - cout << "LJ potential of " << filename << " is " << ljcalc(stru) << '\n'; - return 0; -} diff --git a/docs/examples/lennardjones/ljcalculator.py b/docs/examples/lennardjones/ljcalculator.py deleted file mode 100755 index 4e1e1511..00000000 --- a/docs/examples/lennardjones/ljcalculator.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python - -"""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 - - -class LennardJonesCalculator(PairQuantity): - - # Initialization. The size of the result array is always 1. - def __init__(self): - PairQuantity.__init__(self) - self._resizeValue(1) - return - - def __call__(self, structure): - """Return LJ potential for a specified structure.""" - values = self.eval(structure) - return values[0] - - def _addPairContribution(self, bnds, sumscale): - """Add Lennard-Jones contribution from a single pair of atoms. - - bnds -- a BaseBondGenerator instance that contains information - about the current pair of atom sites. - sumscale -- integer multiplicity of the current pair. It may - be negative in case of fast value updates. - - No return value. Updates _value, the internal results array. - """ - rij = bnds.distance() - ljij = 4 * (rij**-12 - rij**-6) - self._value[0] += sumscale * ljij / 2.0 - return - - -# class LennardJonesCalculator - - -def main(): - # load structure from a specified file, by default "lj50.xyz" - filename = len(sys.argv) > 1 and sys.argv[1] or "lj50.xyz" - stru = Structure() - stru.read(filename) - # create an instance of LennardJonesCalculator - ljcalc = LennardJonesCalculator() - # calculate and print the LJ potential. - print("LJ potential of %s is %g" % (filename, ljcalc(stru))) - - -if __name__ == "__main__": - main() diff --git a/docs/examples/parallelPDF.py b/docs/examples/parallelPDF.py deleted file mode 100755 index 3fdd1a1b..00000000 --- a/docs/examples/parallelPDF.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/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. -""" - -import multiprocessing -import optparse -import os -import sys -import time - -from matplotlib.pyplot import clf, plot, show - -from diffpy.srreal.parallel import createParallelCalculator -from diffpy.srreal.pdfcalculator import PDFCalculator -from diffpy.structure import Structure - - -# load menthol structure and make sure Uiso values are non-zero -def load_structure(opts, mentholcif, Uisodefault): - if opts.pyobjcryst: - # use pyobjcryst if requested by the user - from numpy import pi - from pyobjcryst.crystal import create_crystal_from_cif - - menthol = create_crystal_from_cif(mentholcif) - for sc in menthol.GetScatteringComponentList(): - sp = sc.mpScattPow - sp.Biso = sp.Biso or 8 * pi**2 * Uisodefault - else: - # or use diffpy.structure by default - menthol = Structure(filename=mentholcif) - for a in menthol: - a.Uisoequiv = a.Uisoequiv or Uisodefault - return menthol - - -def calculate_pdf(menthol, cfg, ncpu): - # calculate PDF on a single core - t0 = time.time() - pc0 = PDFCalculator(**cfg) - r0, g0 = pc0(menthol) - t0 = time.time() - t0 - print(f"Calculation time on 1 CPU: {t0:g}") - - # create a pool of workers - pool = multiprocessing.Pool(processes=ncpu) - - t1 = time.time() - # 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) - t1 = time.time() - t1 - pool.close() - pool.join() - - print(f"Calculation time on {ncpu} CPUs: {t1:g}") - print(f"Time ratio: {t0 / t1:g}") - - # plot both results and the difference curve - - clf() - gd = g0 - g1 - plot(r0, g0, label="1 CPU") - plot(r1, g1, label=f"{ncpu} CPUs") - plot(r0, gd - 3, label="Difference − 3") - show() - - -def main(): - mydir = os.path.dirname(os.path.abspath(__file__)) - mentholcif = os.path.join(mydir, "datafiles", "menthol.cif") - Uisodefault = 0.005 - - # configure options parsing - parser = optparse.OptionParser("%prog [options]\n" + __doc__) - parser.add_option( - "--pyobjcryst", - action="store_true", - help="Use pyobjcryst to load the CIF file.", - ) - parser.allow_interspersed_args = True - opts, args = parser.parse_args(sys.argv[1:]) - - # load the structure - menthol = load_structure(opts, mentholcif, Uisodefault) - - # configuration of a PDF calculator - cfg = {"qmax": 25, "rmin": 0, "rmax": 30} - - # number of CPUs for parallel calculation - ncpu = multiprocessing.cpu_count() - calculate_pdf(menthol, cfg, ncpu) - - -if __name__ == "__main__": - multiprocessing.freeze_support() - main() diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index ac53d5bd..00000000 --- a/docs/make.bat +++ /dev/null @@ -1,36 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=source -set BUILDDIR=build -set SPHINXPROJ=PackagingScientificPython - -if "%1" == "" goto help - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% - -:end -popd diff --git a/docs/source/_static/.placeholder b/docs/source/_static/.placeholder deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/source/api/diffpy.srreal.rst b/docs/source/api/diffpy.srreal.rst deleted file mode 100644 index 82b25287..00000000 --- a/docs/source/api/diffpy.srreal.rst +++ /dev/null @@ -1,151 +0,0 @@ -:tocdepth: -1 - -|title| -======= - -.. |title| replace:: diffpy.srreal package - -.. automodule:: diffpy.srreal - :members: - :undoc-members: - :show-inheritance: - -Submodules ----------- - -diffpy.srreal.atomradiitable module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.atomradiitable - :members: - :undoc-members: - :show-inheritance: - - -diffpy.srreal.attributes module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.attributes - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.bondcalculator module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.bondcalculator - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.bvparameterstable module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.bvparameterstable - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.bvscalculator module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.bvscalculator - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.eventticker module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.eventticker - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.overlapcalculator module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.overlapcalculator - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.overlapcalculator module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.overlapcalculator - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.pairquantity module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.pairquantity - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.parallel module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.parallel - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.pdfbaseline module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.pdfbaseline - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.pdfcalculator module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.pdfcalculator - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.pdfenvelope module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.pdfenvelope - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.peakprofile module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.peakprofile - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.peakwidthmodel module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.peakwidthmodel - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.scatteringfactortable module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.scatteringfactortable - :members: - :undoc-members: - :show-inheritance: - -diffpy.srreal.sfaverage module -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. automodule:: diffpy.srreal.sfaverage - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 6ac5e09e..00000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,325 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# diffpy.srreal documentation build configuration file, created by -# sphinx-quickstart on Thu Jan 30 15:49:41 2014. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import time -from importlib.metadata import version -from pathlib import Path - -# Attempt to import the version dynamically from GitHub tag. -try: - fullversion = version("diffpy.srreal") -except Exception: - fullversion = "No version found. The correct version will appear in the released version." # noqa: E501 - -# 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 Path().resolve() to make it absolute, like shown here. -# sys.path.insert(0, str(Path(".").resolve())) -sys.path.insert(0, str(Path("../..").resolve())) -sys.path.insert(0, str(Path("../../src").resolve())) - -# abbreviations -ab_authors = "Pavol Juhás, Christopher L. Farrow, Simon J.L. Billinge group" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "sphinx.ext.intersphinx", - "sphinx_rtd_theme", - "sphinx_copybutton", - "m2r", -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = "diffpy.srreal" -copyright = "%Y, The Trustees of Columbia University in the City of New York" - -# 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. - -# The short X.Y version. -version = "".join(fullversion.split(".post")[:1]) -# The full version, including alpha/beta/rc tags. -release = fullversion - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -today = time.strftime("%B %d, %Y", time.localtime()) -year = today.split()[-1] -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' -# substitute YEAR in the copyright string -copyright = copyright.replace("%Y", year) - -# For sphinx_copybutton extension. -# Do not copy "$" for shell commands in code-blocks. -copybutton_prompt_text = r"^\$ " -copybutton_prompt_is_regexp = True - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -modindex_common_prefix = ["diffpy.srreal"] - -# Display all warnings for missing links. -nitpicky = True - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = "sphinx_rtd_theme" - -html_context = { - "display_github": True, - "github_user": "diffpy", - "github_repo": "diffpy.srreal", - "github_version": "main", - "conf_py_path": "/docs/source/", -} - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -html_theme_options = { - "navigation_with_keys": "true", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -# html_static_path = ['_static'] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Output file base name for HTML help builder. -basename = "diffpy.srreal".replace(" ", "").replace(".", "") -htmlhelp_basename = basename + "doc" - - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - "index", - "diffpy.srreal.tex", - "diffpy.srreal Documentation", - ab_authors, - "manual", - ), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - "index", - "diffpy.srreal", - "diffpy.srreal Documentation", - ab_authors, - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - "index", - "diffpy.srreal", - "diffpy.srreal Documentation", - ab_authors, - "diffpy.srreal", - "One line description of project.", - "Miscellaneous", - ), -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "numpy": ("https://numpy.org/doc/stable/", None), - "python": ("https://docs.python.org/3", None), -} diff --git a/docs/source/examples.rst b/docs/source/examples.rst deleted file mode 100644 index 79bf30aa..00000000 --- a/docs/source/examples.rst +++ /dev/null @@ -1,22 +0,0 @@ -.. _developers-guide-examples: - -=================== -Examples -=================== - -.. This creates the links from the filenames within README to pages. -.. _compareC60PDFs_objcryst.py: examples/compareC60PDFs_objcryst.html -.. _compareC60PDFs.py: examples/compareC60PDFs.html -.. _distanceprinter.py: examples/distanceprinter.html -.. _parallelPDF.py: examples/parallelPDF.html - - -Files ------ - -.. toctree:: - - examples/compareC60PDFs_objcryst.rst - examples/compareC60PDFs.rst - examples/distanceprinter.rst - examples/parallelPDF.rst diff --git a/docs/source/examples/compareC60PDFs.rst b/docs/source/examples/compareC60PDFs.rst deleted file mode 100644 index 625002c9..00000000 --- a/docs/source/examples/compareC60PDFs.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _compareC60PDFs.rst: - -========================== -compareC60PDFs.py -========================== - -.. literalinclude:: ../../examples/compareC60PDFs.py diff --git a/docs/source/examples/compareC60PDFs_objcryst.rst b/docs/source/examples/compareC60PDFs_objcryst.rst deleted file mode 100644 index 44cbf6e8..00000000 --- a/docs/source/examples/compareC60PDFs_objcryst.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _compareC60PDFs_objcryst.py: - -========================== -compareC60PDFs_ObjCryst.py -========================== - -.. literalinclude:: ../../examples/compareC60PDFs_objcryst.py diff --git a/docs/source/examples/distanceprinter.rst b/docs/source/examples/distanceprinter.rst deleted file mode 100644 index 04883d1b..00000000 --- a/docs/source/examples/distanceprinter.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _distanceprinter.py: - -=========================== -distanceprinter.py -=========================== - -.. literalinclude:: ../../examples/distanceprinter.py diff --git a/docs/source/examples/parallelPDF.rst b/docs/source/examples/parallelPDF.rst deleted file mode 100644 index 2263fbe0..00000000 --- a/docs/source/examples/parallelPDF.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _parallelPDF.py: - -=========================== -parallelPDF.py -=========================== - -.. literalinclude:: ../../examples/parallelPDF.py diff --git a/docs/source/index.rst b/docs/source/index.rst deleted file mode 100644 index 71cc54f9..00000000 --- a/docs/source/index.rst +++ /dev/null @@ -1,91 +0,0 @@ -####### -|title| -####### - -.. |title| replace:: diffpy.srreal documentation - -``diffpy.srreal`` - Calculators for PDF, bond valence sum, and other quantities based on atom pair interaction. - -| Software version |release| -| Last updated |today|. - -The diffpy.srreal package provides calculators for atomic pair distribution -function (PDF), bond valence sums (BVS), atom overlaps for a hard-sphere -model, bond distances and directions up to specified maximum distance. The -atomic structure models are represented with internal classes as non-periodic, -periodic or structures with space group symmetries. The package provides -implicit adapters from diffpy.structure classes or from Crystal or Molecule -objects from pyobjcryst. Adapters can be easily defined for any other -structure representations in Python allowing their direct use with the -calculators. Calculators support two evaluation models - BASIC, which -performs a full pair-summation every time, and OPTIMIZED, which updates only -pair contributions that have changed since the last evaluation. Calculations -can be split among parallel jobs using Python multiprocessing package or any -other library that provides parallel map function. PDF calculations can -be done in two modes - either as a real-space summation of peak profiles -(PDFCalculator) or as a reciprocal-space Debye summation and Fourier -transform of the total scattering structure function (DebyePDFCalculator). - -The diffpy.srreal package is a Python binding to the C++ library libdiffpy -(https://github.com/diffpy/libdiffpy). Calculators are created as -objects of a given calculator type and so multiple instances of the same -calculator type can exist with different configurations. Calculators are -composed of other objects that perform lower-level tasks, such as calculating -peak profile or looking up atom scattering factors. These objects can be -re-assigned at runtime allowing to easily customize the calculation procedure. -New classes can be defined using object inheritance either in Python or in C++ -and used with the existing calculators; as an example, this allows to -calculate PDF with a user-defined profile function. A new calculator class -can be also defined for any quantity that is obtained by iteration over atom -pairs, by defining only the function that processes atom-pair contributions. - -======= -Authors -======= - -diffpy.srreal is developed by members of the Billinge Group at -Columbia University and at Brookhaven National Laboratory including -Pavol Juhás, Christopher L. Farrow, Simon J.L. Billinge. - -For a detailed list of contributors see -https://github.com/diffpy/diffpy.srreal/graphs/contributors. - -Reference -========= - -If you use this program for a scientific research that leads -to publication, we ask that you acknowledge use of the program -by citing the following paper in your publication: - - Juhás, P.; Farrow, C. L.; Yang, X.; Knox, K. R.; Billinge, S. J. L. Complex Modeling: A Strategy and Software Program for Combining Multiple Information Sources to Solve Ill Posed Structure and Nanostructure Inverse Problems. Acta Crystallogr A Found Adv 2015, 71 (6), 562–568. https://doi.org/10.1107/S2053273315014473. - -============ -Installation -============ - -See the `README `_ -file included with the distribution. - -================ -Acknowledgements -================ - -``diffpy.srreal`` is built and maintained with `scikit-package `_. - -================= -Table of contents -================= -.. toctree:: - :titlesonly: - - license - release - examples - Package API - -======= -Indices -======= - -* :ref:`genindex` -* :ref:`search` diff --git a/docs/source/license.rst b/docs/source/license.rst deleted file mode 100644 index 03c1eae0..00000000 --- a/docs/source/license.rst +++ /dev/null @@ -1,149 +0,0 @@ -:tocdepth: -1 - -.. index:: license - -License -####### - -OPEN SOURCE LICENSE AGREEMENT -============================= - -Copyright (c) 2009-2011, University of Tennessee - -Copyright (c) 1989, 1991 Free Software Foundation, Inc. - -Copyright (c) 2006, The Regents of the University of California through Lawrence Berkeley National Laboratory - -Copyright (c) 2014, Australian Synchrotron Research Program Inc., ("ASRP") - -Copyright (c) 2006-2007, Board of Trustees of Michigan State University - -Copyright (c) 2008-2012, The Trustees of Columbia University in the City of New York - -Copyright (c) 2014-2019, Brookhaven Science Associates, Brookhaven National Laboratory - -Copyright (c) 2025, The Trustees of Columbia University in the City of New York. -All rights reserved. - -The "DiffPy-CMI" is distributed subject to the following license conditions: - -.. code-block:: text - - SOFTWARE LICENSE AGREEMENT - - Software: DiffPy-CMI - - - (1) The "Software", below, refers to the aforementioned DiffPy-CMI (in either - source code, or binary form and accompanying documentation). - - Part of the software was derived from the DANSE, ObjCryst++ (with permission), - PyCifRW, Python periodictable, CCTBX, and SasView open source projects, of - which the original Copyrights are contained in each individual file. - - Each licensee is addressed as "you" or "Licensee." - - - (2) The copyright holders shown above and their third-party Licensors hereby - grant licensee a royalty-free nonexclusive license, subject to the limitations - stated herein and U.S. Government license rights. - - - (3) You may modify and make a copy or copies of the software for use within - your organization, if you meet the following conditions: - - (a) Copies in source code must include the copyright notice and this - software license agreement. - - (b) Copies in binary form must include the copyright notice and this - Software License Agreement in the documentation and/or other materials - provided with the copy. - - - (4) You may modify a copy or copies of the Software or any portion of it, thus - forming a work based on the Software, and distribute copies of such work - outside your organization, if you meet all of the following conditions: - - (a) Copies in source code must include the copyright notice and this - Software License Agreement; - - (b) Copies in binary form must include the copyright notice and this - Software License Agreement in the documentation and/or other materials - provided with the copy; - - (c) Modified copies and works based on the Software must carry prominent - notices stating that you changed specified portions of the Software. - - (d) Neither the name of Brookhaven Science Associates or Brookhaven - National Laboratory nor the names of its contributors may be used to - endorse or promote products derived from this software without specific - written permission. - - - (5) Portions of the Software resulted from work developed under a U.S. - Government contract and are subject to the following license: - The Government is granted for itself and others acting on its behalf a - paid-up, nonexclusive, irrevocable worldwide license in this computer software - to reproduce, prepare derivative works, and perform publicly and display - publicly. - - - (6) WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT - WARRANTY OF ANY KIND. THE COPYRIGHT HOLDERS, THEIR THIRD PARTY - LICENSORS, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND - THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR IMPLIED, INCLUDING - BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - PARTICULAR PURPOSE, TITLE OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL - LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR USEFULNESS OF - THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF THE SOFTWARE WOULD NOT INFRINGE - PRIVATELY OWNED RIGHTS, (4) DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION - UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL BE CORRECTED. - - - (7) LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT HOLDERS, THEIR - THIRD PARTY LICENSORS, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF - ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, INCIDENTAL, - CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF ANY KIND OR NATURE, INCLUDING - BUT NOT LIMITED TO LOSS OF PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, - WHETHER SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT (INCLUDING - NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE, EVEN IF ANY OF SAID PARTIES HAS - BEEN WARNED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGES. - - -Brookhaven National Laboratory Notice -===================================== - -Acknowledgment of sponsorship ------------------------------ - -This software was produced by the Brookhaven National Laboratory, under -Contract DE-AC02-98CH10886 with the Department of Energy. - - -Government disclaimer of liability ----------------------------------- - -Neither the United States nor the United States Department of Energy, nor -any of their employees, makes any warranty, express or implied, or assumes -any legal liability or responsibility for the accuracy, completeness, or -usefulness of any data, apparatus, product, or process disclosed, or -represents that its use would not infringe privately owned rights. - - -Brookhaven disclaimer of liability ----------------------------------- - -Brookhaven National Laboratory makes no representations or warranties, -express or implied, nor assumes any liability for the use of this software. - - -Maintenance of notice ---------------------- - -In the interest of clarity regarding the origin and status of this -software, Brookhaven National Laboratory requests that any recipient of it -maintain this notice affixed to any distribution by the recipient that -contains a copy or derivative of this software. - - -END OF LICENSE diff --git a/docs/source/release.rst b/docs/source/release.rst deleted file mode 100644 index 27cd0cc9..00000000 --- a/docs/source/release.rst +++ /dev/null @@ -1,5 +0,0 @@ -:tocdepth: -1 - -.. index:: release notes - -.. include:: ../../CHANGELOG.rst diff --git a/libsrreal/Makefile b/libsrreal/Makefile new file mode 100644 index 00000000..a91b718e --- /dev/null +++ b/libsrreal/Makefile @@ -0,0 +1,72 @@ +# User variables - can be set as environment variables or as make arguments +# +# DEBUG debugging flags (-gstabs+), turns off optimizations + +# Objcryst headers +ifndef OBJCRYST_HEADERS +OBJCRYST_HEADERS=/home/chris/local/src/ObjCryst/ObjCryst +endif + +# CFLAGS +ifdef DEBUG +CFLAGS = $(DEBUG) +else +CFLAGS = -fPIC -O3 -ffast-math -funroll-loops -Wall +endif + +# Shared libary for so files +ifndef LIB +LIB = /home/chris/local/lib/ +endif + +# Shared library for python files +ifndef PYLIB +PYLIB = . +endif + +# Location of included header files +INCDIR = . + +# end of setup + +OBJ = pdfcalculator.o profilecalculator.o bondwidthcalculator.o bonditerator.o PointsInSphere.o +SOBJ = libsrreal.so + +CC = g++ +LINK = g++ +LINKFLAGS = -L$(LIB) -Wl,-O1 + + +# Where to search for dependencies +VPATH = $(LIB):$(INCDIR) + +.PHONY : install +install: lib + cp $(SOBJ) $(LIB) + +.PHONY : lib +lib: $(SOBJ) + +# Make the profile library +# The objcryst libraries are included in the srreal library +$(SOBJ):$(OBJ) + $(LINK) -shared $(LINKFLAGS) -o $(SOBJ) $(OBJ) -lobjcryst -lgsl -lgslcblas -lm + +# rules for compiling libraries +%.o:%.cpp + $(CC) $(CFLAGS) -c $< -I$(INCDIR) -I$(OBJCRYST_HEADERS) + +# tests + +TESTS = testsrreal + +.PHONY : test +test: $(TESTS) + +testsrreal: $(SOBJ) testsrreal.o + make install + $(LINK) $(CFLAGS) $(LINKFLAGS) -o $@ $^ -lsrreal +.PHONY : clean +clean: + -rm -f *.so *.o $(TESTS) + diff --git a/libsrreal/PointsInSphere.cpp b/libsrreal/PointsInSphere.cpp new file mode 100644 index 00000000..123bf2e1 --- /dev/null +++ b/libsrreal/PointsInSphere.cpp @@ -0,0 +1,245 @@ +/*********************************************************************** +* +* pdffit2 by DANSE Diffraction group +* Simon J. L. Billinge +* (c) 2006 trustees of the Michigan State University +* All rights reserved. +* +* File coded by: Pavol Juhas +* +* See AUTHORS.txt for a list of people who contributed. +* See LICENSE.txt for license information. +* +************************************************************************ +* +* classes PointsInSphere, ReflectionsInQminQmax, ReflectionsInDmaxDmin +* +* Comments: sequencers for lattice points insided 3D sphere +* +* $Id$ +* +***********************************************************************/ + +#include +#include "PointsInSphere.h" + +using namespace NS_POINTSINSPHERE; + +//////////////////////////////////////////////////////////////////////// +// LatticeParameters +//////////////////////////////////////////////////////////////////////// + +LatticeParameters::LatticeParameters( double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ) : + a(_a), b(_b), c(_c), + alpha(_alpha), beta(_beta), gamma(_gamma) +{ + update(); +} + +LatticeParameters& LatticeParameters::update() +{ + ca = cosd(alpha); cb = cosd(beta); cg = cosd(gamma); + sa = sind(alpha); sb = sind(beta); sg = sind(gamma); + // Vunit is a volume of unit cell with a=b=c=1 + const double Vunit = sqrt(1.0 + 2.0*ca*cb*cg - ca*ca - cb*cb - cg*cg); + ar = sa/(a*Vunit); + br = sb/(b*Vunit); + cr = sg/(c*Vunit); + car = (cb*cg - ca)/(sb*sg); sar = sqrt(1.0 - car*car); + cbr = (ca*cg - cb)/(sa*sg); sbr = sqrt(1.0 - cbr*cbr); + cgr = (ca*cb - cg)/(sa*sb); sgr = sqrt(1.0 - cgr*cgr); + alphar = 180.0/M_PI*acos(car); + betar = 180.0/M_PI*acos(cbr); + gammar = 180.0/M_PI*acos(cgr); + return *this; +} + +LatticeParameters LatticeParameters::reciprocal() const +{ + using namespace std; + LatticeParameters rec(*this); + swap(rec.a, rec.ar); + swap(rec.b, rec.br); + swap(rec.c, rec.cr); + swap(rec.alpha, rec.alphar); + swap(rec.beta, rec.betar); + swap(rec.gamma, rec.gammar); + swap(rec.ca, rec.car); + swap(rec.cb, rec.cbr); + swap(rec.cg, rec.cgr); + swap(rec.sa, rec.sar); + swap(rec.sb, rec.sbr); + swap(rec.sg, rec.sgr); + return rec; +} + + +//////////////////////////////////////////////////////////////////////// +// PointsInSphere +//////////////////////////////////////////////////////////////////////// + +PointsInSphere::PointsInSphere( double _Rmin, double _Rmax, + const LatticeParameters& _latpar ) : + m(mno[0]), n(mno[1]), o(mno[2]), + Rmin(_Rmin), Rmax(_Rmax), latpar(_latpar) +{ + init(); + rewind(); +} + +PointsInSphere::PointsInSphere( double _Rmin, double _Rmax, + double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ) : + m(mno[0]), n(mno[1]), o(mno[2]), + Rmin(_Rmin), Rmax(_Rmax), + latpar(_a, _b, _c, _alpha, _beta, _gamma) +{ + init(); + rewind(); +} + +void PointsInSphere::init() +{ + RminSquare = (Rmin < 0.0) ? -(Rmin*Rmin) : Rmin*Rmin; + RmaxSquare = (Rmax < 0.0) ? -(Rmax*Rmax) : Rmax*Rmax; + dn0dm = latpar.cgr*latpar.br/latpar.ar; + do0dm = latpar.cbr*latpar.cr/latpar.ar; + // 2D reciprocal parameters in bc plane + b2r = 1.0/(latpar.b*latpar.sa); + c2r = 1.0/(latpar.c*latpar.sa); + ca2r = -latpar.ca; + do0dn = ca2r*c2r/b2r; + // 1D reciprocal along c axis + c1r = 1.0/latpar.c; +} + +void PointsInSphere::rewind() +{ + mHalfSpan = Rmax*latpar.ar; + hi_m = int(ceil(mHalfSpan)); + m = -hi_m; + // make indices n, o invalid, reset the neares point + n = hi_n = 0; + o = hi_o = outside_o = 0; + n0plane = o0plane = o0line = 0.0; + // unset excluded zone + oExclHalfSpan = 0.0; + // get the first inside point + next_o(); +} + +void PointsInSphere::next_o() +{ + do + { + o++; + if (o < hi_o) + { + return; + } + if (hi_o != outside_o) + { + hi_o = outside_o; + o = int( ceil(o0line+oExclHalfSpan) ) - 1; + continue; + } + next_n(); + } + while (!finished()); +} + +void PointsInSphere::next_n() +{ + do + { + n++; + if (n < hi_n) + { + o0line = o0plane + (n-n0plane)*do0dn; + double RlineSquare = RplaneSquare - pow((n-n0plane)/b2r,2); + oHalfSpan = RlineSquare > 0.0 ? sqrt(RlineSquare)*c1r : 0.0; + // parentheses improve round-off errors around [0,0,0] + double RExclSquare = RminSquare + (RlineSquare - RmaxSquare); + oExclHalfSpan = RExclSquare > 0.0 ? sqrt(RExclSquare)*c1r : 0.0; + o = int(floor(o0line - oHalfSpan)); + outside_o = int(ceil(o0line + oHalfSpan)); + hi_o = outside_o; + if (oExclHalfSpan) + { + int hole_o = int(ceil(o0line - oExclHalfSpan)); + if (fabs(hole_o-o0line) < oExclHalfSpan) hi_o = hole_o; + } + return; + } + next_m(); + } + while (!finished()); +} + +void PointsInSphere::next_m() +{ + m++; + if (finished()) + { + return; + } + // not finished here + n0plane = m*dn0dm; + o0plane = m*do0dm; + RplaneSquare = RmaxSquare - pow(m/latpar.ar,2); + nHalfSpan = RplaneSquare > 0.0 ? sqrt(RplaneSquare)*b2r : 0.0; + n = int(floor(n0plane - nHalfSpan)); + hi_n = int(ceil(n0plane + nHalfSpan)); +} + +double PointsInSphere::r() const +{ + const double &a = latpar.a, &b = latpar.b, &c = latpar.c; + const double &ca = latpar.ca, &cb = latpar.cb, &cg = latpar.cg; + return sqrt( m*m*a*a + n*n*b*b + o*o*c*c + + 2*m*n*a*b*cg + 2*m*o*a*c*cb + 2*n*o*b*c*ca ); +} + + +//////////////////////////////////////////////////////////////////////// +// ReflectionsInQminQmax +//////////////////////////////////////////////////////////////////////// + +ReflectionsInQminQmax::ReflectionsInQminQmax( double _Qmin, double _Qmax, + const LatticeParameters& _latpar ) : + Qmin(_Qmin), Qmax(_Qmax), + latpar(_latpar), + sph(Qmin*M_1_PI/2.0, Qmax*M_1_PI/2.0, latpar.reciprocal()), + hkl(sph.mno), h(hkl[0]), k(hkl[1]), l(hkl[2]) +{ } + +ReflectionsInQminQmax::ReflectionsInQminQmax( double _Qmin, double _Qmax, + double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ) : + Qmin(_Qmin), Qmax(_Qmax), + latpar(_a, _b, _c, _alpha, _beta, _gamma), + sph(Qmin*M_1_PI/2.0, Qmax*M_1_PI/2.0, latpar.reciprocal()), + hkl(sph.mno), h(hkl[0]), k(hkl[1]), l(hkl[2]) +{ } + + +//////////////////////////////////////////////////////////////////////// +// ReflectionsInDmaxDmin +//////////////////////////////////////////////////////////////////////// + +ReflectionsInDmaxDmin::ReflectionsInDmaxDmin( double _Dmax, double _Dmin, + const LatticeParameters& _latpar ) : + ReflectionsInQminQmax(2.0*M_PI/_Dmax, 2.0*M_PI/_Dmin, _latpar), + Dmax(_Dmax), Dmin(_Dmin) +{ } + +ReflectionsInDmaxDmin::ReflectionsInDmaxDmin( double _Dmax, double _Dmin, + double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ) : + ReflectionsInQminQmax( 2.0*M_PI/_Dmax, 2.0*M_PI/_Dmin, + _a, _b, _c, _alpha, _beta, _gamma ), + Dmax(_Dmax), Dmin(_Dmin) +{ } + +// End of file diff --git a/libsrreal/PointsInSphere.h b/libsrreal/PointsInSphere.h new file mode 100644 index 00000000..e0fab917 --- /dev/null +++ b/libsrreal/PointsInSphere.h @@ -0,0 +1,186 @@ +/*********************************************************************** +* +* pdffit2 by DANSE Diffraction group +* Simon J. L. Billinge +* (c) 2006 trustees of the Michigan State University +* All rights reserved. +* +* File coded by: Pavol Juhas +* +* See AUTHORS.txt for a list of people who contributed. +* See LICENSE.txt for license information. +* +************************************************************************ +* +* classes PointsInSphere, ReflectionsInQminQmax, ReflectionsInDmaxDmin +* +* Constructors: +* +* PointsInSphere(Rmin, Rmax, a, b, c, alpha, beta, gamma) +* ReflectionsInQminQmax(Qmin, Qmax, a, b, c, alpha, beta, gamma) +* ReflectionsInDmaxDmin(Dmax, Dmin, a, b, c, alpha, beta, gamma) +* +* Examples: +* +* PointsInSphere sph(Rmin, Rmax, a, b, c, alpha, beta, gamma) +* for (sph.rewind(); !sph.finished(); sph.next()) +* { +* // lattice indices are in sph.m, sph.n, sph.o or sph.mno[3] +* // sph.r() is distance from origin, +* // where Rmin < sph.r() < Rmax +* } +* +* ReflectionsInQminQmax refl(Qmin, Qmax, a, b, c, alpha, beta, gamma) +* for (ReflectionsInQminQmax ref(Qmin, Qmax, a, b, c, alpha, beta, gamma); +* !ref.finished(); ref.next() ) +* { +* // Miller indices are in ref.h, ref.k, ref.l or ref.hkl[3] +* // ref.Q() is magnitude of Q vector +* // ref.d() is lattice plane spacing +* } +* +* Tip: add epsilon to Rmax to avoid roundoff issues +* +* $Id$ +* +***********************************************************************/ + +#ifndef POINTSINSPHERE_H_INCLUDED +#define POINTSINSPHERE_H_INCLUDED + +// ensure math constants get defined for MSVC +#define _USE_MATH_DEFINES +#include + + +namespace NS_POINTSINSPHERE { + +class LatticeParameters +{ +public: + LatticeParameters( double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ); + // calculate all properties from current lattice parameters + LatticeParameters& update(); + // return a reciprocal of this lattice + LatticeParameters reciprocal() const; + // input arguments + double a, b, c, alpha, beta, gamma; + // cosines and sines of direct lattice angles + double ca, cb, cg, sa, sb, sg; + // reciprocal lattice and its cosines and sines + double ar, br, cr, alphar, betar, gammar; + double car, cbr, cgr, sar, sbr, sgr; +private: + // helper functions + inline double cosd(double x) { return cos(M_PI/180.0*x); } + inline double sind(double x) { return sin(M_PI/180.0*x); } +}; + +class PointsInSphere +{ +public: + PointsInSphere( double _Rmin, double _Rmax, + const LatticeParameters& _latpar ); + PointsInSphere( double _Rmin, double _Rmax, + double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ); + void rewind(); + inline void next() + { + next_o(); + } + inline bool finished() + { + return !(m < hi_m); + } + // mno array and m, n, o aliases are supposed to be read only + int mno[3]; + int &m, &n, &o; + double r() const; + // input arguments + const double Rmin, Rmax; + const LatticeParameters latpar; +private: + // loop advance functions + void next_m(); + void next_n(); + void next_o(); + void init(); + // calculated constants set by init() + double RminSquare, RmaxSquare; + // 2D reciprocal parameters and cosine in bc plane + double b2r, c2r, ca2r; + // reciprocal c + double c1r; + // offset of the nearest point to [0,0,0] + double dn0dm, do0dm, do0dn; + // loop variables + double n0plane, o0plane, o0line; + double mHalfSpan, nHalfSpan, oHalfSpan; + // o indices excluded due to Rmin + double oExclHalfSpan; + int hi_m, hi_n, hi_o, outside_o; + double RplaneSquare; +}; + +class ReflectionsInQminQmax +{ +public: + ReflectionsInQminQmax( double _Qmin, double _Qmax, + const LatticeParameters& _latpar ); + ReflectionsInQminQmax( double _Qmin, double _Qmax, + double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ); + inline void rewind() + { + sph.rewind(); + } + inline void next() + { + sph.next(); + } + inline bool finished() + { + return sph.finished(); + } + // input arguments + const double Qmin, Qmax; + const LatticeParameters latpar; +private: + // sph must be initialized before hkl and h, k, l + PointsInSphere sph; +public: + // hkl array and h, k, l aliases are supposed to be read only + int *hkl; + int &h, &k, &l; + inline double Q() const + { + return 2.0*M_PI*sph.r(); + } + inline double d() const + { + return 1.0/sph.r(); + } +}; + +class ReflectionsInDmaxDmin : ReflectionsInQminQmax +{ +public: + ReflectionsInDmaxDmin( double _Dmax, double _Dmin, + const LatticeParameters& _latpar ); + ReflectionsInDmaxDmin( double _Dmax, double _Dmin, + double _a, double _b, double _c, + double _alpha, double _beta, double _gamma ); + // input arguments + const double Dmax, Dmin; +}; + + +} // namespace NS_POINTSINSPHERE + +using NS_POINTSINSPHERE::PointsInSphere; +using NS_POINTSINSPHERE::ReflectionsInQminQmax; +using NS_POINTSINSPHERE::ReflectionsInDmaxDmin; + +#endif // POINTSINSPHERE_H_INCLUDED diff --git a/libsrreal/bindings/Makefile b/libsrreal/bindings/Makefile new file mode 100644 index 00000000..7f29291c --- /dev/null +++ b/libsrreal/bindings/Makefile @@ -0,0 +1,9 @@ +.PHONY : all +all : ${subst _ext.cpp,,${wildcard *_ext.cpp}} + +%: + MODULE=$@ make -f module.make + +.PHONY : clean +clean: + make -f module.make clean diff --git a/libsrreal/bindings/__init__.py b/libsrreal/bindings/__init__.py new file mode 100644 index 00000000..2d9ab011 --- /dev/null +++ b/libsrreal/bindings/__init__.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Python wrapping of ObjCryst namespace of ObjCryst++.""" + +# import pyobjcryst +import pyobjcryst + +# Register all converters +from registerconverters import * + +# bonditerator +from bonditerator import * + +# bondwidthcalculator +from bondwidthcalculator import * + +# profilecalculator +from profilecalculator import * + +# pdfcalculator +from pdfcalculator import * + diff --git a/libsrreal/bindings/bonditerator.py b/libsrreal/bindings/bonditerator.py new file mode 100644 index 00000000..5e33ee4c --- /dev/null +++ b/libsrreal/bindings/bonditerator.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python + +from _bonditerator import * diff --git a/libsrreal/bindings/bonditerator_ext.cpp b/libsrreal/bindings/bonditerator_ext.cpp new file mode 100644 index 00000000..abb0ff17 --- /dev/null +++ b/libsrreal/bindings/bonditerator_ext.cpp @@ -0,0 +1,131 @@ +/*********************************************************************** +* $Id$ +* +* Boost.python bindings to BondWidthCalculator. +***********************************************************************/ +#include "bonditerator.h" + +#include +#include +#include +#include +#include +#include + +#include + +using namespace boost::python; +using namespace SrReal; + +namespace { + +float getX(ShiftedSC &sc) +{ + return sc.xyz[0]; +} + +void setX(ShiftedSC &sc, float val) +{ + sc.xyz[0] = val; +} + +float getY(ShiftedSC &sc) +{ + return sc.xyz[1]; +} + +void setY(ShiftedSC &sc, float val) +{ + sc.xyz[2] = val; +} + +float getZ(ShiftedSC &sc) +{ + return sc.xyz[2]; +} + +void setZ(ShiftedSC &sc, float val) +{ + sc.xyz[2] = val; +} + +list getUnitCellFromCrystal(ObjCryst::Crystal &crystal) +{ + std::vector unitcell = getUnitCell(crystal); + + list uclist; + for(size_t i=0; i unitcell = bonditer.getUnitCell(); + + list uclist; + for(size_t i=0; i("ShiftedSC", init<>()) + .def(init()) + .def(init()) + .def_readwrite("sc", &ShiftedSC::sc) + .def_readwrite("id", &ShiftedSC::id) + .add_property("x", &getX, &setX) + .add_property("y", &getY, &setY) + .add_property("z", &getZ, &setZ) + .def(self < self) + .def(self == self) + // FIXME - this one doesn't work + //.def(self_ns::str(self)) // seg-faults + ; + + class_("BondPair", init<>()) + .def("getXYZ1", (float (BondPair::*)(size_t)) &BondPair::getXYZ1) + .def("getXYZ2", (float (BondPair::*)(size_t)) &BondPair::getXYZ2) + .def("setXYZ1", (void (BondPair::*)(size_t, float)) &BondPair::setXYZ1) + .def("setXYZ2", (void (BondPair::*)(size_t, float)) &BondPair::setXYZ2) + .def("setSC1", &BondPair::setSC1) + .def("getSC1", &BondPair::getSC1, return_internal_reference<>()) + .def("setSC2", &BondPair::setSC2) + .def("getSC2", &BondPair::getSC2, return_internal_reference<>()) + .def("getMultiplicity", &BondPair::getMultiplicity) + .def("setMultiplicity", &BondPair::setMultiplicity) + .def("getDistance", &BondPair::getDistance) + // FIXME - this one doesn't work + //.def(str(self)) + //.def(self_ns::str(self)) // seg-faults + ; + + class_("BondIterator", init()) + .def(init()) + .def(init()) + .def("setBondRange", &BondIterator::setBondRange) + .def("setScatteringComponent", &BondIterator::setScatteringComponent) + .def("rewind", &BondIterator::rewind) + .def("next", &BondIterator::next) + .def("finished", &BondIterator::finished) + .def("getBondPair", &BondIterator::getBondPair) + .def("getRmin", &BondIterator::getRmin) + .def("getRmax", &BondIterator::getRmax) + .def("getCrystal", &BondIterator::getCrystal, + return_internal_reference<>()) + .def("getUnitCell", &getUnitCellFromBondIterator) + ; +} diff --git a/libsrreal/bindings/bondwidthcalculator.py b/libsrreal/bindings/bondwidthcalculator.py new file mode 100644 index 00000000..f0643434 --- /dev/null +++ b/libsrreal/bindings/bondwidthcalculator.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python + +from _bondwidthcalculator import * diff --git a/libsrreal/bindings/bondwidthcalculator_ext.cpp b/libsrreal/bindings/bondwidthcalculator_ext.cpp new file mode 100644 index 00000000..b9b3660a --- /dev/null +++ b/libsrreal/bindings/bondwidthcalculator_ext.cpp @@ -0,0 +1,66 @@ +/*********************************************************************** +* $Id$ +* +* Boost.python bindings to BondWidthCalculator. +***********************************************************************/ +#include "bondwidthcalculator.h" + +#include +#include +#include +#include +#include + +using namespace boost::python; +using namespace SrReal; + +namespace { + +class BondWidthCalculatorWrap + : public BondWidthCalculator, public wrapper +{ + + public: + + BondWidthCalculatorWrap() + : BondWidthCalculator() + {} + + // Do not wrap. Workaround for missing copy consructor in RefinableObj. + BondWidthCalculatorWrap(const BondWidthCalculatorWrap& other) {} + + float default_calculate(BondPair& bp) + { return BondWidthCalculator::calculate(bp); } + + float calculate(BondPair& bp) + { + if (override calculate + = this->get_override("calculate")) + { + return calculate(bp); + } + return default_calculate(bp); + } +}; // BondWidthCalculatorWrap + +} // anonymous namespace + + +BOOST_PYTHON_MODULE(_bondwidthcalculator) +{ + + class_ >("BondWidthCalculator") + .def("calculate", &BondWidthCalculator::calculate, + &BondWidthCalculatorWrap::default_calculate) + ; + + class_ >("JeongBWCalculator") + .def("getDelta1", &JeongBWCalculator::getDelta1) + .def("getDelta2", &JeongBWCalculator::getDelta2) + .def("getQbroad", &JeongBWCalculator::getQbroad) + .def("setDelta1", &JeongBWCalculator::setDelta1) + .def("setDelta2", &JeongBWCalculator::setDelta2) + .def("setQbroad", &JeongBWCalculator::setQbroad) + ; +} diff --git a/libsrreal/bindings/converters.h b/libsrreal/bindings/converters.h new file mode 100644 index 00000000..c8290bad --- /dev/null +++ b/libsrreal/bindings/converters.h @@ -0,0 +1,24 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ +#ifndef _CONVERTERS_H +#define _CONVERTERS_H + +#include +#include + +#include + +// +// +using namespace boost::python; + +// Make an array out of a data pointer and a dimension vector +PyObject* makeNdArray(float* data, std::vector& dims) +{ + PyObject* pyarray = PyArray_SimpleNewFromData + (dims.size(), &dims[0], PyArray_FLOAT, (void *) data); + return incref(PyArray_Copy( (PyArrayObject*) pyarray )); +} + +#endif diff --git a/libsrreal/bindings/module.make b/libsrreal/bindings/module.make new file mode 100644 index 00000000..4f4d0ea6 --- /dev/null +++ b/libsrreal/bindings/module.make @@ -0,0 +1,101 @@ +# User variables - can be set as environment variables or as make arguments +# +# PYTHON_VERSION version of Python used for compilation, e.g. "2.3" +# PYTHON_INCDIR python header files +# NUMPY_INCDIR numpy header files +# DEBUG debugging flags (-gstabs+), turns off optimizations + +# MODULE +ifndef MODULE +MODULE = profilecalculator +endif + +# figure out user variables +# PYTHON_VERSION +ifndef PYTHON_VERSION +PYTHON_VERSION = $(shell python -c 'import sys; print sys.version[:3]') +endif + +# PYTHON_INCDIR +ifndef PYTHON_INCDIR +PYTHON_INCDIR = /usr/include/python$(PYTHON_VERSION) +endif + +# NUMPY_INCDIR +ifndef NUMPY_INCDIR +#NUMPY_INCDIR = $(shell python -c "import numpy; import os.path; print os.path.split(numpy.__file__)[0] + '/core/include'") +#NUMPY_INCDIR = /usr/lib/python$(PYTHON_VERSION)/site-packages/numpy/core/include +NUMPY_INCDIR=/home/chris/local/include/ +endif + +# Objcryst headers +ifndef OBJCRYST_HEADERS +OBJCRYST_HEADERS=/home/chris/local/src/ObjCryst/ObjCryst +endif + +# SrReal headers +ifndef SRREAL_HEADERS +SRREAL_HEADERS=../ +endif + +# CFLAGS +ifdef DEBUG +CFLAGS = $(DEBUG) -fPIC -Wall +else +CFLAGS = -fPIC -O3 -w -ffast-math -pipe -funroll-loops +endif + +# Shared libary for so files +ifndef LIB +LIB = /home/chris/local/lib +endif + +# Shared library for python files +ifndef PYLIB +PYLIB = . +endif + +# end of setup + +CC = g++ +LINK = g++ +LINKFLAGS = -L$(LIB) -L. + +# Where to search for dependencies +VPATH = $(LIB) + +# Needed for python wrapper +MODOBJ = $(MODULE).o +MODSO = _$(MODULE).so + +## Directives + +.PHONY : $(MODULE) +$(MODULE): $(MODSO) + + +### Rules + +## Boost + +$(MODSO) : $(MODOBJ) _registerconverters.so + $(LINK) -shared $(LINKFLAGS) $< -o $@ -lsrreal -lboost_python -lpython$(PYTHON_VERSION) + +$(MODOBJ) : $(MODULE)_ext.cpp + $(CC) -c $< -o $@ -DHAVE_CONFIG_H -I$(PYTHON_INCDIR) -I$(OBJCRYST_HEADERS) -I$(SRREAL_HEADERS) + +_registerconverters.so : registerconverters.o + $(LINK) -shared $(LINKFLAGS) $< -o $@ -lsrreal -lboost_python -lpython$(PYTHON_VERSION) + +## Object Rules +# + +registerconverters.o : registerconverters.cpp converters.h + +%.o:%.cpp + $(CC) -c $< -DHAVE_CONFIG_H -I$(PYTHON_INCDIR) -I$(NUMPY_INCDIR) -I$(OBJCRYST_HEADERS) + +.PHONY : clean +clean: + -rm -f *.so *.o *.a *.pyc + diff --git a/libsrreal/bindings/pdfcalculator.py b/libsrreal/bindings/pdfcalculator.py new file mode 100644 index 00000000..9f7c9dd1 --- /dev/null +++ b/libsrreal/bindings/pdfcalculator.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python + +from _pdfcalculator import * diff --git a/libsrreal/bindings/pdfcalculator_ext.cpp b/libsrreal/bindings/pdfcalculator_ext.cpp new file mode 100644 index 00000000..60189cf1 --- /dev/null +++ b/libsrreal/bindings/pdfcalculator_ext.cpp @@ -0,0 +1,24 @@ +/*********************************************************************** +* $Id$ +* +* Boost.python bindings to PDFCalculator. +***********************************************************************/ +#include "pdfcalculator.h" + +#include +#include +#include +#include +#include + +using namespace boost::python; +using namespace SrReal; + + +BOOST_PYTHON_MODULE(_pdfcalculator) +{ + + class_ > + ("PDFCalculator", init()) + ; +} diff --git a/libsrreal/bindings/profilecalculator.py b/libsrreal/bindings/profilecalculator.py new file mode 100644 index 00000000..9eb8b37b --- /dev/null +++ b/libsrreal/bindings/profilecalculator.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python + +from _profilecalculator import * diff --git a/libsrreal/bindings/profilecalculator_ext.cpp b/libsrreal/bindings/profilecalculator_ext.cpp new file mode 100644 index 00000000..f9e70f2c --- /dev/null +++ b/libsrreal/bindings/profilecalculator_ext.cpp @@ -0,0 +1,282 @@ +/*********************************************************************** +* $Id$ +* +* Boost.python bindings to ProfileCalculator. +***********************************************************************/ +#define PY_ARRAY_UNIQUE_SYMBOL srreal_ARRAY_API +//#define NO_IMPORT_ARRAY + +#include "profilecalculator.h" +#include "converters.h" + +#include +#include +#include +#include +#include + +#include + +#include +#include + + +using namespace boost::python; +using namespace SrReal; + +namespace { + + +class ProfileCalculatorWrap + : public ProfileCalculator, public wrapper +{ + + public: + + ProfileCalculatorWrap( + BondIterator& _bonditer, + BondWidthCalculator& _bwcalc) + : ProfileCalculator(_bonditer, _bwcalc) + {} + + // pure virtual functions + float* getPDF() + { + return this->get_override("getPDF")(); + } + + float* getRDF() + { + return this->get_override("getRDF")(); + } + + // virtual functions + + BondIterator& default_getBondIterator() + { return ProfileCalculator::getBondIterator(); } + + BondIterator& getBondIterator() + { + if (override getBondIterator + = this->get_override("getBondIterator")) + { + return getBondIterator(); + } + return default_getBondIterator(); + } + + BondWidthCalculator& default_getBondWidthCalculator() + { return ProfileCalculator::getBondWidthCalculator(); } + + BondWidthCalculator& getBondWidthCalculator() + { + if (override getBondWidthCalculator + = this->get_override("getBondWidthCalculator")) + { + return getBondWidthCalculator(); + } + return default_getBondWidthCalculator(); + } + + void default_setScatType(const ObjCryst::RadiationType _radtype) + { ProfileCalculator::setScatType(_radtype); } + + void setScatType(const ObjCryst::RadiationType _radtype) + { + if (override setScatType + = this->get_override("setScatType")) + { + setScatType(_radtype); + return; + } + default_setScatType(_radtype); + } + + ObjCryst::RadiationType default_getScatType() + { return ProfileCalculator::getScatType(); } + + ObjCryst::RadiationType getScatType() + { + if (override getScatType + = this->get_override("getScatType")) + { + return getScatType(); + } + return default_getScatType(); + } + + void default_setCalculationPoints( + const float* _rvals, const size_t numpoints) + { ProfileCalculator::setCalculationPoints(_rvals, numpoints); } + + void setCalculationPoints( + const float* _rvals, const size_t numpoints) + { + if (override setCalculationPoints + = this->get_override("setCalculationPoints")) + { + setCalculationPoints(_rvals, numpoints); + return; + } + default_setCalculationPoints(_rvals, numpoints); + } + + const float* default_getCalculationPoints() + { return ProfileCalculator::getCalculationPoints(); } + + const float* getCalculationPoints() + { + if (override getCalculationPoints + = this->get_override("getCalculationPoints")) + { + return getCalculationPoints(); + } + return default_getCalculationPoints(); + } + + size_t default_getNumPoints() + { return ProfileCalculator::getNumPoints(); } + + size_t getNumPoints() + { + if (override getNumPoints + = this->get_override("getNumPoints")) + { + return getNumPoints(); + } + return default_getNumPoints(); + } + + void default_setQmax(float val) + { ProfileCalculator::setQmax(val); } + + void setQmax(float val) + { + if (override setQmax + = this->get_override("setQmax")) + { + setQmax(val); + return; + } + default_setQmax(val); + } + + float default_getQmax() + { return ProfileCalculator::getQmax(); } + + float getQmax() + { + if (override getQmax + = this->get_override("getQmax")) + { + return getQmax(); + } + return default_getQmax(); + } + + void default_setQmin(float val) + { ProfileCalculator::setQmin(val); } + + void setQmin(float val) + { + if (override setQmin + = this->get_override("setQmin")) + { + setQmin(val); + return; + } + default_setQmin(val); + } + + float default_getQmin() + { return ProfileCalculator::getQmin(); } + + float getQmin() + { + if (override getQmin + = this->get_override("getQmin")) + { + return getQmin(); + } + return default_getQmin(); + } + +}; // ProfileCalculatorWrap + +void setCalculationPointsNdArray(ProfileCalculator& pc, object& obj) +{ + + size_t numpoints = extract(obj.attr("__len__")()); + float *rvals = new float [numpoints]; + for(int i=0; i(obj.attr("__getitem__")(i)); + } + + pc.setCalculationPoints(rvals, numpoints); + delete rvals; +} + +static PyObject* getCalculationPointsNdArray(ProfileCalculator& pc) +{ + const float* rvals = pc.getCalculationPoints(); + size_t numpoints = pc.getNumPoints(); + std::vector dims(1, numpoints); + return makeNdArray(const_cast(rvals), dims); +} + +static PyObject* getPDFNdArray(ProfileCalculator& pc) +{ + float* pdf = pc.getPDF(); + size_t numpoints = pc.getNumPoints(); + //for(size_t i=0; i dims(1, numpoints); + return makeNdArray(pdf, dims); +} + +static PyObject* getRDFNdArray(ProfileCalculator& pc) +{ + float* rdf = pc.getRDF(); + size_t numpoints = pc.getNumPoints(); + std::vector dims(1, numpoints); + return makeNdArray(rdf, dims); +} + +} // anonymous namespace + + +BOOST_PYTHON_MODULE(_profilecalculator) +{ + + import_array(); + + class_ > + ("ProfileCalculator", init()) + .def("getBondIterator", &ProfileCalculator::getBondIterator, + &ProfileCalculatorWrap::default_getBondIterator, + return_internal_reference<>()) + .def("getBondWidthCalculator", &ProfileCalculator::getBondWidthCalculator, + &ProfileCalculatorWrap::default_getBondWidthCalculator, + return_internal_reference<>()) + .def("setScatType", &ProfileCalculator::setScatType, + &ProfileCalculatorWrap::default_setScatType) + .def("getScatType", &ProfileCalculator::getScatType, + &ProfileCalculatorWrap::default_getScatType) + .def("getCalculationPoints", &getCalculationPointsNdArray) + .def("setCalculationPoints", &setCalculationPointsNdArray) + .def("getNumPoints", &ProfileCalculator::getNumPoints, + &ProfileCalculatorWrap::default_getNumPoints) + .def("setQmax", &ProfileCalculator::setQmax, + &ProfileCalculatorWrap::default_setQmax) + .def("getQmax", &ProfileCalculator::getQmax, + &ProfileCalculatorWrap::default_getQmax) + .def("setQmin", &ProfileCalculator::setQmin, + &ProfileCalculatorWrap::default_setQmin) + .def("getQmin", &ProfileCalculator::getQmin, + &ProfileCalculatorWrap::default_getQmin) + .def("getRDF", &getRDFNdArray) + .def("getPDF", &getPDFNdArray) + ; +} diff --git a/libsrreal/bindings/registerconverters.cpp b/libsrreal/bindings/registerconverters.cpp new file mode 100644 index 00000000..075ca8b8 --- /dev/null +++ b/libsrreal/bindings/registerconverters.cpp @@ -0,0 +1,13 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ +#define PY_ARRAY_UNIQUE_SYMBOL srreal_ARRAY_API + +#include +#include + +#include "converters.h" + +BOOST_PYTHON_MODULE(_registerconverters) +{ +} diff --git a/libsrreal/bindings/registerconverters.py b/libsrreal/bindings/registerconverters.py new file mode 100644 index 00000000..2197b115 --- /dev/null +++ b/libsrreal/bindings/registerconverters.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python + +from _registerconverters import * diff --git a/libsrreal/bindings/tests.py b/libsrreal/bindings/tests.py new file mode 100644 index 00000000..c65d9dbf --- /dev/null +++ b/libsrreal/bindings/tests.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python +"""A small test for the bindings.""" + +from pyobjcryst import * +from __init__ import * +import numpy +import time + +def getNi(numscat = 1): + + if numscat < 1: numscat = 1 + + pi = numpy.pi + c = Crystal(3.52, 3.52, 3.52, "225") + for i in xrange(numscat): + sp = ScatteringPowerAtom("Ni%i"%i, "Ni") + sp.SetBiso(8*pi*pi*0.003) + c.AddScatteringPower(sp) + atomp = Atom(0, 0, 0, "Ni%i"%i, sp, 1.0/numscat) + c.AddScatterer(atomp) + return c + +def getLaMnO3(): + + pi = numpy.pi + crystal = Crystal(5.486341, 5.619215, 7.628206, 90, 90, 90, "P b n m") + # La1 + sp = ScatteringPowerAtom("La1", "La") + sp.SetBiso(8*pi*pi*0.003) + atom = Atom(0.996096, 0.0321494, 0.25, "La1", sp) + crystal.AddScatteringPower(sp) + crystal.AddScatterer(atom) + # Mn1 + sp = ScatteringPowerAtom("Mn1", "Mn") + sp.SetBiso(8*pi*pi*0.003) + atom = Atom(0, 0.5, 0, "Mn1", sp) + crystal.AddScatteringPower(sp) + crystal.AddScatterer(atom) + # O1 + sp = ScatteringPowerAtom("O1", "O") + sp.SetBiso(8*pi*pi*0.003) + atom = Atom(0.0595746, 0.496164, 0.25, "O1", sp) + crystal.AddScatteringPower(sp) + crystal.AddScatterer(atom) + # O2 + sp = ScatteringPowerAtom("O2", "O") + sp.SetBiso(8*pi*pi*0.003) + atom = Atom(0.720052, 0.289387, 0.0311126, "O2", sp) + crystal.AddScatteringPower(sp) + crystal.AddScatterer(atom) + + return crystal + +def getCaF2(): + + pi = numpy.pi + crystal = Crystal(5.4625, 5.4625, 5.4625, 90, 90, 90, "F m -3 m") + # Ca1 + sp = ScatteringPowerAtom("Ca1", "Ca") + sp.SetBiso(8*pi*pi*0.003) + atom = Atom(0, 0, 0, "Ca1", sp) + crystal.AddScatteringPower(sp) + crystal.AddScatterer(atom) + # F1 + sp = ScatteringPowerAtom("F1", "F") + sp.SetBiso(8*pi*pi*0.003) + atom = Atom(0.25, 0.25, 0.25, "F1", sp) + crystal.AddScatteringPower(sp) + crystal.AddScatterer(atom) + + return crystal + +def printBonds(): + + c = getNi() + bi = BondIterator(c, 0, 4) + getUnitCell(c) + + scl = c.GetScatteringComponentList() + for sc in scl: + bi.setScatteringComponent(sc) + bi.rewind() + while(not bi.finished()): + bp = bi.getBondPair() + print bp + bi.next() + return + +def printPDF(): + + c = getNi() + #c = getLaMnO3() + rvals = numpy.arange(0, 10, 0.05) + biter = BondIterator(c) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + bwcalc.setDelta2(0) + pdf1 = timeCalculation(pdfcalc) + bwcalc.setDelta2(5) + pdf2 = timeCalculation(pdfcalc) + + + if 0: + from pylab import plot, show + plot(rvals, pdf1, rvals, pdf2) + show() + + return + +def timeCalculation(pdfcalc): + t1 = time.time() + pdf = pdfcalc.getPDF() + t2 = time.time() + print 1000*(t2-t1); + return pdf + +def speedTestLaMnO3(): + """Make some changes to the crystal and calculate the PDF each time.""" + + crystal = getLaMnO3() + rvals = numpy.arange(0, 10, 0.05) + biter = BondIterator(crystal) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + bwcalc.setDelta2(0) + + print "Times are in ms" + + print "Initial calculation" + pdf1 = timeCalculation(pdfcalc) + + # Change the bwcalc. This should take about the same time. + bwcalc.setDelta2(5) + print "Change in BW calculator" + pdf2 = timeCalculation(pdfcalc) + + # Change an x-coordinate + scatla = crystal.GetScatt("La1") + scatla.SetX(0.8) + print "Change in atom 0 x-value" + pdf3 = timeCalculation(pdfcalc) + + # Change an thermal parameter + pi = numpy.pi + sp = crystal.GetScatteringPower("La1") + sp.SetBiso(8*pi*pi*0.008) + print "Change in atom 0 Biso" + pdf4 = timeCalculation(pdfcalc) + + # Change another atom + scato1 = crystal.GetScatt("O1") + scato1.SetX(0.05) + print "Change in atom 2" + pdf5 = timeCalculation(pdfcalc) + + cla = scatla.GetClockScatterer() + co1 = scato1.GetClockScatterer() + # Change properties of two atoms. Should + scatla.SetX(0.9) + scato1.SetX(0.07) + print "Change in atoms 0 and 2" + pdf6 = timeCalculation(pdfcalc) + + return + +def scalingTest(): + + rvals = numpy.arange(0, 10, 0.05) + bwcalc = JeongBWCalculator() + + print "PDF calculation" + for i in range(10): + c = getNi(i+1) + biter = BondIterator(c) + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + print "%-2i scatterers"%(i+1,), + pdf = timeCalculation(pdfcalc) + scat = c.GetScatt("Ni0") + scat.SetOccupancy(1) + pdf = timeCalculation(pdfcalc) + + print "Unit cell generation" + for i in range(10): + c = getNi(i+1) + t1 = time.time() + getUnitCell(c) + t2 = time.time() + print 1000*(t2-t1) + +def consistencyTest(): + """Make some changes to the crystal and calculate the PDF each time.""" + + crystal = getLaMnO3() + rvals = numpy.arange(0, 10, 0.05) + biter = BondIterator(crystal) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + bwcalc.setDelta2(0) + + print "Initial calculation" + pdf1 = pdfcalc.getPDF() + + # Change the bwcalc. This should take about the same time. + bwcalc.setDelta2(5) + print "Change in BW calculator" + pdf2 = pdfcalc.getPDF() + + # Change an x-coordinate + scatla = crystal.GetScatt("La1") + scatla.SetX(0.8) + scatla.SetX(0.81) + scatla.SetX(0.82) + scatla.SetX(0.8) + print "Change in atom 0" + pdf3 = pdfcalc.getPDF() + + # Change an thermal parameter + pi = numpy.pi + sp = crystal.GetScatteringPower("La1") + sp.SetBiso(8*pi*pi*0.008) + print "Change in atom 0 Biso" + pdf4 = pdfcalc.getPDF() + + # Change another atom + scato1 = crystal.GetScatt("O1") + scato1.SetX(0.05) + print "Change in atom 2" + pdf5 = pdfcalc.getPDF() + + # Change properties of two atoms. Should + #scatla.GetClockScatterer().Reset() + scatla.SetX(0.9) + scato1.SetX(0.07) + print "Change in atoms 0 and 2" + pdf6 = pdfcalc.getPDF() + + return + +def scalingTest(): + + rvals = numpy.arange(0, 10, 0.05) + bwcalc = JeongBWCalculator() + + print "PDF calculation" + for i in range(10): + c = getNi(i+1) + biter = BondIterator(c) + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + print "%-2i scatterers"%(i+1,), + pdf = timeCalculation(pdfcalc) + scat = c.GetScatt("Ni0") + scat.SetOccupancy(1) + pdf = timeCalculation(pdfcalc) + + print "Unit cell generation" + for i in range(10): + c = getNi(i+1) + t1 = time.time() + getUnitCell(c) + t2 = time.time() + print 1000*(t2-t1) + +def clockTest(): + + c1 = RefinableObjClock() + c2 = RefinableObjClock() + c3 = RefinableObjClock() + c1.AddChild(c2) + c3.AddChild(c2) + + + print "Clock 1" + for i in range(3): + print "c1 ", + c1.Print() + print "c2 ", + c2.Print() + c1.Click(); + + print "Clock 2" + for i in range(9): + print "c1 ", + c1.Print() + print "c2 ", + c2.Print() + c2.Click(); + + c3.Print() + +def consistencyTest2(): + """Make some changes to the crystal and calculate the PDF each time.""" + + crystal = getLaMnO3() + rvals = numpy.arange(0, 10, 0.05) + biter = BondIterator(crystal) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + bwcalc.setDelta2(0) + + print "Initial calculation" + pdfcalc.getPDF() + + # Change an x-coordinate + scatla = crystal.GetScatt("La1") + scatla.SetX(0.8) + #scatla.SetX(0.81) + #scatla.SetX(0.82) + #scatla.SetX(0.8) + print "Change in atom 0" + pdf3 = pdfcalc.getPDF() + return + +def speedTest(f): + """Make some changes to the crystal and calculate the PDF each time.""" + + crystal = f() + rvals = numpy.arange(0, 10, 0.05) + biter = BondIterator(crystal) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + bwcalc.setDelta2(0) + + print "Times are in ms" + + print "Calculate SCL" + t1 = time.time() + crystal.GetScatteringComponentList() + t2 = time.time() + print 1000*(t2-t1); + + print "Generate unit cell" + t1 = time.time() + getUnitCell(crystal) + t2 = time.time() + print 1000*(t2-t1); + + print "Initial calculation" + timeCalculation(pdfcalc) + + print "Do that again" + timeCalculation(pdfcalc) + + # Change the bwcalc. This should take about the same time. + bwcalc.setDelta2(5) + print "Change in BW calculator" + timeCalculation(pdfcalc) + + # Change an x-coordinate + scat = crystal.GetScatt(0) + scat.SetX(0.8) + print "Change in atom 0 x-value" + timeCalculation(pdfcalc) + + print "Generate unit cell again" + t1 = time.time() + getUnitCell(crystal) + t2 = time.time() + print 1000*(t2-t1); + return + +def scalingTest(): + + rvals = numpy.arange(0, 10, 0.05) + bwcalc = JeongBWCalculator() + + print "PDF calculation" + for i in range(10): + c = getNi(i+1) + biter = BondIterator(c) + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + print "%-2i scatterers"%(i+1,), + pdf = timeCalculation(pdfcalc) + scat = c.GetScatt("Ni0") + scat.SetOccupancy(1) + pdf = timeCalculation(pdfcalc) + + print "Unit cell generation" + for i in range(10): + c = getNi(i+1) + t1 = time.time() + getUnitCell(c) + t2 = time.time() + print 1000*(t2-t1) + +def consistencyTest(): + """Make some changes to the crystal and calculate the PDF each time.""" + + crystal = getLaMnO3() + rvals = numpy.arange(0, 10, 0.05) + biter = BondIterator(crystal) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + bwcalc.setDelta2(0) + + print "Initial calculation" + pdf1 = pdfcalc.getPDF() + + # Change the bwcalc. This should take about the same time. + bwcalc.setDelta2(5) + print "Change in BW calculator" + pdf2 = pdfcalc.getPDF() + + # Change an x-coordinate + scatla = crystal.GetScatt("La1") + scatla.SetX(0.8) + scatla.SetX(0.81) + scatla.SetX(0.82) + scatla.SetX(0.8) + print "Change in atom 0" + pdf3 = pdfcalc.getPDF() + + # Change an thermal parameter + pi = numpy.pi + sp = crystal.GetScatteringPower("La1") + sp.SetBiso(8*pi*pi*0.008) + print "Change in atom 0 Biso" + pdf4 = pdfcalc.getPDF() + + # Change another atom + scato1 = crystal.GetScatt("O1") + scato1.SetX(0.05) + print "Change in atom 2" + pdf5 = pdfcalc.getPDF() + + # Change properties of two atoms. Should + #scatla.GetClockScatterer().Reset() + scatla.SetX(0.9) + scato1.SetX(0.07) + print "Change in atoms 0 and 2" + pdf6 = pdfcalc.getPDF() + + return + +def scalingTest(): + + rvals = numpy.arange(0, 10, 0.05) + bwcalc = JeongBWCalculator() + + print "PDF calculation" + for i in range(10): + c = getNi(i+1) + biter = BondIterator(c) + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + print "%-2i scatterers"%(i+1,), + pdf = timeCalculation(pdfcalc) + scat = c.GetScatt("Ni0") + scat.SetOccupancy(1) + pdf = timeCalculation(pdfcalc) + + print "Unit cell generation" + for i in range(10): + c = getNi(i+1) + t1 = time.time() + getUnitCell(c) + t2 = time.time() + print 1000*(t2-t1) + +def clockTest(): + + c1 = RefinableObjClock() + c2 = RefinableObjClock() + c3 = RefinableObjClock() + c1.AddChild(c2) + c3.AddChild(c2) + + + print "Clock 1" + for i in range(3): + print "c1 ", + c1.Print() + print "c2 ", + c2.Print() + c1.Click(); + + print "Clock 2" + for i in range(9): + print "c1 ", + c1.Print() + print "c2 ", + c2.Print() + c2.Click(); + + c3.Print() + +def consistencyTest2(): + """Make some changes to the crystal and calculate the PDF each time.""" + + crystal = getLaMnO3() + rvals = numpy.arange(0, 10, 0.05) + biter = BondIterator(crystal) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + bwcalc.setDelta2(0) + + print "Initial calculation" + pdfcalc.getPDF() + + # Change an x-coordinate + scatla = crystal.GetScatt("La1") + scatla.SetX(0.8) + #scatla.SetX(0.81) + #scatla.SetX(0.82) + #scatla.SetX(0.8) + print "Change in atom 0" + pdf3 = pdfcalc.getPDF() + +def calculate(f, outname): + c = f() + rvals = numpy.arange(0, 10.0 -0.05, 0.05) + biter = BondIterator(c) + bwcalc = JeongBWCalculator() + + pdfcalc = PDFCalculator(biter, bwcalc) + pdfcalc.setQmax(30) + pdfcalc.setCalculationPoints(rvals) + pdf = timeCalculation(pdfcalc) + + from numpy import savetxt + savetxt(outname, zip(rvals, pdf)) + + + return + +if __name__ == "__main__": + + #scalingTest() + #speedTest(getCaF2) + #calculate(getCaF2, "caf2.pdf.calc") + #consistencyTest2() + #clockTest() + diff --git a/libsrreal/bonditerator.cpp b/libsrreal/bonditerator.cpp new file mode 100644 index 00000000..d09d8346 --- /dev/null +++ b/libsrreal/bonditerator.cpp @@ -0,0 +1,531 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ + +#include +#include +#include + +#include "bonditerator.h" +#include "PointsInSphere.h" + +// From ObjCryst distribution +#include "CrystVector/CrystVector.h" +#include "ObjCryst/ScatteringPower.h" +#include "ObjCryst/SpaceGroup.h" + +#include "assert.h" + +using namespace SrReal; +using std::set; +using std::vector; + +namespace { + +float rtod = 180.0/M_PI; +const float toler = 1e-5; + +} // End anonymous namespace + +/****************************************************************************** +***** BondIterator implementation ********************************************* +******************************************************************************/ + +SrReal::BondIterator:: +BondIterator (ObjCryst::Crystal& _crystal) + : crystal(_crystal), rmin(0), rmax(0) + +{ + sph = NULL; + sc = NULL; + itclock.Reset(); + latclock.Reset(); + //rewind(); +} + +SrReal::BondIterator:: +BondIterator (ObjCryst::Crystal& _crystal, float _rmin, float _rmax) + : crystal(_crystal), rmin(_rmin), rmax(_rmax) + +{ + sph = NULL; + sc = NULL; + itclock.Reset(); + latclock.Reset(); + //rewind(); +} + +SrReal::BondIterator:: +BondIterator(const BondIterator& other) + : crystal(other.crystal), rmin(other.rmin), rmax(other.rmax) +{ + sph = NULL; + sc = NULL; + itclock.Reset(); + latclock.Reset(); + //rewind(); +} + +SrReal::BondIterator:: +~BondIterator() +{ + if( sph != NULL ) + { + delete sph; + } +} + +void +SrReal::BondIterator:: +setBondRange(float _rmin, float _rmax) +{ + rmin = _rmin; + rmax = _rmax; + itclock.Reset(); + latclock.Reset(); + //rewind(); + return; +} + +void +SrReal::BondIterator:: +setScatteringComponent(const ObjCryst::ScatteringComponent& _sc) +{ + sc = &_sc; + calculateDegeneracy(); + + // Assign the first half of the bp + float x, y, z; + x = sc->mX; + y = sc->mY; + z = sc->mZ; + crystal.FractionalToOrthonormalCoords(x,y,z); + bp.xyz1[0] = x; + bp.xyz1[1] = y; + bp.xyz1[2] = z; + bp.sc1 = sc; + + //rewind(); + return; +} + +/* Rewind the iterator. + * + * This detects changes in the crystal and regenerates the unit cell if + * necessary. + */ +void +SrReal::BondIterator:: +rewind() +{ + + // update the iterator (if necessary). + update(); + + if( sc == NULL ) + { + isfinished = true; + return; + } + + if(sscvec.size() == 0) + { + isfinished = true; + return; + } + + if(rmax == 0) + { + isfinished = true; + } + + // Prepare for the incrementor. + iteri = sscvec.begin(); + sph->rewind(); + isfinished = false; + + // Initialize the first bond + next(); + + return; + +} + +/* This sets bp to the next bond in the iteration sequence. + * + * The duty of this function is to call the incrementer. It is the + * responsibility of the incrementer to set bp and indicate if it was + * successful. + */ +void +SrReal::BondIterator:: +next() +{ + + if( isfinished ) return; + + isfinished = !increment(); + + return; + +} + +bool +SrReal::BondIterator:: +finished() +{ + return isfinished; +} + +/* Get the bond pair from the iterator */ +BondPair +SrReal::BondIterator:: +getBondPair() +{ + return bp; +} + +/*****************************************************************************/ + +/* This expands primitive cell of the crystal and fills sscvec if the crystal + * clock is greater than the iterator clock. + */ +void +SrReal::BondIterator:: +update() +{ + //std::cout << "crystal clock: "; + //crystclock.Print(); + //std::cout << "iterator clock: "; + //itclock.Print(); + + // FIXME - don't need to recalculate when only atom occupancies change or + // Biso values change. + if(itclock < crystal.GetClockScattCompList()) + { + //std::cout << "crystal changed" << std::endl; + // Reset the sscvec + sscvec.clear(); + sscvec = SrReal::getUnitCell(crystal); + + // Calculate the degeracy of sc in the unit cell. + calculateDegeneracy(); + + // Synchronize the clocks + itclock = crystal.GetClockScattCompList(); + } + + if(rmax != 0) + { + + if(latclock >= crystal.GetClockLatticePar()) return; + latclock = crystal.GetClockLatticePar(); + + if(sph != NULL) delete sph; + sph = new PointsInSphere((float) rmin, (float) rmax, + crystal.GetLatticePar(0), + crystal.GetLatticePar(1), + crystal.GetLatticePar(2), + rtod*crystal.GetLatticePar(3), + rtod*crystal.GetLatticePar(4), + rtod*crystal.GetLatticePar(5) + ); + } + + return; +} + + +/* This increments the iterator. + * + * Returns true when the incrementer progressed, false otherwise. + */ +bool +SrReal::BondIterator:: +increment() +{ + /* iteri = slow iterator (outer loop) + * sph = fast iterator (inner loop) + */ + + // Terminate when the outer loop finishes. + if(iteri == sscvec.end()) + { + return false; + } + // Skip this scatterer with itself + // FIXME - this comparison is not right. Must create a ShiftedSC from the + // ScatteringComponent as is done in getUnitCell. + //if( sph->mno[0] == 0 && + // sph->mno[0] == 0 && + // sph->mno[0] == 0 && + // ) + //{ + + // // Increment sph + // sph->next(); + // // If sph is finished, then we reset it and increment iteri + // if( sph->finished() ) + // { + // sph->rewind(); + // ++iteri; + // } + // return increment(); + //} + + // If we got here, then we can record the bond + for(size_t l=0;l<3;++l) + { + bp.xyz2[l] = iteri->xyz[l]; + } + placeInSphere(bp.xyz2); + bp.sc2 = iteri->sc; + bp.multiplicity = degen; + + // Increment sph + sph->next(); + + // If sph is finished, then we reset it and increment iteri + if( sph->finished() ) + { + sph->rewind(); + ++iteri; + } + + return true; +} + +/* Place cartesian coordinates xyz in the location defined by the PointsInSphere + * iterator. + */ +void +SrReal::BondIterator:: +placeInSphere(float *xyz) +{ + float dxyz[3]; + for(size_t l=0; l<3; ++l) + { + dxyz[l] = sph->mno[l]; + } + crystal.FractionalToOrthonormalCoords(dxyz[0], dxyz[1], dxyz[2]); + for(size_t l=0; l<3; ++l) + { + xyz[l] += dxyz[l]; + } + return; +} + +/* Calculate the degeneracy of the ScatteringComponent */ +void +SrReal::BondIterator:: +calculateDegeneracy() +{ + degen = 0; + + if(sc == NULL) return; + + // Check if were dealing with 'P1' symmetry. If so, then we can speed this + // up a bit. + if(crystal.GetSpaceGroup().GetName() == ObjCryst::SpaceGroup().GetName()) + { + degen = 1; + return; + } + + // Count the scattering components in the unit cell that are identical to + // the sc. + for(iteri=sscvec.begin(); iteri != sscvec.end(); ++iteri) + { + if( (*(iteri->sc)) == *sc ) ++degen; + } +} + +/****************************************************************************** +***** ShiftedSC implementation ************************************************ +******************************************************************************/ + +ShiftedSC:: +ShiftedSC(const ObjCryst::ScatteringComponent *_sc, + const float x, const float y, const float z, const int _id) : + sc(_sc), id(_id) +{ + //sc->Print(); + xyz[0] = x; + xyz[1] = y; + xyz[2] = z; + //std::cout << x << ' ' << y << ' ' << z << endl; +} + +ShiftedSC:: +ShiftedSC(const ShiftedSC& _ssc) +{ + id = _ssc.id; + sc = _ssc.sc; + //sc->Print(); + xyz[0] = _ssc.xyz[0]; + xyz[1] = _ssc.xyz[1]; + xyz[2] = _ssc.xyz[2]; + //std::cout << x << ' ' << y << ' ' << z << endl; +} + +// Be careful of dangling references +ShiftedSC:: +ShiftedSC() +{ + xyz[0] = xyz[1] = xyz[2] = 0; + id = -1; + sc = NULL; +} + +bool +ShiftedSC:: +operator<(const ShiftedSC& rhs) const +{ + // The sign of A-B is equal the sign of the first non-zero component of the + // vector. + + size_t l; + + for(l = 0; l < 3; ++l) + { + if( fabs(xyz[l] - rhs.xyz[l]) > toler ) + { + return xyz[l] < rhs.xyz[l]; + } + } + if(sc == NULL or rhs.sc == NULL) return false; + + // If we get here then the vectors are equal. We compare the addresses of + // the ScatteringPower member of the ScatteringComponent + return sc->mpScattPow < rhs.sc->mpScattPow; + +} + +bool +ShiftedSC:: +operator==(const ShiftedSC& rhs) const +{ + + //std::cout << id << " vs " << rhs.id << endl; + + bool poseq = ((xyz[0] == rhs.xyz[0]) + && (xyz[1] == rhs.xyz[1]) + && (xyz[2] == rhs.xyz[2])); + + bool sceq; + if(sc == NULL or rhs.sc == NULL) sceq = true; + else sceq = (*sc == *(rhs.sc)); + + return poseq && sceq; +} + +/* Utility functions */ + +/* Get the conventional unit cell from the crystal. + */ +vector +SrReal:: +getUnitCell(const ObjCryst::Crystal& crystal) +{ + // Expand each scattering component in the primitive cell and record the new + // atoms. + const ObjCryst::ScatteringComponentList& mScattCompList + = crystal.GetScatteringComponentList(); + + size_t nbComponent = mScattCompList.GetNbComponent(); + + size_t nbSymmetrics = crystal.GetSpaceGroup().GetNbSymmetrics(); + //std::cout << "nbComponent = " << nbComponent << std::endl; + //std::cout << "nbSymmetrics = " << nbSymmetrics << std::endl; + + float x, y, z; + float junk; + CrystMatrix symmetricsCoords; + set workset; + vector workvec; + set::iterator it1; + ShiftedSC workssc; + // For each scattering component, find its position in the primitive cell + // and expand that position. Record this as a ShiftedSC. + // NOTE - I've also tried this algorithm by finding the unique elements in a + // vector. The speed of that method is comparable to this one. + for(size_t i=0;impScattPow->GetSymbol() << '(' << ssc.id << "): "; + os << ssc.xyz[0] << " "; + os << ssc.xyz[1] << " "; + os << ssc.xyz[2]; + return os; +} + +std::ostream& +SrReal::operator<<(ostream& os, const BondPair& bp) +{ + os << "(" << bp.multiplicity << ") "; + os << bp.sc1->mpScattPow->GetSymbol() << ' '; + os << "["; + os << bp.xyz1[0] << ", "; + os << bp.xyz1[1] << ", "; + os << bp.xyz1[2] << "]"; + os << " -- "; + os << bp.sc2->mpScattPow->GetSymbol() << ' '; + os << "["; + os << bp.xyz2[0] << ", "; + os << bp.xyz2[1] << ", "; + os << bp.xyz2[2] << "]"; + + return os; +} + diff --git a/libsrreal/bonditerator.h b/libsrreal/bonditerator.h new file mode 100644 index 00000000..097d0c04 --- /dev/null +++ b/libsrreal/bonditerator.h @@ -0,0 +1,257 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ + +#ifndef BONDITERATOR_H +#define BONDITERATOR_H + +#include +#include + +#include "ObjCryst/Crystal.h" +#include "ObjCryst/Scatterer.h" +#include "ObjCryst/General.h" +#include "PointsInSphere.h" + + +namespace SrReal +{ + +class ShiftedSC; +class BondPair; +class BondIterator; + +// Very useful utility function +std::vector getUnitCell(const ObjCryst::Crystal&); + +/* Container class for holding a "shifted" ScatteringComponent. It holds a + * reference to the ScatteringComponent and its shifted (Cartesian) position. + * This is used when expanding the scatterers in a crystal into the conventional + * unit cell. +*/ +class ShiftedSC +{ + + public: + ShiftedSC(const ObjCryst::ScatteringComponent* _sc, + const float x, const float y, const float z, const int _id = 0); + + ShiftedSC(const ShiftedSC& _ssc); + ShiftedSC(); + + /* Data members */ + + // Pointer to a ScatteringComponent + const ObjCryst::ScatteringComponent* sc; + + // Orthonormal coordinates + float xyz[3]; + + // Id for testing purposes + int id; + + /* Operators */ + + bool operator<(const ShiftedSC& rhs) const; + + // Compares equality. + bool operator==(const ShiftedSC& rhs) const; + + /* Friends */ + friend class BondIterator; + friend std::ostream& operator<<(ostream& os, const ShiftedSC& ssc); + +}; + +std::ostream& operator<<(ostream& os, const SrReal::ShiftedSC& ssc); + +/* Container class for holding bond pair information + * + * xyz are in cartesian coordinates. + */ +class BondPair +{ + public: + + BondPair() + { + for(size_t l = 0; l < 3; ++l) + { + xyz1[l] = xyz2[l] = 0; + } + sc1 = sc2 = NULL; + multiplicity = 0; + r = -1; + }; + + inline void setXYZ1(float* _xyz) + { + for(size_t l = 0; l < 3; ++l) xyz1[l] = _xyz[l]; + r = -1; + } + + inline void setXYZ1(size_t i, float val) + { + xyz1[i] = val; + r = -1; + } + + inline float* getXYZ1() { return xyz1; } + + inline float getXYZ1(size_t i) { return xyz1[i]; } + + inline void setXYZ2(float* _xyz) + { + for(size_t l = 0; l < 3; ++l) xyz2[l] = _xyz[l]; + r = -1; + } + + inline void setXYZ2(size_t i, float val) + { + xyz2[i] = val; + r = -1; + } + + inline float* getXYZ2() { return xyz2; } + + inline float getXYZ2(size_t i) { return xyz2[i]; } + + inline void setSC1(ObjCryst::ScatteringComponent* _sc1) { sc1 = _sc1; } + + inline const ObjCryst::ScatteringComponent* getSC1() { return sc1; } + + inline void setSC2(ObjCryst::ScatteringComponent* _sc2) { sc2 = _sc2; } + + inline const ObjCryst::ScatteringComponent* getSC2() { return sc2; } + + inline void setMultiplicity(size_t _m) { multiplicity = _m; } + + inline size_t getMultiplicity() { return multiplicity; } + + inline float getDistance() + { + if(r == -1) + { + r = 0; + for(size_t l = 0; l < 3; ++l) + { + r += pow(xyz1[l]-xyz2[l], 2); + } + r = sqrt(r); + } + return r; + } + + private: + // Cartesian coordinates of the scatterers + float xyz1[3]; + float xyz2[3]; + const ObjCryst::ScatteringComponent* sc1; + const ObjCryst::ScatteringComponent* sc2; + size_t multiplicity; + float r; + + /* Friends */ + friend class BondIterator; + friend std::ostream& operator<<(ostream& os, const BondPair& bp); + +}; + +std::ostream& operator<<(ostream& os, const SrReal::BondPair& bp); + +class BondIterator +{ + public: + + BondIterator(ObjCryst::Crystal& _crystal); + BondIterator(ObjCryst::Crystal& _crystal, float _rmin, float _rmax); + BondIterator(const BondIterator&); + + ~BondIterator(); + + // Set the range of the iterator + void setBondRange(float _rmin, float _rmax); + + // Set one scatterer in the bond + void setScatteringComponent(const ObjCryst::ScatteringComponent& _sc); + + // Rewind the iterator. This detects changes in the crystal and updates + // itself as necessary. + void rewind(); + + // Advance the iterator + void next(); + + // Check if the iterator is finished + bool finished(); + + // Get the current pair. + BondPair getBondPair(); + + // Get the crystal and bounds on the iterator + inline float getRmin() { return rmin; } + inline float getRmax() { return rmax; } + inline const ObjCryst::Crystal& getCrystal() { return crystal; } + + // Get the unit cell calculated internally + inline std::vector getUnitCell() { update(); return sscvec; } + + //FIXME:TESTING private: + + // Update the iterator + void update(); + + // Increment the iterator + bool increment(); + + // Check if the PointsInSphere is at 0, 0, 0 + inline bool sphAtOrigin() + { + return (sph->mno[0]==0 && sph->mno[1]==0 && sph->mno[2]==0); + } + + // Place cartesian coords in location defined by PointsInSphere iterator + void placeInSphere(float* xyz); + + // Calculate the degeneracy of the scattering component in the unit cell + void calculateDegeneracy(); + /**** Data members ****/ + + // Reference to crystal + const ObjCryst::Crystal& crystal; + + // Reference to one scattering component in the bond + const ObjCryst::ScatteringComponent* sc; + + // Minimum and maximum r values + float rmin; + float rmax; + + // For holding the current BondPair + BondPair bp; + + // flag indicating when we're finished. + bool isfinished; + + // Clock for comparing with scattering components + ObjCryst::RefinableObjClock itclock; + // Clock for comparing with lattice clock + ObjCryst::RefinableObjClock latclock; + + + // Holds ScatteringComponents in the primitive unit + std::vector sscvec; + // Iterators for punit and sunit; + std::vector::iterator iteri; + // degeneracy + size_t degen; + + // Points in sphere iterator + NS_POINTSINSPHERE::PointsInSphere* sph; + +}; + +} // end namespace SrReal + + +#endif diff --git a/libsrreal/bondwidthcalculator.cpp b/libsrreal/bondwidthcalculator.cpp new file mode 100644 index 00000000..6f663378 --- /dev/null +++ b/libsrreal/bondwidthcalculator.cpp @@ -0,0 +1,134 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ + +#include +#include "RefinableObj/RefinableObj.h" // From ObjCryst +#include "bondwidthcalculator.h" + +/* BondWidthCalculator */ +SrReal::BondWidthCalculator:: +BondWidthCalculator() : ObjCryst::RefinableObj() {} + +SrReal::BondWidthCalculator:: +~BondWidthCalculator() {} + +float +SrReal::BondWidthCalculator:: +calculate(SrReal::BondPair& bp) +{ + + float sigma; + sigma = bp.getSC1()->mpScattPow->GetBiso(); + sigma += bp.getSC2()->mpScattPow->GetBiso(); + + return sqrt(sigma/(8*M_PI*M_PI)); + +} + +/* JeongBWCalculator */ + +SrReal::JeongBWCalculator:: +JeongBWCalculator() +{ + delta1 = delta2 = qbroad = 0.0; + + ResetParList(); + + /* Create the RefinablePar objects for delta1 and delta2 */ + // delta1 + { + ObjCryst::RefinablePar* tmp = new ObjCryst::RefinablePar("delta1", &delta1, 0.0, 1.0, + &SrReal::bwrefpartype, ObjCryst::REFPAR_DERIV_STEP_ABSOLUTE, + false, false, true, false, 1.0, 1); + tmp->AssignClock(mClockMaster); + AddPar(tmp); + } + + // delta2 + { + ObjCryst::RefinablePar* tmp = new ObjCryst::RefinablePar("delta2", &delta2, 0.0, 1.0, + &SrReal::bwrefpartype, ObjCryst::REFPAR_DERIV_STEP_ABSOLUTE, + false, false, true, false, 1.0, 1); + tmp->AssignClock(mClockMaster); + AddPar(tmp); + } + + // qbroad + { + ObjCryst::RefinablePar* tmp = new ObjCryst::RefinablePar("qbroad", &qbroad, 0.0, 1.0, + &SrReal::bwrefpartype, ObjCryst::REFPAR_DERIV_STEP_ABSOLUTE, + false, false, true, false, 1.0, 1); + tmp->AssignClock(mClockMaster); + AddPar(tmp); + } +} + +SrReal::JeongBWCalculator:: +~JeongBWCalculator() +{} + +float +SrReal::JeongBWCalculator:: +calculate(SrReal::BondPair& bp) +{ + + // Only isotropic scattering factors are supported right now. Only one of + // delta1 or delta2 should be used. This is not enforced. + float r, sigma, corr; + sigma = SrReal::BondWidthCalculator::calculate(bp); + r = bp.getDistance(); + corr = 1.0 - delta1/r - delta2/(r*r) + pow(qbroad*r, 2); + if(corr > 0) + { + sigma *= sqrt(corr); + } + return sigma; +} + +float +SrReal::JeongBWCalculator:: +getDelta1() +{ + // Called this way in case the parameter is constrained + return GetPar(&delta1).GetValue(); +} + +float +SrReal::JeongBWCalculator:: +getDelta2() +{ + return GetPar(&delta2).GetValue(); +} + +float +SrReal::JeongBWCalculator:: +getQbroad() +{ + return GetPar(&qbroad).GetValue(); +} + +void +SrReal::JeongBWCalculator:: +setDelta1(float val) +{ + GetPar(&delta1).MutateTo(val); + return; +} + +void +SrReal::JeongBWCalculator:: +setDelta2(float val) +{ + GetPar(&delta2).MutateTo(val); + return; +} + +void +SrReal::JeongBWCalculator:: +setQbroad(float val) +{ + GetPar(&qbroad).MutateTo(val); + return; +} + diff --git a/libsrreal/bondwidthcalculator.h b/libsrreal/bondwidthcalculator.h new file mode 100644 index 00000000..568a30ea --- /dev/null +++ b/libsrreal/bondwidthcalculator.h @@ -0,0 +1,77 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ + +/* Calculators for bond widths. Each of these classes contains public data that + * tunes the calculation parameters of a peak width. The calculate function + * takes a SrReal::BondPair instance and returns a floating point number that + * in some cases represents sigma, the correlated Debye-Waller factor. + */ + +#ifndef BONDWIDTHCALCULATOR_H +#define BONDWIDTHCALCULATOR_H + +#include + +#include "bonditerator.h" +#include "RefinableObj/RefinableObj.h" // From ObjCryst + +namespace SrReal +{ + + +/* Base class for bond width calculators. + * + * This calculates the uncorrelated bond width from the Biso values of the + * constituents. This class is derived from ObjCryst::RefinableObj so that we + * can make use of the ObjCryst clock mechanism. + */ +class BondWidthCalculator + : public ObjCryst::RefinableObj +{ + + public: + BondWidthCalculator(); + virtual ~BondWidthCalculator(); + + // Returns the bond width in angstroms + virtual float calculate(SrReal::BondPair& bp); +}; + +/* Bond width calculator using the formula from I.-K. Jeong, et al., Phys. Rev. + * B 67, 104301 (2003) + */ +class JeongBWCalculator + : public BondWidthCalculator +{ + + public: + JeongBWCalculator(); + virtual ~JeongBWCalculator(); + + virtual float calculate(SrReal::BondPair& bp); + + float getDelta1(); + float getDelta2(); + float getQbroad(); + void setDelta1(float val); + void setDelta2(float val); + void setQbroad(float val); + + protected: + + /* Refinable parameters */ + // These are accessible through the refinable parameter interface inherited + // from RefinableObj. + float delta1; // The low-temperature coefficient (of 1/r) + float delta2; // The high-temperature coefficient (of 1/r^2) + float qbroad; // A resolution-based broadening factor + +}; + +// Refinable parameter type for BondWidthCalculator parameters +const ObjCryst::RefParType bwrefpartype(string("bwrefpartype")); + +} // end namespace SrReal + +#endif // BONDWIDTHCALCULATOR_H diff --git a/libsrreal/pdfcalculator.cpp b/libsrreal/pdfcalculator.cpp new file mode 100644 index 00000000..ce293694 --- /dev/null +++ b/libsrreal/pdfcalculator.cpp @@ -0,0 +1,764 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ + +#include +#include +#include +#include + +#include "profilecalculator.h" +#include "pdfcalculator.h" + +/****************************************************************************/ + +namespace { + + const float sqrt2pi = sqrt(2*M_PI); + const float eps = 1e-8; +} + +SrReal::PDFCalculator:: +PDFCalculator( + SrReal::BondIterator& _bonditer, SrReal::BondWidthCalculator& _bwcalc) + : SrReal::ProfileCalculator(_bonditer, _bwcalc), + crystal(_bonditer.getCrystal()) +{ + rdf = pdf = NULL; + ffta = NULL; + cnumpoints = 0; + crmin = crmax = cdr = 0; + bavg = 0; + numscat = 0; + qmaxidxlo = qmaxidxhi = qminidxhi = 0; + recalc = true; + + bwclock.Reset(); + latclock.Reset(); + slclock.Reset(); + scatclocks.resize(crystal.GetNbScatterer()); + for(int i=0; iAssignClock(mClockMaster); + AddPar(tmp); + } + + // scale + { + ObjCryst::RefinablePar* tmp = new ObjCryst::RefinablePar("scale", &scale, 0.0, 1.0, + &SrReal::profilerefpartype, ObjCryst::REFPAR_DERIV_STEP_ABSOLUTE, + false, false, true, false, 1.0, 1); + tmp->AssignClock(mClockMaster); + AddPar(tmp); + } + + /* Add all parameters from the crystal and bond width calculator. This will + * make it easier to save and restore their values. + */ + AddPar(bwcalc); + AddPar(const_cast(crystal)); + for(int l=0; l(scat)); + } + + // Free these + UnFixAllPar(); + + // Print for fun + //for(int i=0; i changeidx; + //std::cout << "-- Initial --" << std::endl; + for(int i=0; i (size_t) crystal.GetNbScatterer() ) + { + calculateRDF(); + return; + } + + /* For each altered scatterer, add the contributions from its scattering + * components and subtract those from the previous time step. + */ + calcAvgScatPow(); + // Add current contribution + for(size_t l=0; l( (grmin - crmin)/cdr ); + gimax = static_cast( (grmax - crmin)/cdr ); + assert(gimin <= cnumpoints); + assert(gimax <= cnumpoints); + for(size_t l=gimin; l 0 ) + { + + // zero high Q components in ffta + for (size_t i = qmaxidxlo; i < qmaxidxhi; ++i) + { + ffta[2*i] = ffta[2*i+1] = 0.0; + } + } + + if( qmin > 0) + { + // zero low Q components in ffta + for (size_t i = 0; i < qminidxhi; ++i) + { + ffta[2*i] = ffta[2*i+1] = 0.0; + } + } + + // transform back + fftstatus = gsl_fft_complex_radix2_inverse(ffta, 1, fftlen); + + if (fftstatus != GSL_SUCCESS) + { + // FIXME should be exception + std::cerr << "Inverse FFT failed!"; + exit(1); + } + } + + return; +} + +void +SrReal::PDFCalculator:: +calcAvgScatPow() { + + std::vector unitcell = bonditer.getUnitCell(); + std::vector::iterator it1; + + bavg = 0.0; + numscat = 0.0; + + for(it1 = unitcell.begin(); it1 != unitcell.end(); ++it1) + { + numscat += it1->sc->mOccupancy; + bavg += it1->sc->mpScattPow->GetForwardScatteringFactor(radtype) * + it1->sc->mOccupancy; + } + bavg /= numscat; + //std::cout << "numscat = " << numscat << std::endl; + //std::cout << "cell size = " << unitcell.size() << std::endl; + return; +} + +float +SrReal::PDFCalculator:: +getPairScatPow(SrReal::BondPair &bp) +{ + float scatpow = 1; + scatpow *= bp.getSC1()->mpScattPow->GetForwardScatteringFactor(radtype); + scatpow *= bp.getSC1()->mOccupancy; + scatpow *= bp.getSC2()->mpScattPow->GetForwardScatteringFactor(radtype); + scatpow *= bp.getSC2()->mOccupancy; + + return scatpow; +} + +// Calculate the diameter of the sphere that can encompass the crystal. +float +SrReal::PDFCalculator:: +phaseDiameter() const +{ + float center[3] = {0.0, 0.0, 0.0}; + std::vector unitcell = bonditer.getUnitCell(); + float d = 0, maxd = 0; + + for(size_t i=0; i < unitcell.size(); ++i) + { + for(size_t j=0; j<3; ++j) + { + center[j] += unitcell[i].xyz[j] / unitcell.size(); + } + } + for(size_t i=0; i < unitcell.size(); ++i) + { + d = 0; + for(int j=0; j<3; ++j) + { + d += pow(center[j]-unitcell[i].xyz[j], 2); + } + maxd = (d > maxd ? d : maxd); + } + return 2*sqrt(maxd); +} + + + diff --git a/libsrreal/pdfcalculator.h b/libsrreal/pdfcalculator.h new file mode 100644 index 00000000..7b5b086f --- /dev/null +++ b/libsrreal/pdfcalculator.h @@ -0,0 +1,155 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ + +#ifndef PDFCALCULATOR_H +#define PDFCALCULATOR_H + +#include + +#include "profilecalculator.h" +#include "bonditerator.h" +#include "bondwidthcalculator.h" + +#include "ObjCryst/Crystal.h" +#include "ObjCryst/Scatterer.h" +#include "ObjCryst/General.h" +#include "ObjCryst/Crystal.h" +#include "RefinableObj/RefinableObj.h" // From ObjCryst + +namespace SrReal +{ + +/* Implementation of ProfileCalculator virtual class. This calculator is meant + * for crystal systems where periodic boundary conditions are enforced on the + * unit cell. + * + */ + +class PDFCalculator : public SrReal::ProfileCalculator +{ + public: + + PDFCalculator( + SrReal::BondIterator& _bonditer, + SrReal::BondWidthCalculator& _bwcalc); + virtual ~PDFCalculator(); + + /* Defined in ProfileCalculator + * virtual void setScatType(const ObjCryst::RadiationType _rt); + * virtual ObjCryst::RadiationType getScatType(); + * virtual const float* getCalculationPoints(); + * virtual size_t getNumPoints(); // The number of calculation points + * virtual float getQmax(); + * virtual float getQmin(); + */ + + /* Overloaded from ProfileCalculator */ + // Set the calculation points and determine the internal calculation points + virtual void setCalculationPoints( + const float* _rvals, const size_t _numpoints); + // Set the maximum Q value + virtual void setQmax(float val); + // Set the minimum Q value + virtual void setQmin(float val); + + // Get the RDF over the requested calculation points + virtual float* getPDF(); + // Get the RDF over the requested calculation points + virtual float* getRDF(); + + private: + + /* Defined in ProfileCalculator + * SrReal::BondIterator& bonditer; + * SrReal::BondWidthCalculator& bwcalc; + * ObjCryst::RadiationType radtype; + * float *rvals; + * size_t numpoints; + * float qmin, qmax; + */ + + // Calculate the RDF over the internal calculation range from scratch. This + // is extended beyond the requested calculation range so peaks centered + // outside of the calculation range that overlap with the calculation range + // are included. + void calculateRDF(); + // Add contributions to the RDF from a ObjCryst::ScatteringComponentList + void buildRDF(const ObjCryst::ScatteringComponentList &scl, float pref); + // Update the RDF. This checks for changes in the parameters and then either + // reshapes the RDF or recalculates it. + void updateRDF(); + // Reshape the RDF by adding changes in scattering components. + void reshapeRDF(); + // Calculate the PDF over the internal calculation range. + void calculatePDF(); + + // Add a gaussian to the rdf + void addGaussian(float d, float sigma, float amp); + // Calculate the average scattering power in the unit cell + void calcAvgScatPow(); + // Get the scattering power of a pair of scatterers + float getPairScatPow(SrReal::BondPair &bp); + // Get the corrected profile + float* getCorrectedProfile(float* df); + // Apply termination ripples + void applyTerminationRipples(); + // Setup the FFT for termination ripples + void setupFFT(); + // Calculate the diameter of the sphere that can encompass the crystal. + float phaseDiameter() const; + + /* Clocks for tracking changes */ + // Compare this clock with the crystal lattice + ObjCryst::RefinableObjClock latclock; + // Compare this clock with the scattering list clock + ObjCryst::RefinableObjClock slclock; + // Compare this clock with the bond width calculator + ObjCryst::RefinableObjClock bwclock; + // These compare with the scatterers + std::vector scatclocks; + + // flag for recalculation + bool recalc; + + // handle to the crystal + const ObjCryst::Crystal &crystal; + + /* Refinable parameters */ + // These are accessible through the refinable parameter interface inherited + // from RefinableObj + float qdamp; + float scale; + + /* Data */ + + // RDF without resolution or qmax corrections + float *rdf; + // PDF without resolution or qmax corrections + float *pdf; + // array for computing fft for termination ripples + double *ffta; + size_t fftlen; + size_t qmaxidxlo; + size_t qmaxidxhi; + size_t qminidxhi; + + // For the internal calculation range + size_t cnumpoints; + float crmin; + float crmax; + float cdr; + + // The average scattering power in the unit cell + float bavg; + // The number of scatterers in the unit cell, calculated from occupancy + float numscat; + + // Ids for accessing saved crystal parameters + size_t lastsave; + size_t cursave; + +}; + +} +#endif diff --git a/libsrreal/profilecalculator.cpp b/libsrreal/profilecalculator.cpp new file mode 100644 index 00000000..24ba6644 --- /dev/null +++ b/libsrreal/profilecalculator.cpp @@ -0,0 +1,118 @@ +/*********************************************************************** +* $Id$ +***********************************************************************/ + +#include "profilecalculator.h" + +#include "ObjCryst/General.h" + +SrReal::ProfileCalculator:: +ProfileCalculator( + SrReal::BondIterator& _bonditer, + SrReal::BondWidthCalculator& _bwcalc) : + ObjCryst::RefinableObj(), bonditer(_bonditer), bwcalc(_bwcalc) +{ + rvals = NULL; + numpoints = 0; + qmin = qmax = 0.0; + radtype = ObjCryst::RAD_XRAY; +} + +SrReal::ProfileCalculator:: +~ProfileCalculator() +{ + if( rvals != NULL ) + { + delete [] rvals; + } + +} + +SrReal::BondIterator& +SrReal::ProfileCalculator:: +getBondIterator() +{ + return bonditer; +} + +SrReal::BondWidthCalculator& +SrReal::ProfileCalculator:: +getBondWidthCalculator() +{ + return bwcalc; +} + +void +SrReal::ProfileCalculator:: +setScatType(ObjCryst::RadiationType _radtype) +{ + radtype = _radtype; +} + +ObjCryst::RadiationType +SrReal::ProfileCalculator:: +getScatType() +{ + return radtype; +} + +void +SrReal::ProfileCalculator:: +setCalculationPoints( + const float* _rvals, const size_t _numpoints) +{ + // make space for the copies + if( rvals != NULL ) + { + delete [] rvals; + } + + numpoints = _numpoints; + rvals = new float[numpoints]; +} + +// This may return NULL! +const float* +SrReal::ProfileCalculator:: +getCalculationPoints() +{ + return rvals; +} + +size_t +SrReal::ProfileCalculator:: +getNumPoints() +{ + return numpoints; +} + + +void +SrReal::ProfileCalculator:: +setQmax(float val) +{ + qmax = (val > 0 ? val : 0); +} + +float +SrReal::ProfileCalculator:: +getQmax() +{ + return qmax; +} + +void +SrReal::ProfileCalculator:: +setQmin(float val) +{ + qmin = (val > 0 ? val : 0); +} + +float +SrReal::ProfileCalculator:: +getQmin() +{ + return qmin; +} + + diff --git a/libsrreal/profilecalculator.h b/libsrreal/profilecalculator.h new file mode 100644 index 00000000..cd8c2bd8 --- /dev/null +++ b/libsrreal/profilecalculator.h @@ -0,0 +1,64 @@ +#ifndef PROFILECALCULATOR_H +#define PROFILECALCULATOR_H + +#include "bonditerator.h" +#include "bondwidthcalculator.h" + +#include "ObjCryst/Crystal.h" +#include "ObjCryst/Scatterer.h" +#include "ObjCryst/General.h" +#include "ObjCryst/Crystal.h" +#include "RefinableObj/RefinableObj.h" // From ObjCryst + +namespace SrReal +{ + +/* Virtual base class for real space profile calculation. All PDF and RDF + * calculators need this basic functionality + */ + +class ProfileCalculator : public ObjCryst::RefinableObj +{ + public: + + ProfileCalculator( + SrReal::BondIterator& _bonditer, + SrReal::BondWidthCalculator& _bwcalc); + virtual ~ProfileCalculator(); + + virtual SrReal::BondIterator& getBondIterator(); + virtual SrReal::BondWidthCalculator& getBondWidthCalculator(); + + // Calculation setup + virtual void setScatType(const ObjCryst::RadiationType _radtype); + virtual ObjCryst::RadiationType getScatType(); + virtual void setCalculationPoints( + const float* _rvals, const size_t _numpoints); // copies _rvals + virtual const float* getCalculationPoints(); + virtual size_t getNumPoints(); // The number of calculation points + virtual void setQmax(float val); + virtual float getQmax(); + virtual void setQmin(float val); + virtual float getQmin(); + + // Related to calculation + virtual float* getPDF() = 0; + virtual float* getRDF() = 0; + + protected: + + // Data necessary for the above functions + SrReal::BondIterator& bonditer; + SrReal::BondWidthCalculator& bwcalc; + ObjCryst::RadiationType radtype; + float *rvals; + size_t numpoints; + float qmin, qmax; + +}; + +// Refinable parameter type for ProfileCalculator parameters +const ObjCryst::RefParType profilerefpartype(string("profilerefpartype")); + +} +#endif diff --git a/libsrreal/testsrreal.cpp b/libsrreal/testsrreal.cpp new file mode 100644 index 00000000..d45da7d8 --- /dev/null +++ b/libsrreal/testsrreal.cpp @@ -0,0 +1,198 @@ +#include "bonditerator.h" +#include "pdfcalculator.h" + +#include "ObjCryst/Crystal.h" // From ObjCryst distribution +#include "ObjCryst/Atom.h" // From ObjCryst distribution +#include "ObjCryst/ScatteringPower.h" // From ObjCryst distribution + +#include +#include + +using namespace std; +using namespace SrReal; + +// FIXME + +ObjCryst::Crystal* makeNi() +{ + // Create the Ni structure + ObjCryst::Crystal* crystal = new ObjCryst::Crystal(3.52, 3.52, 3.52, "225"); + ObjCryst::ScatteringPowerAtom* sp + = new ObjCryst::ScatteringPowerAtom("Ni", "Ni"); + sp->SetBiso(8*M_PI*M_PI*0.003); + // Atoms only belong to one crystal. They must be allocated in the heap. + ObjCryst::Atom *atomp = new ObjCryst::Atom(0.0, 0.0, 0.0, "Ni", sp); + crystal->AddScatterer(atomp); + crystal->AddScatteringPower(sp); + return crystal; +} + +ObjCryst::Crystal* makeLaMnO3() +{ + ObjCryst::Crystal* crystal = + new ObjCryst::Crystal(5.486341, 5.619215, 7.628206, 90, 90, 90, "P b n m"); + ObjCryst::ScatteringPowerAtom* sp; + ObjCryst::Atom *atomp; + // Add the atoms + // La1 + sp = new ObjCryst::ScatteringPowerAtom("La1", "La"); + sp->SetBiso(8*M_PI*M_PI*0.003); + atomp = new ObjCryst::Atom(0.996096, 0.0321494, 0.25, "La1", sp); + crystal->AddScatterer(atomp); + crystal->AddScatteringPower(sp); + // Mn1 + sp = new ObjCryst::ScatteringPowerAtom("Mn1", "Mn"); + sp->SetBiso(8*M_PI*M_PI*0.003); + atomp = new ObjCryst::Atom(0, 0.5, 0, "Mn1", sp); + crystal->AddScatterer(atomp); + crystal->AddScatteringPower(sp); + // O1 + sp = new ObjCryst::ScatteringPowerAtom("O1", "O"); + sp->SetBiso(8*M_PI*M_PI*0.003); + atomp = new ObjCryst::Atom(0.0595746, 0.496164, 0.25, "O1", sp); + crystal->AddScatterer(atomp); + crystal->AddScatteringPower(sp); + // O2 + sp = new ObjCryst::ScatteringPowerAtom("O2", "O"); + sp->SetBiso(8*M_PI*M_PI*0.003); + atomp = new ObjCryst::Atom(0.720052, 0.289387, 0.0311126, "O2", sp); + crystal->AddScatterer(atomp); + crystal->AddScatteringPower(sp); + + return crystal; +} + +ObjCryst::Crystal* makeZnS() +{ + // Create the ZnS structure + ObjCryst::Crystal* crystal + = new ObjCryst::Crystal(3.811, 3.811, 6.234, 90, 90, 120, "P 63 m c"); + ObjCryst::ScatteringPowerAtom* zsp + = new ObjCryst::ScatteringPowerAtom("Zn", "Zn"); + ObjCryst::ScatteringPowerAtom* ssp + = new ObjCryst::ScatteringPowerAtom("S", "S"); + ObjCryst::ScatteringPowerAtom* csp + = new ObjCryst::ScatteringPowerAtom("C", "C"); + zsp->SetBiso(8*M_PI*M_PI*0.003); + ssp->SetBiso(8*M_PI*M_PI*0.003); + csp->SetBiso(8*M_PI*M_PI*0.003); + // Atoms only belong to one crystal. They must be allocated in the heap. + ObjCryst::Atom *zatomp = + new ObjCryst::Atom(1.0/3, 2.0/3, 0.0, "Zn", zsp); + ObjCryst::Atom *satomp = + new ObjCryst::Atom(1.0/3, 2.0/3, 0.385, "S", ssp, 1); + ObjCryst::Atom *catomp = + new ObjCryst::Atom(1.0/3, 2.0/3, 0.385, "C", csp, 0); + crystal->AddScatterer(zatomp); + crystal->AddScatterer(satomp); + crystal->AddScatterer(catomp); + return crystal; +} + +ObjCryst::Crystal* makeCaF2() +{ + // Create the ZnS structure + ObjCryst::Crystal* crystal + = new ObjCryst::Crystal(5.4625, 5.4625, 5.4625, 90, 90, 120, "F m -3 m"); + ObjCryst::ScatteringPowerAtom* casp + = new ObjCryst::ScatteringPowerAtom("Ca", "Ca"); + ObjCryst::ScatteringPowerAtom* fsp + = new ObjCryst::ScatteringPowerAtom("F", "F"); + casp->SetBiso(8*M_PI*M_PI*0.003); + fsp->SetBiso(8*M_PI*M_PI*0.003); + // Atoms only belong to one crystal. They must be allocated in the heap. + ObjCryst::Atom *caatomp = + new ObjCryst::Atom(0, 0, 0, "Ca", casp); + ObjCryst::Atom *fatomp = + new ObjCryst::Atom(0.25, 0.25, 0.25, "F", fsp); + crystal->AddScatterer(caatomp); + crystal->AddScatterer(fatomp); + return crystal; +} + +void calculateTest( ObjCryst::Crystal* (*f)() ) +{ + + ObjCryst::Crystal& crystal = *(f()); + + // Create the calculation points + float rmin, rmax, dr; + rmin = 0; + rmax = 10; + dr = 0.01; + size_t numpoints = static_cast(ceil((rmax-rmin)/dr)); + float *rvals = new float [numpoints]; + for(size_t i=0; i(ceil((rmax-rmin)/dr)); + float *rvals = new float [numpoints]; + for(size_t i=0; i - -**Changed:** - -* - -**Deprecated:** - -* - -**Removed:** - -* - -**Fixed:** - -* - -**Security:** - -* diff --git a/news/ay-cleanings.rst b/news/ay-cleanings.rst deleted file mode 100644 index b074e5a1..00000000 --- a/news/ay-cleanings.rst +++ /dev/null @@ -1,23 +0,0 @@ -**Added:** - -* No news added: one small typo fix - -**Changed:** - -* - -**Deprecated:** - -* - -**Removed:** - -* - -**Fixed:** - -* - -**Security:** - -* diff --git a/news/citationfix.rst b/news/citationfix.rst deleted file mode 100644 index ea0ce460..00000000 --- a/news/citationfix.rst +++ /dev/null @@ -1,23 +0,0 @@ -**Added:** - -* Update citation reference in README and docs. - -**Changed:** - -* - -**Deprecated:** - -* - -**Removed:** - -* - -**Fixed:** - -* - -**Security:** - -* diff --git a/news/deprecate-setscattering.rst b/news/deprecate-setscattering.rst deleted file mode 100644 index a010e6b4..00000000 --- a/news/deprecate-setscattering.rst +++ /dev/null @@ -1,23 +0,0 @@ -**Added:** - -* - -**Changed:** - -* - -**Deprecated:** - -* Deprecated setScatteringFactorTableByType. - -**Removed:** - -* - -**Fixed:** - -* - -**Security:** - -* diff --git a/news/devutils.rst b/news/devutils.rst deleted file mode 100644 index 7c8fd417..00000000 --- a/news/devutils.rst +++ /dev/null @@ -1,23 +0,0 @@ -**Added:** - -* - -**Changed:** - -* - -**Deprecated:** - -* - -**Removed:** - -* Remove utils scripts ``devutils`` from the package. - -**Fixed:** - -* - -**Security:** - -* diff --git a/news/examples.rst b/news/examples.rst deleted file mode 100644 index cafcc660..00000000 --- a/news/examples.rst +++ /dev/null @@ -1,23 +0,0 @@ -**Added:** - -* - -**Changed:** - -* - -**Deprecated:** - -* - -**Removed:** - -* - -**Fixed:** - -* Fixed `parallelPDF.py` example multiprocessing safe importing of main module issue. - -**Security:** - -* diff --git a/news/wf.rst b/news/wf.rst deleted file mode 100644 index 2e17320d..00000000 --- a/news/wf.rst +++ /dev/null @@ -1,23 +0,0 @@ -**Added:** - -* No news: workflow changes. - -**Changed:** - -* - -**Deprecated:** - -* - -**Removed:** - -* - -**Fixed:** - -* - -**Security:** - -* diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 840710d8..00000000 --- a/pyproject.toml +++ /dev/null @@ -1,85 +0,0 @@ -[build-system] -requires = ["setuptools>=62.0", "setuptools-git-versioning>=2.0", "numpy"] -build-backend = "setuptools.build_meta" - -[project] -name = "diffpy.srreal" -dynamic=['version', 'dependencies'] -authors = [ - { name="Simon Billinge", email="sb2896@columbia.edu" }, -] -maintainers = [ - { name="Simon Billinge", email="sb2896@columbia.edu" }, -] -description = "Calculators for PDF, bond valence sum, and other quantities based on atom pair interaction." -keywords = ['PDF', 'BVS', 'atom', 'overlap', 'calculator', 'real-space'] -readme = "README.rst" -requires-python = ">=3.11, <3.14" -classifiers = [ - 'Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Intended Audience :: Developers', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: BSD License', - 'Operating System :: MacOS :: MacOS X', - 'Operating System :: Microsoft :: Windows', - 'Operating System :: POSIX', - 'Operating System :: Unix', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'Programming Language :: Python :: 3.13', - 'Topic :: Scientific/Engineering :: Physics', - 'Topic :: Scientific/Engineering :: Chemistry', -] - -[project.urls] -Homepage = "https://github.com/diffpy/diffpy.srreal/" -Issues = "https://github.com/diffpy/diffpy.srreal/issues/" - -[tool.setuptools-git-versioning] -enabled = true -template = "{tag}" -dev_template = "{tag}" -dirty_template = "{tag}" - -[tool.setuptools.packages.find] -where = ["src"] # list of folders that contain the packages (["."] by default) -include = ["*"] # package names should match these glob patterns (["*"] by default) -exclude = [] # exclude packages matching these glob patterns (empty by default) -namespaces = false # to disable scanning PEP 420 namespaces (true by default) - -[tool.setuptools.dynamic] -dependencies = {file = ["requirements/pip.txt"]} - -[tool.codespell] -exclude-file = ".codespell/ignore_lines.txt" -ignore-words = ".codespell/ignore_words.txt" -skip = "*.cif,*.dat" - -[tool.docformatter] -recursive = true -wrap-summaries = 72 -wrap-descriptions = 72 - -[tool.black] -line-length = 79 -include = '\.pyi?$' -exclude = ''' -/( - \.git - | \.hg - | \.mypy_cache - | \.tox - | \.venv - | \.rst - | \.txt - | _build - | buck-out - | build - | dist - - # The following are specific to Black, you probably don't want those. - | blib2to3 - | tests/data -)/ -''' diff --git a/requirements/build.txt b/requirements/build.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/requirements/conda.txt b/requirements/conda.txt deleted file mode 100644 index 0f11dbec..00000000 --- a/requirements/conda.txt +++ /dev/null @@ -1,6 +0,0 @@ -libdiffpy -libboost-devel -libobjcryst -pyobjcryst -diffpy.structure -periodictable diff --git a/requirements/docs.txt b/requirements/docs.txt deleted file mode 100644 index 5f34c6ed..00000000 --- a/requirements/docs.txt +++ /dev/null @@ -1,5 +0,0 @@ -sphinx -sphinx_rtd_theme -sphinx-copybutton -doctr -m2r diff --git a/requirements/pip.txt b/requirements/pip.txt deleted file mode 100644 index a85739ed..00000000 --- a/requirements/pip.txt +++ /dev/null @@ -1,2 +0,0 @@ -setuptools -numpy diff --git a/requirements/tests.txt b/requirements/tests.txt deleted file mode 100644 index a7277865..00000000 --- a/requirements/tests.txt +++ /dev/null @@ -1,6 +0,0 @@ -flake8 -pytest -codecov -coverage -pytest-cov -pytest-env diff --git a/setup.py b/setup.py deleted file mode 100644 index ab1f8587..00000000 --- a/setup.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env python - -"""diffpy.srreal - calculators for PDF, bond valence sum, and other -quantities based on atom pair interaction. - -Packages: diffpy.srreal -""" - -import glob -import os -import sys -from ctypes.util import find_library -from pathlib import Path - -import numpy -from setuptools import Extension, setup - - -def get_boost_libraries(): - major, minor = sys.version_info[:2] - candidates = [ - f"boost_python{major}{minor}", - f"boost_python{major}", - "boost_python", - ] - - conda_prefix = os.environ.get("CONDA_PREFIX") - if conda_prefix: - libdir = os.path.join(conda_prefix, "lib") - for name in candidates: - so = f"lib{name}.so" - if os.path.isfile(os.path.join(libdir, so)): - return [name] - - # fallback to ldconfig - for name in candidates: - found = find_library(name) - if found: - return [name] - raise RuntimeError("Cannot find a suitable Boost.Python library.") - - -def get_boost_config(): - boost_path = os.environ.get("BOOST_PATH", "") - if boost_path: - inc = Path(boost_path) / "include" - lib = Path(boost_path) / "lib" - else: - conda_prefix = os.environ.get("CONDA_PREFIX") - if not conda_prefix: - raise EnvironmentError( - "Neither BOOST_PATH nor CONDA_PREFIX are set. " - "Please install Boost or set BOOST_PATH." - ) - if os.name == "nt": - inc = Path(conda_prefix) / "Library" / "include" - lib = Path(conda_prefix) / "Library" / "lib" - else: - inc = Path(conda_prefix) / "include" - lib = Path(conda_prefix) / "lib" - return {"include_dirs": [str(inc)], "library_dirs": [str(lib)]} - - -def get_objcryst_libraries(): - conda_prefix = os.environ.get("CONDA_PREFIX") - if not conda_prefix: - raise EnvironmentError( - "CONDA_PREFIX is not set. " - "Please install ObjCryst using conda and activate the environment." - ) - if os.name == "nt": - libdir = Path(conda_prefix) / "Library" / "lib" - else: - libdir = Path(conda_prefix) / "lib" - - libs = [] - for fn in os.listdir(libdir): - stem = Path(fn).stem - if "objcryst" not in stem.lower(): - continue - # strip a leading "lib" - # so that setuptools does -lObjCryst, not -llibObjCryst - if os.name != "nt" and stem.startswith("lib"): - stem = stem[3:] - libs.append(stem) - - if not libs: - raise RuntimeError(f"No ObjCryst libraries found in {libdir}") - return libs - - -if os.name == "nt": - compile_args = ["/std:c++14"] - macros = [("_USE_MATH_DEFINES", None)] - extra_link_args = ["/FORCE:MULTIPLE"] -else: - compile_args = ["-std=c++11"] - macros = [] - extra_link_args = [] - -boost_cfg = get_boost_config() -objcryst_libs = get_objcryst_libraries() - -ext_kws = { - "libraries": ["diffpy"] + get_boost_libraries() + objcryst_libs, - "extra_compile_args": compile_args, - "extra_link_args": extra_link_args, - "include_dirs": [numpy.get_include()] + boost_cfg["include_dirs"], - "library_dirs": boost_cfg["library_dirs"], - # "runtime_library_dirs": boost_cfg["library_dirs"], - "define_macros": macros, -} - - -def create_extensions(): - "Initialize Extension objects for the setup function." - ext = Extension( - "diffpy.srreal.srreal_ext", - glob.glob("src/extensions/*.cpp"), - **ext_kws, - ) - return [ext] - - -# Extensions not included in pyproject.toml -def ext_modules(): - if set(sys.argv) & {"build_ext", "bdist_wheel", "install"}: - return create_extensions() - return [] - - -if __name__ == "__main__": - setup(ext_modules=ext_modules()) diff --git a/src/diffpy/__init__.py b/src/diffpy/__init__.py deleted file mode 100644 index 67de5256..00000000 --- a/src/diffpy/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# (c) 2025 The Trustees of Columbia University in the City of New York. -# All rights reserved. -# -# File coded by: Billinge Group members and community contributors. -# -# See GitHub contributions for a more detailed list of contributors. -# https://github.com/diffpy/diffpy.srreal/graphs/contributors -# -# See LICENSE.rst for license information. -# -############################################################################## -"""Blank namespace package for module diffpy.""" - - -from pkgutil import extend_path - -__path__ = extend_path(__path__, __name__) - -# End of file diff --git a/src/diffpy/srreal/__init__.py b/src/diffpy/srreal/__init__.py deleted file mode 100644 index 2beff97f..00000000 --- a/src/diffpy/srreal/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# (c) 2025 The Trustees of Columbia University in the City of New York. -# All rights reserved. -# -# File coded by: Billinge Group members and community contributors. -# -# See GitHub contributions for a more detailed list of contributors. -# https://github.com/diffpy/diffpy.srreal/graphs/contributors -# -# See LICENSE.rst for license information. -# -############################################################################## -"""Tools for real space structure analysis.""" - -# package version -from diffpy.srreal.version import __version__ - -# silence the pyflakes syntax checker -assert __version__ or True - -# End of file diff --git a/src/diffpy/srreal/_cleanup.py b/src/diffpy/srreal/_cleanup.py deleted file mode 100644 index 19fdffd2..00000000 --- a/src/diffpy/srreal/_cleanup.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal Complex Modeling Initiative -# (c) 2016 Brookhaven Science Associates, -# Brookhaven National Laboratory. -# All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE.txt for license information. -# -############################################################################## -"""Cancel registration of Python-extended C++ classes when Python exits. - -Note ----- -Python finishes before the shared library libdiffpy, but the registry of -class prototypes is implemented in libdiffpy. Any Python-extended classes -thus need to be removed from the registry prior to Python exit. - -This module is not intended for direct use. It is used implicitly within -a call of _registerThisType. -""" - - -import atexit -import weakref - -# Routine to be used from srreal_ext module ---------------------------------- - - -def registerForCleanUp(obj): - """Remember to clean up the specified prototype at Python exit. - - Parameters - ---------- - obj : wrapped class that has class registry - This is an object being added to the C++ registry of prototypes. - If active at Python exit, the associated string type will be - removed from the class registry. - - No return value. - """ - _cleanup_handler.add(obj) - return - - -# ---------------------------------------------------------------------------- - - -class _DerivedClassesCleanUpHandler(object): - - def __init__(self): - self._references = set() - return - - def add(self, obj): - wr = weakref.ref(obj) - self._references.add(wr) - return - - def clean(self): - while self._references: - wr = self._references.pop() - obj = wr() - if obj is not None: - obj._deregisterType(obj.type()) - return - - -# end of class _DerivedClassesCleanUpHandler - - -# create singleton instance of the cleanup handler -_cleanup_handler = _DerivedClassesCleanUpHandler() -atexit.register(_cleanup_handler.clean) - -del _DerivedClassesCleanUpHandler - -# End of file. diff --git a/src/diffpy/srreal/_docstrings.py b/src/diffpy/srreal/_docstrings.py deleted file mode 100644 index a743a985..00000000 --- a/src/diffpy/srreal/_docstrings.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal Complex Modeling Initiative -# (c) 2016 Brookhaven Science Associates, -# Brookhaven National Laboratory. -# All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE.txt for license information. -# -############################################################################## -"""Docstrings for classes and functions in srreal_ext module.""" - -# Shared docstrings for classes derived from HasClassRegistry ---------------- - - -def get_registry_docstrings(cls): - """Build a dictionary of docstrings per each HasClassRegistry - method. - - Parameters - ---------- - cls : class type that is wrapped - This parameter is used to extract the class name and substitute - it in the docstrings template. - - Returns a dictionary mapping Python method names to their docstrins. - """ - n = cls.__name__ - rv = { - k: v.replace("@NAME@", n) - for k, v in ( - ("create", doc_HasClassRegistry_create), - ("clone", doc_HasClassRegistry_clone), - ("type", doc_HasClassRegistry_type), - ("_registerThisType", doc_HasClassRegistry__registerThisType), - ("_aliasType", doc_HasClassRegistry__aliasType), - ("_deregisterType", doc_HasClassRegistry__deregisterType), - ("createByType", doc_HasClassRegistry_createByType), - ("isRegisteredType", doc_HasClassRegistry_isRegisteredType), - ("getAliasedTypes", doc_HasClassRegistry_getAliasedTypes), - ("getRegisteredTypes", doc_HasClassRegistry_getRegisteredTypes), - ) - } - return rv - - -doc_HasClassRegistry_create = """\ -Return a new instance of the same type as self. - -This method must be overloaded in a derived class. -""" - - -doc_HasClassRegistry_clone = """\ -Return a new instance that is a copy of self. - -This method must be overloaded in a derived class. -""" - - -doc_HasClassRegistry_type = """\ -Return a unique string type that identifies a @NAME@-derived class. -The string type is used for class registration and in the `createByType` -function. - -This method must be overloaded in a derived class. -""" - - -doc_HasClassRegistry__registerThisType = """\ -Add this class to the global registry of @NAME@ types. - -This method must be called once after definition of the derived -class to support pickling and the `createByType` factory. -""" - - -doc_HasClassRegistry__aliasType = """\ -Register the specified class type under another string alias. - -Parameters ----------- -tp : str - string type identifying a registered @NAME@ class. -alias : str - string alias to be used for the `tp` type. - -Raises ------- -RuntimeError - When they `tp` type is unknown or if the `alias` type is already - registered. -""" - - -doc_HasClassRegistry__deregisterType = """\ -Cancel registration of the specified string type and any of its aliases. - -Parameters ----------- -tp : str - string type or an alias of a registered @NAME@ class. - -Returns -------- -count : int - Number of unregistered names or aliases. - Return 0 if `tp` is not a registered type. -""" - - -doc_HasClassRegistry_createByType = """\ -Return a new @NAME@ instance of the specified string type. - -Parameters ----------- -tp : str - string type identifying a registered @NAME@ class. - -Returns -------- -@NAME@ - A new instance of the @NAME@-derived class named `tp`. - -See Also --------- -getRegisteredTypes : Return set of the recognized type strings. -getAliasedTypes : Return dictionary of string aliases. -""" - - -doc_HasClassRegistry_isRegisteredType = """\ -Check if the given string is registered as a named @NAME@ type. - -Parameters ----------- -tp : str - string name or an alias to be checked. - -Returns -------- -bool - ``True`` if `tp` is known to the registry either as a standard - type or its alias. -""" - - -doc_HasClassRegistry_getAliasedTypes = """\ -Get all aliases registered for the @NAME@ string types. - -Returns -------- -dict - a map of registered aliases to their corresponding standard names. -""" - - -doc_HasClassRegistry_getRegisteredTypes = """\ -Get string types of all registered @NAME@ classes. - -These are the allowed arguments for the `createByType` factory. - -Returns -------- -set - the registered string types. -""" diff --git a/src/diffpy/srreal/_final_imports.py b/src/diffpy/srreal/_final_imports.py deleted file mode 100644 index b61e0dc1..00000000 --- a/src/diffpy/srreal/_final_imports.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal Complex Modeling Initiative -# (c) 2016 Brookhaven Science Associates, -# Brookhaven National Laboratory. -# All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE.txt for license information. -# -############################################################################## -"""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 -must call the `import_now` function. If this module is not loaded -by the time of srreal_ext initialization, `import_now` is executed -from srreal_ext. - -This avoids unresolvable import dependencies for any order of imports. -""" - - -def import_now(): - """Import all Python modules that tweak extension-defined - classes.""" - global _import_now_called - if _import_now_called: - return - _import_now_called = True - from importlib import import_module - - import_module("diffpy.srreal.attributes") - import_module("diffpy.srreal.atomradiitable") - import_module("diffpy.srreal.bondcalculator") - import_module("diffpy.srreal.bvscalculator") - import_module("diffpy.srreal.overlapcalculator") - import_module("diffpy.srreal.pdfbaseline") - import_module("diffpy.srreal.pdfenvelope") - import_module("diffpy.srreal.peakprofile") - import_module("diffpy.srreal.peakwidthmodel") - import_module("diffpy.srreal.scatteringfactortable") - import_module("diffpy.srreal.pdfcalculator") - import_module("diffpy.srreal.structureconverters") - return - - -_import_now_called = False diff --git a/src/diffpy/srreal/atomradiitable.py b/src/diffpy/srreal/atomradiitable.py deleted file mode 100644 index bdc012ca..00000000 --- a/src/diffpy/srreal/atomradiitable.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2011 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""Class AtomRadiiTable -- storage of empirical atom radii.""" - - -# exported items, these also makes them show in pydoc. -__all__ = ["AtomRadiiTable", "ConstantRadiiTable", "CovalentRadiiTable"] - -from diffpy.srreal.srreal_ext import AtomRadiiTable, ConstantRadiiTable - -# class CovalentRadiiTable --------------------------------------------------- - - -class CovalentRadiiTable(AtomRadiiTable): - """Covalent radii from Cordero et al., 2008, doi:10.1039/b801115j. - - Instantiation of this class requires the periodictable module. - """ - - # class variable that holds the periodictable.elements object - _elements = None - - def _standardLookup(self, smbl): - """Return covalent atom radius in Angstroms. - - Attributes - ---------- - smbl - string symbol of an element - - Return float. Raise ValueError for unknown element symbol. - """ - if CovalentRadiiTable._elements is None: - from periodictable import elements - - CovalentRadiiTable._elements = elements - e = self._elements.isotope(smbl) - rv = e.covalent_radius - if rv is None: - emsg = "Undefined covalent radius for %r." % smbl - raise ValueError(emsg) - return rv - - # HasClassRegistry overloads: - - def create(self): - """Create new instance of the CovalentRadiiTable.""" - return CovalentRadiiTable() - - def clone(self): - """Return a new duplicate instance of self.""" - import copy - - 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. - - Return string. - """ - return "covalent" - - -# End of class CovalentRadiiTable -CovalentRadiiTable()._registerThisType() - -# End of file diff --git a/src/diffpy/srreal/attributes.py b/src/diffpy/srreal/attributes.py deleted file mode 100644 index 3e188caa..00000000 --- a/src/diffpy/srreal/attributes.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# 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. -""" - -__all__ = ["Attributes"] - -from diffpy.srreal.srreal_ext import Attributes - -# Inject the __getattr__ and __setattr__ methods to the Attributes class - - -def _getattr(self, name): - """Lookup a C++ double attribute if standard Python lookup fails. - - Raise AttributeError if C++ double attribute does not exist. - """ - rv = self._getDoubleAttr(name) - return rv - - -Attributes.__getattr__ = _getattr - - -def _setattr(self, name, value): - """Assign to C++ double attribute if Python attribute does not - exist.""" - try: - object.__getattribute__(self, name) - except AttributeError: - if self._hasDoubleAttr(name): - self._setDoubleAttr(name, value) - return - object.__setattr__(self, name, value) - return - - -Attributes.__setattr__ = _setattr - -# Helper accessor functions used by the _registerDoubleAttribute method - - -def _pyattrgetter(name): - def f(obj): - return object.__getattribute__(obj, name) - - return f - - -def _pyattrsetter(name): - def f(obj, value): - object.__setattr__(obj, name, value) - - return f - - -# End of file diff --git a/src/diffpy/srreal/bondcalculator.py b/src/diffpy/srreal/bondcalculator.py deleted file mode 100644 index 0fede96e..00000000 --- a/src/diffpy/srreal/bondcalculator.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2011 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""Class BondCalculator -- distances between atoms in the structure.""" - - -# exported items, these also makes them show in pydoc. -__all__ = ["BondCalculator"] - -from diffpy.srreal.srreal_ext import BondCalculator -from diffpy.srreal.wraputils import ( - propertyFromExtDoubleAttr, - setattrFromKeywordArguments, -) - -# property wrappers to C++ double attributes - -BondCalculator.rmin = propertyFromExtDoubleAttr( - "rmin", - """Lower bound for the bond distances. - [0 A]""", -) - -BondCalculator.rmax = propertyFromExtDoubleAttr( - "rmax", - """Upper bound for the bond distances. - [5 A]""", -) - - -# method overrides that support keyword arguments - - -def _init_kwargs(self, **kwargs): - """Create a new instance of BondCalculator. Keyword arguments can be - used to configure calculator properties, for example: - - bdc = BondCalculator(rmin=1.5, rmax=2.5) - - Raise ValueError for invalid keyword argument. - """ - BondCalculator.__boostpython__init(self) - setattrFromKeywordArguments(self, **kwargs) - return - - -def _call_kwargs(self, structure=None, **kwargs): - """Return sorted bond distances in the specified structure. - - Attributes - ---------- - structure - structure to be evaluated, an instance of diffpy Structure - or pyobjcryst Crystal. Reuse the last structure when None. - kwargs - optional parameter settings for this calculator - - Return a sorted numpy array. - """ - setattrFromKeywordArguments(self, **kwargs) - self.eval(structure) - return self.distances - - -BondCalculator.__boostpython__init = BondCalculator.__init__ -BondCalculator.__init__ = _init_kwargs -BondCalculator.__call__ = _call_kwargs - -# End of file diff --git a/src/diffpy/srreal/bvparameterstable.py b/src/diffpy/srreal/bvparameterstable.py deleted file mode 100644 index 6d6d9242..00000000 --- a/src/diffpy/srreal/bvparameterstable.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2011 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# 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.""" - - -# exported items, these also makes them show in pydoc. -__all__ = ["BVParam", "BVParametersTable"] - -from diffpy.srreal.srreal_ext import BVParam, BVParametersTable - -# End of file diff --git a/src/diffpy/srreal/bvscalculator.py b/src/diffpy/srreal/bvscalculator.py deleted file mode 100644 index 855cf874..00000000 --- a/src/diffpy/srreal/bvscalculator.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""Class BVSCalculator -- bond valence sums calculator.""" - - -# exported items -__all__ = ["BVSCalculator"] - -from diffpy.srreal.srreal_ext import BVSCalculator -from diffpy.srreal.wraputils import ( - propertyFromExtDoubleAttr, - setattrFromKeywordArguments, -) - -# Property wrappers to C++ double attributes - -BVSCalculator.valenceprecision = propertyFromExtDoubleAttr( - "valenceprecision", - """Cutoff value for valence contributions at long distances. - [1e-5]""", -) - -BVSCalculator.rmaxused = propertyFromExtDoubleAttr( - "rmaxused", - """Effective bound for bond lengths, where valence contributions - become smaller than valenceprecission, read-only. Always smaller or - equal to rmax. The value depends on ions present in the structure. - """, -) - -BVSCalculator.rmin = propertyFromExtDoubleAttr( - "rmin", - """Lower bound for the summed bond lengths. - [0 A]""", -) - -BVSCalculator.rmax = propertyFromExtDoubleAttr( - "rmax", - """Upper bound for the summed bond lengths. The calculation is - actually cut off much earlier when valence contributions get below - valenceprecission. See also rmaxused and valenceprecission. - [1e6 A]""", -) - - -# method overrides that support keyword arguments - - -def _init_kwargs(self, **kwargs): - """Create a new instance of BVSCalculator. - Keyword arguments can be used to configure the calculator properties, - for example: - - bvscalc = BVSCalculator(valenceprecision=0.001) - - Raise ValueError for invalid keyword argument. - """ - BVSCalculator.__boostpython__init(self) - setattrFromKeywordArguments(self, **kwargs) - return - - -def _call_kwargs(self, structure=None, **kwargs): - """Return bond valence sums at each atom site in the structure. - - Attributes - ---------- - structure - structure to be evaluated, an instance of diffpy Structure - or pyobjcryst Crystal. Reuse the last structure when None. - kwargs - optional parameter settings for this calculator - - Return an array of calculated valence sums. - See valences for the expected values. - """ - setattrFromKeywordArguments(self, **kwargs) - rv = self.eval(structure) - return rv - - -BVSCalculator.__boostpython__init = BVSCalculator.__init__ -BVSCalculator.__init__ = _init_kwargs -BVSCalculator.__call__ = _call_kwargs - -# End of file diff --git a/src/diffpy/srreal/eventticker.py b/src/diffpy/srreal/eventticker.py deleted file mode 100644 index 58d95565..00000000 --- a/src/diffpy/srreal/eventticker.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal Complex Modeling Initiative -# (c) 2013 Brookhaven Science Associates, -# Brookhaven National Laboratory. -# All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE.txt for license information. -# -############################################################################## -"""Class EventTicker -- storage of modification times of dependent -objects.""" - - -# exported items -__all__ = ["EventTicker"] - -from diffpy.srreal.srreal_ext import EventTicker - -# End of file diff --git a/src/diffpy/srreal/overlapcalculator.py b/src/diffpy/srreal/overlapcalculator.py deleted file mode 100644 index 6abd4b40..00000000 --- a/src/diffpy/srreal/overlapcalculator.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2011 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""Class OverlapCalculator -- calculator of atom overlaps in a -structure.""" - - -# exported items, these also makes them show in pydoc. -__all__ = ["OverlapCalculator"] - -from diffpy.srreal.srreal_ext import OverlapCalculator -from diffpy.srreal.wraputils import ( - propertyFromExtDoubleAttr, - setattrFromKeywordArguments, -) - -# property wrappers to C++ double attributes - -OverlapCalculator.rmin = propertyFromExtDoubleAttr( - "rmin", - """Lower bound for the bond distances. - [0 A]""", -) - -OverlapCalculator.rmax = propertyFromExtDoubleAttr( - "rmax", - """Upper bound for the bond distances. - [5 A]""", -) - -OverlapCalculator.rmaxused = propertyFromExtDoubleAttr( - "rmaxused", - """Effective upper bound for the bond distances. - rmaxused equals either a double of the maximum atom radius - in the structure or rmax. - """, -) - -# method overrides that support keyword arguments - - -def _init_kwargs(self, **kwargs): - """Create a new instance of OverlapCalculator. Keyword arguments can - be used to configure calculator properties, for example: - - olc = OverlapCalculator(rmax=2.5) - - Raise ValueError for invalid keyword argument. - """ - OverlapCalculator.__boostpython__init(self) - setattrFromKeywordArguments(self, **kwargs) - return - - -def _call_kwargs(self, structure=None, **kwargs): - """Return siteSquareOverlaps per each site of the structure. - - Attributes - ---------- - structure - structure to be evaluated, an instance of diffpy Structure - or pyobjcryst Crystal. Reuse the last structure when None. - kwargs - optional parameter settings for this calculator - - Return a numpy array. - """ - setattrFromKeywordArguments(self, **kwargs) - self.eval(structure) - return self.sitesquareoverlaps - - -OverlapCalculator.__boostpython__init = OverlapCalculator.__init__ -OverlapCalculator.__init__ = _init_kwargs -OverlapCalculator.__call__ = _call_kwargs - -# End of file diff --git a/src/diffpy/srreal/pairquantity.py b/src/diffpy/srreal/pairquantity.py deleted file mode 100644 index 7097e7c8..00000000 --- a/src/diffpy/srreal/pairquantity.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""Class PairQuantity -- base class for Python defined -calculators.""" - - -# exported items -__all__ = ["PairQuantity"] - -from diffpy.srreal.srreal_ext import PairQuantity - -# End of file diff --git a/src/diffpy/srreal/parallel.py b/src/diffpy/srreal/parallel.py deleted file mode 100644 index 45aa39c2..00000000 --- a/src/diffpy/srreal/parallel.py +++ /dev/null @@ -1,238 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""ParallelPairQuantity -- proxy class for converting PairQuantity types -into parallel calculators. -""" - - -# exported items -__all__ = ["createParallelCalculator"] - -import copy -import inspect - -from diffpy.srreal.attributes import Attributes - -# ---------------------------------------------------------------------------- - - -def createParallelCalculator(pqobj, ncpu, pmap): - """Create a proxy parallel calculator to a PairQuantity instance. - - Attributes - ---------- - pqobj - instance of PairQuantity calculator to be run in parallel - ncpu - number of parallel jobs - pmap - a parallel map function used to submit job to workers - - The ``pqobj.evaluatortype`` is reset to 'BASIC' because other - evaluator types are not supported within parallel calculations. - - Return a proxy calculator instance that has the same interface, - but executes the calculation in parallel split among ncpu jobs. - """ - - class ParallelPairQuantity(Attributes): - """Class for running parallel calculations. This is a proxy - class to the wrapper PairQuantity type with the same interface. - - Instance data: - - Attributes - ---------- - pqobj - the master PairQuantity object to be evaluated in parallel - ncpu - number of parallel jobs - pmap - a parallel map function used to submit job to workers - """ - - def __init__(self, pqobj, ncpu, pmap): - """Initialize a parallel proxy to the PairQuantity instance. - - Attributes - ---------- - pqobj - instance of PairQuantity calculator to be run - in parallel - ncpu - number of parallel jobs - pmap - a parallel map function used to submit job to workers - """ - # use explicit assignment to avoid setattr forwarding to the pqobj - object.__setattr__(self, "pqobj", pqobj) - object.__setattr__(self, "ncpu", ncpu) - object.__setattr__(self, "pmap", pmap) - # parallel calculations support only the BASIC evaluation - self.pqobj.evaluatortype = "BASIC" - return - - def eval(self, stru=None): - """Perform parallel calculation and return internal value - array. - - Attributes - ---------- - stru - object that can be converted to StructureAdapter, - e.g., example diffpy Structure or pyobjcryst Crystal. - Use the last structure when None. - - Return numpy array. - """ - # use StructureAdapter for faster pickles - from diffpy.srreal.structureadapter import createStructureAdapter - - if stru is None: - struadpt = self.pqobj.getStructure() - else: - struadpt = createStructureAdapter(stru) - self.pqobj.setStructure(struadpt) - kwd = { - "cpuindex": None, - "ncpu": self.ncpu, - "pqobj": copy.copy(self.pqobj), - } - # shallow copies of kwd dictionary each with a unique cpuindex - arglist = [kwd.copy() for kwd["cpuindex"] in range(self.ncpu)] - for pdata in self.pmap(_parallelData, arglist): - self.pqobj._mergeParallelData(pdata, self.ncpu) - return self.pqobj.value - - def __call__(self, *args, **kwargs): - """Call the wrapped calculator using parallel evaluation. - - The arguments and return value are the same as for the - wrapped PairQuantity calculator. - """ - savedeval = self.pqobj.__dict__.get("eval") - - def restore_eval(): - if savedeval: - self.pqobj.eval = savedeval - else: - self.pqobj.__dict__.pop("eval", None) - - def parallel_eval(stru): - assert self.pqobj.eval is parallel_eval - restore_eval() - return self.eval(stru) - - self.pqobj.eval = parallel_eval - try: - rv = self.pqobj(*args, **kwargs) - finally: - restore_eval() - return rv - - @property - def evaluatortype(self): - """str : Type of evaluation procedure. - - Parallel calculations allow only the 'BASIC' type. - """ - return self.pqobj.evaluatortype - - @evaluatortype.setter - def evaluatortype(self, value): - if value != "BASIC": - emsg = "Parallel calculations require 'BASIC' evaluatortype." - raise ValueError(emsg) - self.pqobj.evaluatortype = value - return - - # class ParallelPairQuantity - - # Create proxy method and properties to the wrapped PairQuantity - - pqtype = type(pqobj) - - # create proxy methods to all public methods and some protected methods - - proxy_forced = set( - """_getDoubleAttr _setDoubleAttr _hasDoubleAttr - _namesOfDoubleAttributes _namesOfWritableDoubleAttributes - """.split() - ) - - def _make_proxymethod(name, f): - def proxymethod(self, *args, **kwargs): - pqobj = object.__getattribute__(self, "pqobj") - return f(pqobj, *args, **kwargs) - - proxymethod.__name__ = name - proxymethod.__doc__ = f.__doc__ - return proxymethod - - for n, f in inspect.getmembers(pqtype, inspect.isroutine): - ignore = n not in proxy_forced and ( - n.startswith("_") or hasattr(ParallelPairQuantity, n) - ) - if ignore: - continue - setattr(ParallelPairQuantity, n, _make_proxymethod(n, f)) - - # create proxy properties to all properties that do not conflict with - # existing class items - - def _make_proxyproperty(prop): - fget = fset = fdel = None - if prop.fget: - - def _fget(self): - return prop.fget(self.pqobj) - - fget = _fget - - if prop.fset: - - def _fset(self, value): - return prop.fset(self.pqobj, value) - - fset = _fset - - if prop.fdel: - - 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): - if hasattr(ParallelPairQuantity, n): - continue - setattr(ParallelPairQuantity, n, _make_proxyproperty(p)) - - # finally create an instance of this very custom class - return ParallelPairQuantity(pqobj, ncpu, pmap) - - -def _parallelData(kwd): - """Helper for calculating and fetching raw results from a worker - node.""" - pqobj = kwd["pqobj"] - pqobj._setupParallelRun(kwd["cpuindex"], kwd["ncpu"]) - pqobj.eval() - return pqobj._getParallelData() - - -# End of file diff --git a/src/diffpy/srreal/pdfbaseline.py b/src/diffpy/srreal/pdfbaseline.py deleted file mode 100644 index d3d2e56e..00000000 --- a/src/diffpy/srreal/pdfbaseline.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -""" -Classes for configuring PDF baseline: - PDFBaseline, ZeroBaseline, LinearBaseline -""" - - -# exported items -__all__ = """ - PDFBaseline makePDFBaseline - ZeroBaseline - LinearBaseline - """.split() - -from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import LinearBaseline, PDFBaseline, ZeroBaseline -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr - -# class PDFBaseline ---------------------------------------------------------- - -# disable dictionary pickling for wrapped C++ classes - -LinearBaseline.__getstate_manages_dict__ = None -ZeroBaseline.__getstate_manages_dict__ = None - -# attribute wrapper - -LinearBaseline.slope = propertyFromExtDoubleAttr( - "slope", - """Slope of an unscaled linear baseline. For crystal structures it - is preset to (-4 * pi * rho0).""", -) - -# Python functions wrapper - - -def makePDFBaseline(name, fnc, replace=False, **dbattrs): - """Helper function for registering Python function as a PDFBaseline. - This is required for using Python function as - PDFCalculator.baseline. - - Attributes - ---------- - name - unique string name for registering Python function in the - global registry of PDFBaseline types. This will be the - string identifier for the createByType factory. - fnc - Python function of a floating point argument and optional - float parameters. The parameters need to be registered as - double attributes in the functor class. The function fnc - must be picklable and it must return a float. - replace - when set replace any PDFBaseline type already registered - under the name. Otherwise raise RuntimeError when the - name is taken. - dbattrs - optional float parameters of the wrapped function. - These will be registered as double attributes in the - functor class. The wrapped function must be callable as - fnc(x, **dbattrs). Make sure to pick attribute names that - do not conflict with other PDFCalculator attributes. - - Return an instance of the new PDFBaseline class. - - Example: - - # Python baseline function - def fshiftedline(x, aline, bline): - return aline * x + bline - # wrap it as a PDFBaseline and register as a "shiftedline" type - makePDFBaseline("shiftedline", fshiftedline, aline=-1, bline=0) - baseline = PDFBaseline.createByType("shiftedline") - print map(baseline, range(5)) - # use it in PDFCalculator - pdfc = PDFCalculator() - pdfc.baseline = baseline - # or pdfc.baseline = "shiftedline" - """ - from diffpy.srreal.wraputils import _wrapAsRegisteredUnaryFunction - - rv = _wrapAsRegisteredUnaryFunction( - PDFBaseline, name, fnc, replace=replace, **dbattrs - ) - return rv - - -# Import delayed tweaks of the extension classes. - -_final_imports.import_now() -del _final_imports - -# End of file diff --git a/src/diffpy/srreal/pdfcalculator.py b/src/diffpy/srreal/pdfcalculator.py deleted file mode 100644 index d4f1c1fb..00000000 --- a/src/diffpy/srreal/pdfcalculator.py +++ /dev/null @@ -1,335 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# 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__ = """ - DebyePDFCalculator PDFCalculator - fftftog fftgtof - """.split() - -# imports for backward compatibility -from diffpy.srreal.pdfbaseline import ( - LinearBaseline, - PDFBaseline, - ZeroBaseline, - makePDFBaseline, -) -from diffpy.srreal.pdfenvelope import ( - PDFEnvelope, - QResolutionEnvelope, - ScaleEnvelope, - SphericalShapeEnvelope, - StepCutEnvelope, - makePDFEnvelope, -) -from diffpy.srreal.peakprofile import PeakProfile -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( - ( - PDFBaseline, - makePDFBaseline, - ZeroBaseline, - LinearBaseline, - PDFEnvelope, - makePDFEnvelope, - QResolutionEnvelope, - ScaleEnvelope, - SphericalShapeEnvelope, - StepCutEnvelope, - PeakProfile, - PeakWidthModel, - ConstantPeakWidth, - DebyeWallerPeakWidth, - JeongPeakWidth, - ) -) - -# ---------------------------------------------------------------------------- - - -def _defineCommonInterface(cls): - """This function defines shared properties of PDF calculator - classes.""" - - cls.scale = propertyFromExtDoubleAttr( - "scale", - """Scale factor of the calculated PDF. Active for ScaleEnvelope. - [1.0 unitless]""", - ) - - cls.delta1 = propertyFromExtDoubleAttr( - "delta1", - """Coefficient for (1/r) contribution to the peak sharpening. - Active for JeongPeakWidth model. - [0 A]""", - ) - - cls.delta2 = propertyFromExtDoubleAttr( - "delta2", - """Coefficient for (1/r**2) contribution to the peak sharpening. - Active for JeongPeakWidth model. - [0 A**2]""", - ) - - cls.qdamp = propertyFromExtDoubleAttr( - "qdamp", - """PDF Gaussian dampening factor due to limited Q-resolution. - Not applied when equal to zero. Active for QResolutionEnvelope. - [0 1/A]""", - ) - - cls.qbroad = propertyFromExtDoubleAttr( - "qbroad", - """PDF peak broadening from increased intensity noise at high Q. - Not applied when equal zero. Active for JeongPeakWidth model. - [0 1/A]""", - ) - - cls.extendedrmin = propertyFromExtDoubleAttr( - "extendedrmin", - """Low boundary of the extended r-range, read-only. - [A]""", - ) - - cls.extendedrmax = propertyFromExtDoubleAttr( - "extendedrmax", - """Upper boundary of the extended r-range, read-only. - [A]""", - ) - - cls.maxextension = propertyFromExtDoubleAttr( - "maxextension", - """Maximum extension of the r-range that accounts for contributions - from the out of range peaks. - [10 A]""", - ) - - cls.rmin = propertyFromExtDoubleAttr( - "rmin", - """Lower bound of the r-grid for PDF calculation. - [0 A]""", - ) - - cls.rmax = propertyFromExtDoubleAttr( - "rmax", - """Upper bound of the r-grid for PDF calculation. - [10 A]""", - ) - - cls.rstep = propertyFromExtDoubleAttr( - "rstep", - """Spacing in the calculated r-grid. r-values are at the - multiples of rstep. - [0.01 A]""", - ) - - 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. - - Attributes - ---------- - structure - a structure object to be evaluated. Reuse the last - structure when None. - kwargs - optional parameter settings for this calculator - - Example: pdfcalc(structure, qmax=20, spdiameter=15) - - Return a tuple of (r, G) numpy arrays. - """ - setattrFromKeywordArguments(self, **kwargs) - self.eval(structure) - # apply kwargs again if structure contained any attribute - # that may affect the result. - setattrFromKeywordArguments(self, **kwargs) - rv = (self.rgrid, self.pdf) - return rv - - cls.__call__ = _call_kwargs - - -# _defineCommonInterface - -# class DebyePDFCalculator --------------------------------------------------- - -# shared interface of the PDF calculator classes - -_defineCommonInterface(DebyePDFCalculator) - -# Property wrappers to double attributes of the C++ DebyePDFCalculator - -DebyePDFCalculator.debyeprecision = propertyFromExtDoubleAttr( - "debyeprecision", - """Cutoff amplitude for the sine contributions to the F(Q). - [1e-6 unitless]""", -) - -DebyePDFCalculator.qmin = propertyFromExtDoubleAttr( - "qmin", - """Lower bound of the Q-grid for the calculated F(Q). - Affects the shape envelope. - [0 1/A] - """, -) - -DebyePDFCalculator.qmax = propertyFromExtDoubleAttr( - "qmax", - """Upper bound of the Q-grid for the calculated F(Q). - Affects the termination ripples. - [25 1/A] - """, -) - -DebyePDFCalculator.qstep = propertyFromExtDoubleAttr( - "qstep", - """Spacing in the Q-grid. Q-values are at the multiples of qstep. - [PI/extendedrmax A] unless user overridden. - See also setOptimumQstep, isOptimumQstep.""", -) - -# method overrides to support optional keyword arguments - - -def _init_kwargs0(self, **kwargs): - """Create a new instance of the DebyePDFCalculator. - Keyword arguments can be used to configure the calculator properties, - for example: - - dpc = DebyePDFCalculator(qmax=20, rmin=7, rmax=15) - - Raise ValueError for invalid keyword argument. - """ - DebyePDFCalculator.__boostpython__init(self) - setattrFromKeywordArguments(self, **kwargs) - return - - -DebyePDFCalculator.__boostpython__init = DebyePDFCalculator.__init__ -DebyePDFCalculator.__init__ = _init_kwargs0 - -# End of class DebyePDFCalculator - -# PDFCalculator -------------------------------------------------------------- - -# shared interface of the PDF calculator classes - -_defineCommonInterface(PDFCalculator) - -# Property wrappers to double attributes of the C++ PDFCalculator - -PDFCalculator.peakprecision = propertyFromExtDoubleAttr( - "peakprecision", - """Cutoff amplitude of the peak tail relative to the peak maximum. - [3.33e-6 unitless]""", -) - -PDFCalculator.qmin = propertyFromExtDoubleAttr( - "qmin", - """Lower bound of the experimental Q-range used. - Affects the shape envelope. - [0 1/A]""", -) - -PDFCalculator.qmax = propertyFromExtDoubleAttr( - "qmax", - """Upper bound of the experimental Q-range used. - Affects the termination ripples. Not used when zero. - [0 1/A]""", -) - -PDFCalculator.qstep = propertyFromExtDoubleAttr( - "qstep", - """Spacing in the Q-grid. Q-values are at the multiples of qstep. - The value is padded by rsteps so that PI/qstep > extendedrmax and - PI/(qstep * rstep) is a power of 2. Read-only. - [PI/(padded extendedrmax) A]""", -) - -PDFCalculator.slope = propertyFromExtDoubleAttr( - "slope", - """Slope of the linear PDF background. Assigned according to - number density of the evaluated structure at each PDF calculation. - Active for LinearBaseline. - [-4*pi*numdensity unitless]""", -) - -PDFCalculator.spdiameter = propertyFromExtDoubleAttr( - "spdiameter", - """Spherical particle diameter for PDF shape damping correction. - Not used when zero. Active for SphericalShapeEnvelope. - [0 A]""", -) - -PDFCalculator.stepcut = propertyFromExtDoubleAttr( - "stepcut", - """r-boundary for a step cutoff of the calculated PDF. - Not used when negative or zero. Active for StepCutEnvelope. - Not used when zero. Active for StepCutEnvelope. - [0 A]""", -) - -# method overrides to support optional keyword arguments - - -def _init_kwargs1(self, **kwargs): - """Create a new instance of PDFCalculator. - Keyword arguments can be used to configure the calculator properties, - for example: - - pc = PDFCalculator(qmax=20, rmin=7, rmax=15) - - Raise ValueError for invalid keyword argument. - """ - PDFCalculator.__boostpython__init(self) - setattrFromKeywordArguments(self, **kwargs) - return - - -PDFCalculator.__boostpython__init = PDFCalculator.__init__ -PDFCalculator.__init__ = _init_kwargs1 - -# End of class PDFCalculator - -# End of file diff --git a/src/diffpy/srreal/pdfenvelope.py b/src/diffpy/srreal/pdfenvelope.py deleted file mode 100644 index a8f68a48..00000000 --- a/src/diffpy/srreal/pdfenvelope.py +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -""" -Classes for configuring PDF scaling envelope: - PDFEnvelope, ScaleEnvelope, QResolutionEnvelope, - SphericalShapeEnvelope, StepCutEnvelope -""" - - -# exported items -__all__ = """ - PDFEnvelope makePDFEnvelope - QResolutionEnvelope - ScaleEnvelope - SphericalShapeEnvelope - StepCutEnvelope - """.split() - -from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import ( - PDFEnvelope, - QResolutionEnvelope, - ScaleEnvelope, - SphericalShapeEnvelope, - StepCutEnvelope, -) -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr - -# class PDFEnvelope ---------------------------------------------------------- - -# disable dictionary pickling for wrapped C++ classes - -QResolutionEnvelope.__getstate_manages_dict__ = None -ScaleEnvelope.__getstate_manages_dict__ = None -SphericalShapeEnvelope.__getstate_manages_dict__ = None -StepCutEnvelope.__getstate_manages_dict__ = None - -# attribute wrappers - -QResolutionEnvelope.qdamp = propertyFromExtDoubleAttr( - "qdamp", - """Dampening parameter in the Gaussian envelope function. - """, -) - -ScaleEnvelope.scale = propertyFromExtDoubleAttr( - "scale", - """Overall scale for a uniform scaling envelope. - """, -) - -SphericalShapeEnvelope.spdiameter = propertyFromExtDoubleAttr( - "spdiameter", - """Particle diameter in Angstroms for a spherical shape damping. - """, -) - -StepCutEnvelope.stepcut = propertyFromExtDoubleAttr( - "stepcut", - """Cutoff for a step-function envelope. - """, -) - -# Python functions wrapper - - -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. - - Attributes - ---------- - name - unique string name for registering Python function in the - global registry of PDFEnvelope types. This will be the - string identifier for the createByType factory. - fnc - Python function of a floating point argument and optional - float parameters. The parameters need to be registered as - double attributes in the functor class. The function fnc - must be picklable and it must return a float. - replace - when set replace any PDFEnvelope type already registered - under the name. Otherwise raise RuntimeError when the - name is taken. - dbattrs - optional float parameters of the wrapped function. - These will be registered as double attributes in the - functor class. The wrapped function must be callable as - fnc(x, **dbattrs). Make sure to pick attribute names that - do not conflict with other PDFCalculator attributes. - - Return an instance of the new PDFEnvelope class. - - Example: - - # Python envelope function - def fexpdecay(x, expscale, exptail): - from math import exp - return expscale * exp(-x / exptail) - # wrap it as a PDFEnvelope and register as a "expdecay" type - makePDFEnvelope("expdecay", fexpdecay, expscale=5, exptail=4) - envelope = PDFEnvelope.createByType("expdecay") - print map(envelope, range(9)) - # use it in PDFCalculator - pdfc = PDFCalculator() - pdfc.addEnvelope(envelope) - # or pdfc.addEnvelope("expdecay") - """ - from diffpy.srreal.wraputils import _wrapAsRegisteredUnaryFunction - - rv = _wrapAsRegisteredUnaryFunction( - PDFEnvelope, name, fnc, replace=replace, **dbattrs - ) - return rv - - -# Import delayed tweaks of the extension classes. - -_final_imports.import_now() -del _final_imports - -# End of file diff --git a/src/diffpy/srreal/peakprofile.py b/src/diffpy/srreal/peakprofile.py deleted file mode 100644 index 7692e1d7..00000000 --- a/src/diffpy/srreal/peakprofile.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -""" -Class for configuring PDF profile function: - PeakProfile - GaussianProfile, CroppedGaussianProfile -""" - - -# exported items -__all__ = ["PeakProfile", "GaussianProfile", "CroppedGaussianProfile"] - -from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import ( - CroppedGaussianProfile, - GaussianProfile, - PeakProfile, -) -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr - -# class PeakProfile ---------------------------------------------------------- - -# disable dictionary pickling for wrapped C++ classes - -GaussianProfile.__getstate_manages_dict__ = None -CroppedGaussianProfile.__getstate_manages_dict__ = None - -# add attribute wrappers for PeakProfile and derived classes - -PeakProfile.peakprecision = propertyFromExtDoubleAttr( - "peakprecision", - """Profile amplitude relative to the peak maximum for evaluating peak - bounds xboundlo and xboundhi. [3.33e-6 unitless] - """, -) - -# Import delayed tweaks of the extension classes. - -_final_imports.import_now() -del _final_imports - -# End of file diff --git a/src/diffpy/srreal/peakwidthmodel.py b/src/diffpy/srreal/peakwidthmodel.py deleted file mode 100644 index 7c73e8e8..00000000 --- a/src/diffpy/srreal/peakwidthmodel.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -""" -Classes for configuring peak width evaluation in PDF calculations: - PeakWidthModel, - ConstantPeakWidth, DebyeWallerPeakWidth, JeongPeakWidth -""" - - -# exported items -__all__ = [ - "PeakWidthModel", - "ConstantPeakWidth", - "DebyeWallerPeakWidth", - "JeongPeakWidth", -] - -from diffpy.srreal import _final_imports -from diffpy.srreal.srreal_ext import ( - ConstantPeakWidth, - DebyeWallerPeakWidth, - JeongPeakWidth, - PeakWidthModel, -) -from diffpy.srreal.wraputils import propertyFromExtDoubleAttr - -# class PeakWidthModel ------------------------------------------------------- - -# add attribute wrappers for the derived classes - -ConstantPeakWidth.width = propertyFromExtDoubleAttr( - "width", - """Constant FWHM value returned by this model. - """, -) - -ConstantPeakWidth.bisowidth = propertyFromExtDoubleAttr( - "bisowidth", - """Equivalent uniform Biso for this constant `width`. - """, -) - -ConstantPeakWidth.uisowidth = propertyFromExtDoubleAttr( - "uisowidth", - """Equivalent uniform Uiso for this constant `width`. - """, -) - -JeongPeakWidth.delta1 = propertyFromExtDoubleAttr( - "delta1", "Coefficient for (1/r) contribution to the peak sharpening." -) - -JeongPeakWidth.delta2 = propertyFromExtDoubleAttr( - "delta2", "Coefficient for (1/r**2) contribution to the peak sharpening." -) - -JeongPeakWidth.qbroad = propertyFromExtDoubleAttr( - "qbroad", "PDF peak broadening from increased intensity noise at high Q." -) - -# Import delayed tweaks of the extension classes. - -_final_imports.import_now() -del _final_imports - -# End of file diff --git a/src/diffpy/srreal/scatteringfactortable.py b/src/diffpy/srreal/scatteringfactortable.py deleted file mode 100644 index 9fa232ac..00000000 --- a/src/diffpy/srreal/scatteringfactortable.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""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.sfaverage import SFAverage -from diffpy.srreal.srreal_ext import ( - ScatteringFactorTable, - SFTElectron, - SFTElectronNumber, - SFTNeutron, - SFTXray, -) - -# Pickling Support ----------------------------------------------------------- - -# disable dictionary pickling for wrapped C++ classes - -SFTXray.__getstate_manages_dict__ = None -SFTElectron.__getstate_manages_dict__ = None -SFTNeutron.__getstate_manages_dict__ = None -SFTElectronNumber.__getstate_manages_dict__ = None - -# End of file diff --git a/src/diffpy/srreal/sfaverage.py b/src/diffpy/srreal/sfaverage.py deleted file mode 100644 index d524b0c3..00000000 --- a/src/diffpy/srreal/sfaverage.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal Complex Modeling Initiative -# (c) 2016 Brookhaven Science Associates, -# Brookhaven National Laboratory. -# All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE.txt for license information. -# -############################################################################## -"""Compositional averaging of atom scattering factors. - -Examples --------- -:: - - import numpy as np - from diffpy.srreal.scatteringfactortable import SFTXray - xtb = SFTXray() - qa = np.linspace(0, 25) - sfavg1 = SFAverage.fromComposition({'Na' : 1, 'Cl' : 1}, xtb, qa) - sfavg2 = SFAverage.fromComposition([('Mn', 1), ('O', 2)], xtb, qa) - - from diffpy.structure import loadStructure - from diffpy.srreal.pdfcalculator import DebyePDFCalculator - dpdfc = DebyePDFCalculator() - dpdfc(loadStructure('rutile.cif')) - sfavg3 = SFAverage.fromStructure(dpdfc.getStructure(), - dpdfc.scatteringfactortable, dpdfc.qgrid) -""" - - -# class SFAverage ------------------------------------------------------------ - - -class SFAverage(object): - """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. - - Attributes - ---------- - f1sum : - Sum of scattering factors from all atoms. - Float or NumPy array. - f2sum : - Sum of squared scattering factors from all atoms. - Float or NumPy array. - count : - Total number of atoms. Can be non-integer in case of - fractional occupancies. - f1avg : - Compositional average of scattering factors. - Float or NumPy array. - f2avg : - Compositional average of squared scattering factors. - Float or NumPy array. - composition : - Dictionary of atom symbols and their total abundance. - """ - - f1sum = 0 - f2sum = 0 - count = 0 - f1avg = 0 - f2avg = 0 - composition = None - - @classmethod - def fromStructure(cls, stru, sftb, q=0): - """Calculate average scattering factors from a structure object. - - Parameters - ---------- - stru : diffpy Structure or pyobjcryst Crystal or StructureAdapter - The structure object that stores the atom species and their - occupancies. Can be any type with a registered conversion - to the StructureAdapter class. - sftb : ScatteringFactorTable or str - The ScatteringFactorTable object for looking up the values. - When string use `ScatteringFactorTable.createByType` to create - a new lookup table of the specified type. - q : float or NumPy array (optional) - The Q value in inverse Angstroms for which to lookup - the scattering factor values. - - See also - -------- - RegisterStructureAdapter : to add support for more structure types. - - Returns - ------- - SFAverage - The calculated scattering factor averages. - """ - # a bit of duck-typing for faster handling of diffpy.structure - if hasattr(type(stru), "composition"): - composition = stru.composition - if isinstance(composition, dict): - return cls.fromComposition(composition, sftb, q) - # otherwise let's convert to a known structure type - from diffpy.srreal.structureadapter import createStructureAdapter - - adpt = createStructureAdapter(stru) - composition = {} - for i in range(adpt.countSites()): - smbl = adpt.siteAtomType(i) - cnt = adpt.siteOccupancy(i) * adpt.siteMultiplicity(i) - composition[smbl] = composition.get(smbl, 0) + cnt - return cls.fromComposition(composition, sftb, q) - - @classmethod - def fromComposition(cls, composition, sftb, q=0): - """Calculate average scattering factors from atom - concentrations. - - Parameters - ---------- - composition : dictionary or a list of (symbol, amount) pairs. - The chemical composition for evaluating the average. Atom - symbols may repeat when it is a list of (symbol, amount) pairs. - sftb : ScatteringFactorTable or str - The ScatteringFactorTable object for looking up the values. - When string use `ScatteringFactorTable.createByType` to create - a new lookup table of the specified type. - q : float or NumPy array (optional) - The Q value in inverse Angstroms for which to lookup - the scattering factor values. - - Returns - ------- - SFAverage - The calculated scattering factor averages. - """ - from diffpy.srreal.scatteringfactortable import ScatteringFactorTable - - sfa = cls() - sfa.composition = {} - if isinstance(composition, dict): - sfa.composition.update(composition) - else: - for smbl, cnt in composition: - if smbl not in sfa.composition: - sfa.composition[smbl] = 0 - sfa.composition[smbl] += cnt - sfa.f1sum = 0.0 * q - sfa.f2sum = 0.0 * q - # resolve the lookup table object `tb` - tb = ( - sftb - if not isinstance(sftb, str) - else ScatteringFactorTable.createByType(sftb) - ) - for smbl, cnt in sfa.composition.items(): - sfq = tb.lookup(smbl, q) - sfa.f1sum += cnt * sfq - sfa.f2sum += cnt * sfq**2 - sfa.count += cnt - denom = sfa.count if sfa.count > 0 else 1 - sfa.f1avg = sfa.f1sum / denom - sfa.f2avg = sfa.f2sum / denom - return sfa - - -# End of class SFAverage diff --git a/src/diffpy/srreal/structureadapter.py b/src/diffpy/srreal/structureadapter.py deleted file mode 100644 index 3f6b8aa9..00000000 --- a/src/diffpy/srreal/structureadapter.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""Class StructureAdapter -- adapter of any structure object to the -interface expected by srreal PairQuantity calculators. - -Routines: - -createStructureAdapter -- create StructureAdapter from a Python object -nometa -- create StructureAdapter with disabled _customPQConfig method - this prevents copying of diffpy.structure pdffit metadata - to PDFCalculator object -nosymmetry -- create StructureAdapter with disabled symmetry expansion. - -Constants: - -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. - - Attributes - ---------- - stru - an object that is convertible to StructureAdapter, i.e., it has - a registered factory that converts Python structure object to - StructureAdapter. Return stru if already a StructureAdapter. - - Return a StructureAdapter instance. - Raise TypeError if stru cannot be converted to StructureAdapter. - """ - if isinstance(stru, StructureAdapter): - return stru - import inspect - - # build fully-qualified names of Python types in method resolution order - cls = type(stru) - fqnames = [str(tp).split("'")[1] for tp in inspect.getmro(cls)] - for fqn in fqnames: - if fqn not in _adapter_converters_registry: - continue - factory = _adapter_converters_registry[fqn] - return factory(stru) - # none of the registered factories could convert the stru object - emsg = "Cannot create structure adapter for %r." % (stru,) - raise TypeError(emsg) - - -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 diffpy.srreal structure type. - - Attributes - ---------- - fqname - fully qualified class name for the convertible objects. - This is the quoted string included in "str(type(obj))". - The converter function would be called for object of the - same or derived types. - fnc - function that converts the fqname type to StructureAdapter. - - Note: When fnc is None RegisterStructureAdapter works as a decorator - and the conversion function can be specified below, i.e., - - @RegisterStructureAdapter('my.structure.Type') - def convertMyStructure(stru): - ... - - See diffpy.srreal.structureconverters module for usage example. - """ - - def __wrapper(fnc): - _adapter_converters_registry[fqname] = fnc - return fnc - - if fnc is None: - return __wrapper - return __wrapper(fnc) - - -_adapter_converters_registry = {} - -EMPTY = _emptyStructureAdapter() -del _emptyStructureAdapter - -# silence the pyflakes syntax checker -assert all( - ( - Atom, - AtomicStructureAdapter, - PeriodicStructureAdapter, - CrystalStructureAdapter, - StructureDifference, - nometa, - nosymmetry, - BaseBondGenerator, - ) -) - -# End of file diff --git a/src/diffpy/srreal/structureconverters.py b/src/diffpy/srreal/structureconverters.py deleted file mode 100644 index 67883f79..00000000 --- a/src/diffpy/srreal/structureconverters.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal Complex Modeling Initiative -# (c) 2014 Brookhaven Science Associates, -# Brookhaven National Laboratory. -# All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# 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 ------------------------ - - -RegisterStructureAdapter( - "pyobjcryst._pyobjcryst.Molecule", convertObjCrystMolecule -) -RegisterStructureAdapter( - "pyobjcryst._pyobjcryst.Crystal", convertObjCrystCrystal -) - -# Converter for Structure class from diffpy.structure ------------------------ - - -# TODO prune in version 1.4. -@RegisterStructureAdapter("diffpy.Structure.structure.Structure") -@RegisterStructureAdapter("diffpy.structure.structure.Structure") -def convertDiffPyStructure(stru): - """Adapt Structure class from diffpy.structure package.""" - haslattice = (1, 1, 1, 90, 90, 90) != stru.lattice.abcABG() - isperiodic = haslattice - hasmeta = _DiffPyStructureMetadata.hasMetadata(stru) - if hasmeta: - if isperiodic: - adpt = DiffPyStructurePeriodicAdapter() - else: - adpt = DiffPyStructureAtomicAdapter() - adpt._fetchMetadata(stru) - else: - if isperiodic: - adpt = PeriodicStructureAdapter() - else: - adpt = AtomicStructureAdapter() - _fetchDiffPyStructureData(adpt, stru) - return adpt - - -# Adapter classes and helpers for diffpy.structure class --------------------- - - -class _DiffPyStructureMetadata(object): - """Base class for handling metadata information in the pdffit - attribute.""" - - pdffit = None - - @staticmethod - def hasMetadata(stru): - """True if Structure object carries data in its pdffit - attribute.""" - rv = hasattr(stru, "pdffit") and bool(stru.pdffit) - return rv - - def _customPQConfig(self, pqobj): - """Apply PDF-related metadata if defined in PDFFit structure - format.""" - pqname = type(pqobj).__name__ - if pqname not in ("PDFCalculator", "DebyePDFCalculator"): - return - if not self.pdffit: - return - # scale - envtps = pqobj.usedenvelopetypes - if "scale" not in envtps: - pqobj.addEnvelope("scale") - pqobj.scale = self.pdffit["scale"] - # spdiameter - if "spdiameter" in self.pdffit: - if "sphericalshape" not in envtps: - pqobj.addEnvelope("sphericalshape") - pqobj.spdiameter = self.pdffit["spdiameter"] - # stepcut - if "stepcut" in self.pdffit: - if "stepcut" not in envtps: - pqobj.addEnvelope("stepcut") - pqobj.stepcut = self.pdffit["stepcut"] - # delta1, delta2 - set these only when using JeongPeakWidth model - if pqobj.peakwidthmodel.type() == "jeong": - pqobj.delta1 = self.pdffit["delta1"] - pqobj.delta2 = self.pdffit["delta2"] - return - - def _fetchMetadata(self, stru): - """Copy data from the pdffit attribute of diffpy Structure - object. - - Attributes - ---------- - stru - instance of Structure class from diffpy.structure - - No return value. - """ - # get PDF-related metadata - self.pdffit = {} - if self.hasMetadata(stru): - self.pdffit.update(scale=1.0, delta1=0.0, delta2=0.0) - self.pdffit.update(stru.pdffit) - return - - -# end of class _DiffPyStructureMetadata - - -class DiffPyStructureAtomicAdapter( - _DiffPyStructureMetadata, AtomicStructureAdapter -): - pass - - -class DiffPyStructurePeriodicAdapter( - _DiffPyStructureMetadata, PeriodicStructureAdapter -): - pass - - -def _fetchDiffPyStructureData(adpt, stru): - """Copy structure data from diffpy Structure object to this Adapter. - - Attributes - ---------- - adpt - instance of AtomicStructureAdapter or PeriodicStructureAdapter - stru - instance of Structure class from diffpy.structure - - No return value. - """ - from diffpy.srreal.srreal_ext import Atom as AdapterAtom - - # copy atoms - del adpt[:] - adpt.reserve(len(stru)) - aa = AdapterAtom() - for a0 in stru: - aa.atomtype = a0.element - aa.occupancy = a0.occupancy - aa.anisotropy = a0.anisotropy - # copy fractional coordinates - aa.xyz_cartn = a0.xyz - aa.uij_cartn = a0.U - adpt.append(aa) - if hasattr(adpt, "setLatPar"): - adpt.setLatPar(*stru.lattice.abcABG()) - for aa in adpt: - adpt.toCartesian(aa) - return - - -# End of file diff --git a/src/diffpy/srreal/version.py b/src/diffpy/srreal/version.py deleted file mode 100644 index a988772a..00000000 --- a/src/diffpy/srreal/version.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# (c) 2025 The Trustees of Columbia University in the City of New York. -# All rights reserved. -# -# File coded by: Billinge Group members and community contributors. -# -# See GitHub contributions for a more detailed list of contributors. -# https://github.com/diffpy/diffpy.srreal/graphs/contributors -# -# See LICENSE.rst for license information. -# -############################################################################## -"""Definition of __version__.""" - -# We do not use the other three variables, but can be added back if needed. -# __all__ = ["__date__", "__git_commit__", "__timestamp__", "__version__"] - -# obtain version information -from importlib.metadata import PackageNotFoundError, version - -FALLBACK_VERSION = "1.3.0" - -try: - __version__ = version("diffpy.srreal") -except PackageNotFoundError: - __version__ = FALLBACK_VERSION - - -# End of file diff --git a/src/diffpy/srreal/wraputils.py b/src/diffpy/srreal/wraputils.py deleted file mode 100644 index b3a5ee6f..00000000 --- a/src/diffpy/srreal/wraputils.py +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env python -############################################################################## -# -# diffpy.srreal by DANSE Diffraction group -# Simon J. L. Billinge -# (c) 2010 The Trustees of Columbia University -# in the City of New York. All rights reserved. -# -# File coded by: Pavol Juhas -# -# See AUTHORS.txt for a list of people who contributed. -# See LICENSE_DANSE.txt for license information. -# -############################################################################## -"""Local utilities helpful for tweaking interfaces to boost python -classes.""" - - -import copy - -# Routines ------------------------------------------------------------------- - - -def propertyFromExtDoubleAttr(attrname, doc): - """Create property wrapper to a DoubleAttr in C++ extension object. - - Attributes - ---------- - attrname - string name of the double attribute - doc - docstring for the Python class property - - Return a property object. - """ - - def fget(self): - return self._getDoubleAttr(attrname) - - def fset(self, value): - self._setDoubleAttr(attrname, value) - return - - rv = property(fget, fset, doc=doc) - return rv - - -def setattrFromKeywordArguments(obj, **kwargs): - """Set attributes of the obj according to keyword arguments. - For example: setattrFromKeywordArguments(obj, qmax=24, scale=2) - This is a shared helper function used by __init__ and __call__. - - Attributes - ---------- - kwargs - one or more keyword arguments - - No return value. - Raise TypeError for invalid keyword argument. - """ - for n in kwargs: - if not hasattr(obj, n): - emsg = "Invalid keyword argument %r" % n - raise TypeError(emsg) - for n, v in kwargs.items(): - setattr(obj, n, v) - return - - -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. - - Attributes - ---------- - cls - the functor class for wrapping the Python function - regname - string name for registering the function in the global - registry of cls functors. This will be the string - identifier for the createByType factory. - fnc - Python function of a floating point argument and optional - float parameters. The parameters need to be registered as - dbattrs in the functor class. The function fnc - must be picklable and it must return a float. - replace - when set replace any functor already registered under - the regname. Otherwise raise RuntimeError when regname - is taken. - dbattrs - optional float parameters of the wrapped function. - These will be registered as double attributes in the - functor class. The wrapped function must be callable as - fnc(x, **dbattrs). - - Return an instance of the functor class. - """ - - class RegisteredUnaryFunction(cls): - - def create(self): - """Create new instance of the same type as self.""" - return RegisteredUnaryFunction() - - def clone(self): - """Return a new duplicate instance of 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. - - Return string identifier. - """ - return regname - - def __call__(self, x): - """Evaluate this functor at x.""" - if dbattrs: - kw = {n: getattr(self, n) for n in dbattrs} - rv = fnc(x, **kw) - else: - rv = fnc(x) - return rv - - def __init__(self): - cls.__init__(self) - for n, v in dbattrs.items(): - setattr(self, n, v) - self._registerDoubleAttribute(n) - return - - def __reduce__(self): - rv = (_regunary_create, (cls, regname), self.__getstate__()) - return rv - - # End of class RegisteredUnaryFunction - - if replace: - RegisteredUnaryFunction._deregisterType(regname) - RegisteredUnaryFunction.__name__ = "User" + cls.__name__ + "_" + regname - RegisteredUnaryFunction.__getstate__ = _pickle_getstate - RegisteredUnaryFunction.__setstate__ = _pickle_setstate - RegisteredUnaryFunction()._registerThisType() - rv = RegisteredUnaryFunction.createByType(regname) - assert type(rv) is RegisteredUnaryFunction - return rv - - -# pickling support functions - - -def _regunary_create(cls, tp): - return cls.createByType(tp) - - -def _pickle_getstate(self): - state = (self.__dict__,) - return state - - -def _pickle_setstate(self, state): - if len(state) != 1: - emsg = "expected 1-item tuple in call to __setstate__, got " + repr( - state - ) - raise ValueError(emsg) - self.__dict__.update(state[0]) - return - - -# End of file diff --git a/src/extensions/srreal_converters.cpp b/src/extensions/srreal_converters.cpp deleted file mode 100644 index 298663d5..00000000 --- a/src/extensions/srreal_converters.cpp +++ /dev/null @@ -1,403 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2009 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* utilities for conversion between C++ and Python types. -* boost python converters are prone to conflicts. -* -*****************************************************************************/ - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include "srreal_converters.hpp" -#include "srreal_validators.hpp" - -#include "srreal_numpy_symbol.hpp" -// numpy/arrayobject.h needs to be included after srreal_numpy_symbol.hpp, -// which defines PY_ARRAY_UNIQUE_SYMBOL. NO_IMPORT_ARRAY indicates -// import_array will be called in the extension module initializer. -#define NO_IMPORT_ARRAY -#include - - -namespace { - -// exception translations ---------------------------------------------------- - -using diffpy::attributes::DoubleAttributeError; -using std::invalid_argument; - -void translate_DoubleAttributeError(const DoubleAttributeError& e) -{ - PyErr_SetString(PyExc_AttributeError, e.what()); -} - - -void translate_invalid_argument(const invalid_argument& e) -{ - PyErr_SetString(PyExc_ValueError, e.what()); -} - - -boost::python::object newNumPyArray(int dim, const int* sz, int typenum) -{ - using namespace std; - using namespace boost; - // copy the size information to an array of npy_intp - valarray npsza(dim); - npy_intp& npsz = npsza[0]; - copy(sz, sz + dim, &npsz); - // create numpy array - python::object rv( - python::handle<>(PyArray_SimpleNew(dim, &npsz, typenum))); - return rv; -} - -} // namespace - -namespace srrealmodule { - -/// this function registers all exception translators -void wrap_exceptions() -{ - using boost::python::register_exception_translator; - register_exception_translator( - &translate_DoubleAttributeError); - register_exception_translator( - &translate_invalid_argument); -} - - -/// helper for creating numpy array of doubles -NumPyArray_DoublePtr createNumPyDoubleArray(int dim, const int* sz) -{ - boost::python::object rvobj = newNumPyArray(dim, sz, NPY_DOUBLE); - PyArrayObject* a = reinterpret_cast(rvobj.ptr()); - double* rvdata = static_cast(PyArray_DATA(a)); - NumPyArray_DoublePtr rv(rvobj, rvdata); - return rv; -} - - -/// helper for creating numpy array of the same shape as the argument -NumPyArray_DoublePtr createNumPyDoubleArrayLike(boost::python::object& obj) -{ - assert(PyArray_Check(obj.ptr())); - PyArrayObject* a = reinterpret_cast(obj.ptr()); - // create numpy array - boost::python::object rvobj( - boost::python::handle<>( - PyArray_NewLikeArray( - a, NPY_CORDER, PyArray_DescrFromType(NPY_DOUBLE), 0))); - PyArrayObject* a1 = reinterpret_cast(rvobj.ptr()); - double* rvdata = static_cast(PyArray_DATA(a1)); - NumPyArray_DoublePtr rv(rvobj, rvdata); - return rv; -} - - -/// helper for creating a numpy array view on a double array -boost::python::object -createNumPyDoubleView(double* data, int dim, const int* sz) -{ - using namespace std; - using namespace boost; - valarray npsza(dim); - npy_intp* npsz = &(npsza[0]); - copy(sz, sz + dim, npsz); - python::object rv( - python::handle<>( - PyArray_SimpleNewFromData(dim, npsz, NPY_DOUBLE, data))); - return rv; -} - - -/// NumPy array view specializations for R3::Vector -boost::python::object viewAsNumPyArray(::diffpy::srreal::R3::Vector& v) -{ - using namespace diffpy::srreal; - double* data = &(v[0]); - int sz = R3::Ndim; - return createNumPyDoubleView(data, 1, &sz); -} - - -/// NumPy array view specializations for R3::Matrix -boost::python::object viewAsNumPyArray(::diffpy::srreal::R3::Matrix& mx) -{ - using namespace diffpy::srreal; - double* data = &(mx(0, 0)); - int sz[2] = {R3::Ndim, R3::Ndim}; - return createNumPyDoubleView(data, 2, sz); -} - - -/// Copy NumPy array to R3::Vector -void assignR3Vector( - ::diffpy::srreal::R3::Vector& dst, boost::python::object& value) -{ - using namespace boost; - using diffpy::srreal::R3::Ndim; - // If value is numpy array, try direct data access - if (PyArray_Check(value.ptr())) - { - PyArrayObject* a = reinterpret_cast( - PyArray_ContiguousFromAny(value.ptr(), NPY_DOUBLE, 1, 1)); - if (a && Ndim == PyArray_DIM(a, 0)) - { - double* p = static_cast(PyArray_DATA(a)); - std::copy(p, p + Ndim, dst.data().begin()); - Py_DECREF(a); - return; - } - Py_XDECREF(a); - } - // handle scalar assignment - python::extract getvalue(value); - if (getvalue.check()) - { - std::fill(dst.data().begin(), dst.data().end(), getvalue()); - return; - } - // finally assign using array view - python::object dstview = viewAsNumPyArray(dst); - dstview[python::slice()] = value; -} - - -/// Copy possible NumPy array to R3::Matrix -void assignR3Matrix( - ::diffpy::srreal::R3::Matrix& dst, boost::python::object& value) -{ - using namespace boost; - using diffpy::srreal::R3::Ndim; - // If value is numpy array, try direct data access - if (PyArray_Check(value.ptr())) - { - PyArrayObject* a = reinterpret_cast( - PyArray_ContiguousFromAny(value.ptr(), NPY_DOUBLE, 2, 2)); - if (a && Ndim == PyArray_DIM(a, 0) && Ndim == PyArray_DIM(a, 1)) - { - double* p = static_cast(PyArray_DATA(a)); - std::copy(p, p + Ndim * Ndim, dst.data().begin()); - Py_DECREF(a); - return; - } - Py_XDECREF(a); - } - // handle scalar assignment - python::extract getvalue(value); - if (getvalue.check()) - { - std::fill(dst.data().begin(), dst.data().end(), getvalue()); - return; - } - // finally assign using array view - python::object dstview = viewAsNumPyArray(dst); - dstview[python::slice()] = value; -} - - -/// helper for creating numpy array of integers -NumPyArray_IntPtr createNumPyIntArray(int dim, const int* sz) -{ - boost::python::object rvobj = newNumPyArray(dim, sz, NPY_INT); - PyArrayObject* a = reinterpret_cast(rvobj.ptr()); - int* rvdata = static_cast(PyArray_DATA(a)); - NumPyArray_IntPtr rv(rvobj, rvdata); - return rv; -} - - -/// efficient conversion of Python object to a QuantityType -diffpy::srreal::QuantityType& -extractQuantityType( - boost::python::object obj, - diffpy::srreal::QuantityType& rv) -{ - using namespace boost; - using diffpy::srreal::QuantityType; - // extract QuantityType directly - python::extract getqt(obj); - if (getqt.check()) return getqt(); - // copy data directly if it is a numpy array of doubles - PyArrayObject* a = PyArray_Check(obj.ptr()) ? - reinterpret_cast(obj.ptr()) : NULL; - bool isdoublenumpyarray = a && - (1 == PyArray_NDIM(a)) && - (NPY_DOUBLE == PyArray_TYPE(a)); - if (isdoublenumpyarray) - { - double* src = static_cast(PyArray_DATA(a)); - npy_intp stride = PyArray_STRIDE(a, 0) / PyArray_ITEMSIZE(a); - rv.resize(PyArray_SIZE(a)); - QuantityType::iterator dst = rv.begin(); - for (; dst != rv.end(); ++dst, src += stride) *dst = *src; - return rv; - } - // otherwise copy elementwise converting each element to a double - python::stl_input_iterator begin(obj), end; - rv.assign(begin, end); - return rv; -} - - -/// efficient conversion of Python object to a numpy array of doubles -NumPyArray_DoublePtr extractNumPyDoubleArray(::boost::python::object& obj) -{ - PyObject* pobj = PyArray_ContiguousFromAny(obj.ptr(), NPY_DOUBLE, 0, 0); - if (!pobj) - { - const char* emsg = "Cannot convert this object to numpy array."; - PyErr_SetString(PyExc_TypeError, emsg); - boost::python::throw_error_already_set(); - abort(); - } - boost::python::object rvobj((boost::python::handle<>(pobj))); - PyArrayObject* a = reinterpret_cast(pobj); - double* rvdata = static_cast(PyArray_DATA(a)); - NumPyArray_DoublePtr rv(rvobj, rvdata); - return rv; -} - - -/// extract double with a support for numpy.int types -double extractdouble(boost::python::object obj) -{ - using namespace boost; - python::extract getx(obj); - if (getx.check()) return getx(); - PyObject* pobj = obj.ptr(); - if (PyArray_CheckScalar(pobj)) - { - double x; - PyArray_CastScalarToCtype(pobj, &x, - PyArray_DescrFromType(NPY_DOUBLE)); - return x; - } - // nothing worked, call getx which will raise an exception - return getx(); -} - - -/// extract integer with a support for numpy.int types -int extractint(boost::python::object obj) -{ - using namespace boost; - python::extract geti(obj); - if (geti.check()) return geti(); - PyObject* pobj = obj.ptr(); - if (PyArray_CheckScalar(pobj)) - { - int rv = PyArray_PyIntAsInt(pobj); - if (rv == -1 && PyErr_Occurred()) python::throw_error_already_set(); - return rv; - } - // nothing worked, call geti which will raise an exception - return geti(); -} - - -/// extract a vector of integers from a numpy array, iterable or scalar -std::vector extractintvector(boost::python::object obj) -{ - using namespace boost::python; - std::vector rv; - // iterable of integers - if (isiterable(obj)) - { - PyArrayObject* a = PyArray_Check(obj.ptr()) ? - reinterpret_cast(obj.ptr()) : NULL; - // handle numpy array of integers - bool isintegernumpyarray = - a && (1 == PyArray_NDIM(a)) && PyArray_ISINTEGER(a); - if (isintegernumpyarray) - { - object aobj = obj; - if (NPY_INT != PyArray_TYPE(a)) - { - object a1(handle<>(PyArray_Cast(a, NPY_INT))); - aobj = a1; - } - PyArrayObject* a1 = reinterpret_cast(aobj.ptr()); - assert(NPY_INT == PyArray_TYPE(a1)); - int* pfirst = static_cast(PyArray_DATA(a1)); - int* plast = pfirst + PyArray_SIZE(a1); - rv.assign(pfirst, plast); - return rv; - } - // otherwise translate every item in the iterable - stl_input_iterator ii(obj), end; - rv.reserve(len(obj)); - for (; ii != end; ++ii) - { - int idx = extractint(*ii); - rv.push_back(idx); - } - return rv; - } - // try to handle it as a scalar - int idx = extractint(obj); - rv.push_back(idx); - return rv; -} - - -/// helper for raising RuntimeError on a call of pure virtual function -void throwPureVirtualCalled(const char* fncname) -{ - std::string emsg = "Pure virtual function '"; - emsg += fncname; - emsg += "' called."; - PyErr_SetString(PyExc_RuntimeError, emsg.c_str()); - boost::python::throw_error_already_set(); -} - -} // namespace srrealmodule - - -namespace diffpy { -namespace srreal { - -/// shared converter that first tries to extract the pointer and then calls -/// diffpy.srreal.structureadapter.createStructureAdapter -StructureAdapterPtr createStructureAdapter(::boost::python::object stru) -{ - using namespace boost::python; - StructureAdapterPtr adpt; - extract getadpt(stru); - if (getadpt.check()) adpt = getadpt(); - else - { - object mod = import("diffpy.srreal.structureadapter"); - object convertinpython = mod.attr("createStructureAdapter"); - adpt = extract(convertinpython(stru)); - } - return adpt; -} - -} // namespace srreal -} // namespace diffpy - -// End of file diff --git a/src/extensions/srreal_converters.hpp b/src/extensions/srreal_converters.hpp deleted file mode 100644 index b888c001..00000000 --- a/src/extensions/srreal_converters.hpp +++ /dev/null @@ -1,439 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2009 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* utilities for conversion between C++ and Python types. -* boost python converters are prone to conflicts. -* -*****************************************************************************/ - -#ifndef SRREAL_CONVERTERS_HPP_INCLUDED -#define SRREAL_CONVERTERS_HPP_INCLUDED - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#if DIFFPY_VERSION < 1004000000 -#error diffpy.srreal requires libdiffpy 1.4.0 or later. -#endif - -/// Conversion function that supports implicit conversions in -/// PairQuantity::eval and PairQuantity::setStructure - -namespace diffpy { -namespace srreal { - -StructureAdapterPtr -createStructureAdapter(::boost::python::object); - -} // namespace srreal -} // namespace diffpy - -namespace srrealmodule { - -using diffpy::srreal::createStructureAdapter; - -/// this macro creates a setter for overloaded method that can accept -/// either instance or a type string -#define DECLARE_BYTYPE_SETTER_WRAPPER(method, wrapper) \ - template \ - void wrapper(T& obj, ::boost::python::object value) \ - { \ - using ::boost::python::extract; \ - extract tp(value); \ - if (tp.check()) obj.method##ByType(tp()); \ - else \ - { \ - typename V::SharedPtr p = extract(value); \ - obj.method(p); \ - } \ - } \ - - -/// this macro defines a wrapper function for a C++ method, -/// that converts the result to numpy array -#define DECLARE_PYARRAY_METHOD_WRAPPER(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj) \ - { \ - ::boost::python::object rv = convertToNumPyArray(obj.method()); \ - return rv; \ - } \ - - -/// this macro defines a wrapper function for a C++ method with one argument, -/// that converts the result to numpy array -#define DECLARE_PYARRAY_METHOD_WRAPPER1(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj, const T1& a1) \ - { \ - ::boost::python::object rv = convertToNumPyArray(obj.method(a1)); \ - return rv; \ - } \ - - -/// this macro defines a wrapper function for a C++ method, -/// that converts the result to numpy character array -#define DECLARE_PYCHARARRAY_METHOD_WRAPPER(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj) \ - { \ - ::boost::python::list lst = convertToPythonList(obj.method()); \ - ::boost::python::object tochararray = \ - ::boost::python::import("numpy").attr("char").attr("array"); \ - ::boost::python::object rv = tochararray(lst); \ - return rv; \ - } \ - - -/// this macro defines a wrapper function for a C++ method, -/// that converts the result to a python set -#define DECLARE_PYSET_METHOD_WRAPPER(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj) \ - { \ - ::boost::python::object rv = convertToPythonSet(obj.method()); \ - return rv; \ - } \ - - -/// this macro defines a wrapper function for a C++ method with one argument, -/// that converts the result to a python set -#define DECLARE_PYSET_METHOD_WRAPPER1(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj, const T1& a1) \ - { \ - ::boost::python::object rv = convertToPythonSet(obj.method(a1)); \ - return rv; \ - } \ - - -/// this macro defines a wrapper for C++ function without arguments -/// that converts the result to a python set -#define DECLARE_PYSET_FUNCTION_WRAPPER(fnc, wrapper) \ - ::boost::python::object wrapper() \ - { \ - ::boost::python::object rv = convertToPythonSet(fnc()); \ - return rv; \ - } \ - - -/// this macro defines a wrapper function for a C++ method, -/// that converts the result to a python list -#define DECLARE_PYLIST_METHOD_WRAPPER(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj) \ - { \ - ::boost::python::object rv = convertToPythonList(obj.method()); \ - return rv; \ - } \ - - -/// this macro defines wrapper for a C++ method with one argument, -/// that convert the result to python list -#define DECLARE_PYLIST_METHOD_WRAPPER1(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj, const T1& a1) \ - { \ - ::boost::python::object rv = convertToPythonList(obj.method(a1)); \ - return rv; \ - } \ - - -/// this macro defines a wrapper function for a C++ method, -/// that converts the result to a python list of NumPy arrays -#define DECLARE_PYLISTARRAY_METHOD_WRAPPER(method, wrapper) \ - template \ - ::boost::python::list wrapper(const T& obj) \ - { \ - ::boost::python::list rvlist; \ - fillPyListWithArrays(rvlist, obj.method()); \ - return rvlist; \ - } \ - - -/// this macro defines a wrapper function for a C++ method, -/// that converts the result to a list of Python sets -#define DECLARE_PYLISTSET_METHOD_WRAPPER(method, wrapper) \ - template \ - ::boost::python::list wrapper(const T& obj) \ - { \ - ::boost::python::list rvlist; \ - fillPyListWithSets(rvlist, obj.method()); \ - return rvlist; \ - } \ - - -/// this macro defines a wrapper function for a C++ method, -/// that converts the result to a python dict -#define DECLARE_PYDICT_METHOD_WRAPPER(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj) \ - { \ - ::boost::python::object rv = convertToPythonDict(obj.method()); \ - return rv; \ - } \ - - -/// this macro defines a wrapper function for a C++ method with one argument, -/// that converts the result to a python dict -#define DECLARE_PYDICT_METHOD_WRAPPER1(method, wrapper) \ - template \ - ::boost::python::object wrapper(const T& obj, const T1& a1) \ - { \ - ::boost::python::object rv = convertToPythonDict(obj.method(a1)); \ - return rv; \ - } \ - - -/// helper template function for DECLARE_PYLISTARRAY_METHOD_WRAPPER -template -void fillPyListWithArrays(::boost::python::list lst, const T& value) -{ - typename T::const_iterator v = value.begin(); - for (; v != value.end(); ++v) lst.append(convertToNumPyArray(*v)); -} - - -/// template function for converting C++ STL container to a python set -template -::boost::python::object -convertToPythonSet(const T& value) -{ - using namespace ::boost; - python::object rvset(python::handle<>(PySet_New(NULL))); - python::object rvset_add = rvset.attr("add"); - typename T::const_iterator ii; - for (ii = value.begin(); ii != value.end(); ++ii) rvset_add(*ii); - return rvset; -} - - -/// helper template function for DECLARE_PYLISTSET_METHOD_WRAPPER -template -void fillPyListWithSets(::boost::python::list lst, const T& value) -{ - typename T::const_iterator v = value.begin(); - for (; v != value.end(); ++v) lst.append(convertToPythonSet(*v)); -} - - -/// Type for numpy array object and a raw pointer to its double data -typedef std::pair NumPyArray_DoublePtr; - - -/// helper for creating numpy array of doubles -NumPyArray_DoublePtr createNumPyDoubleArray(int dim, const int* sz); - - -/// helper for creating numpy array of the same shape as the argument -NumPyArray_DoublePtr createNumPyDoubleArrayLike(boost::python::object& obj); - - -/// helper for creating numpy views on existing double array -boost::python::object createNumPyDoubleView(double*, int dim, const int* sz); - - -/// template function for converting iterables to numpy array of doubles -template -::boost::python::object -convertToNumPyArray(Iter first, Iter last) -{ - int sz = last - first; - NumPyArray_DoublePtr ap = createNumPyDoubleArray(1, &sz); - std::copy(first, last, ap.second); - return ap.first; -} - - -/// specialization for R3::Vector -inline ::boost::python::object -convertToNumPyArray(const ::diffpy::srreal::R3::Vector& value) -{ - return convertToNumPyArray(value.begin(), value.end()); -} - - -/// specialization for R3::Matrix -inline ::boost::python::object -convertToNumPyArray(const ::diffpy::srreal::R3::Matrix& mx) -{ - using namespace diffpy::srreal; - int sz[2] = {R3::Ndim, R3::Ndim}; - NumPyArray_DoublePtr ap = createNumPyDoubleArray(2, sz); - double* xo = ap.second; - *(xo++) = mx(0, 0); *(xo++) = mx(0, 1); *(xo++) = mx(0, 2); - *(xo++) = mx(1, 0); *(xo++) = mx(1, 1); *(xo++) = mx(1, 2); - *(xo++) = mx(2, 0); *(xo++) = mx(2, 1); *(xo++) = mx(2, 2); - return ap.first; -} - - -/// specialization for std::vector -inline ::boost::python::object -convertToNumPyArray(const ::std::vector& vr3v) -{ - using namespace diffpy::srreal; - int n = vr3v.size(); - int sz[2] = {n, R3::Ndim}; - NumPyArray_DoublePtr ap = createNumPyDoubleArray(2, sz); - double* p = ap.second; - std::vector::const_iterator v = vr3v.begin(); - for (; v != vr3v.end(); ++v) - { - const double* pv = &((*v)[0]); - const double* pvlast = pv + R3::Ndim; - for (; pv != pvlast; ++p, ++pv) *p = *pv; - } - assert(p == ap.second + sz[0] * sz[1]); - return ap.first; -} - - -/// specialization for QuantityType -inline ::boost::python::object -convertToNumPyArray(const ::diffpy::srreal::QuantityType& value) -{ - return convertToNumPyArray(value.begin(), value.end()); -} - - -/// NumPy array view specializations for R3::Vector -boost::python::object -viewAsNumPyArray(::diffpy::srreal::R3::Vector&); - - -/// NumPy array view specializations for R3::Matrix -boost::python::object -viewAsNumPyArray(::diffpy::srreal::R3::Matrix&); - - -/// Copy possible NumPy array to R3::Vector -void assignR3Vector( - ::diffpy::srreal::R3::Vector& dst, boost::python::object& value); - - -/// Copy possible NumPy array to R3::Matrix -void assignR3Matrix( - ::diffpy::srreal::R3::Matrix& dst, boost::python::object& value); - - -/// Type for numpy array object and a raw pointer to its double data -typedef std::pair NumPyArray_IntPtr; - - -/// helper for creating numpy array of integers -NumPyArray_IntPtr createNumPyIntArray(int dim, const int* sz); - - -/// specialization for a vector of integers -inline ::boost::python::object -convertToNumPyArray(const ::std::vector& value) -{ - int sz = value.size(); - NumPyArray_IntPtr ap = createNumPyIntArray(1, &sz); - std::copy(value.begin(), value.end(), ap.second); - return ap.first; -} - - -/// template function for converting C++ STL container to a python list -template -::boost::python::list -convertToPythonList(const T& value) -{ - using namespace ::boost; - python::list rvlist; - typename T::const_iterator ii; - for (ii = value.begin(); ii != value.end(); ++ii) rvlist.append(*ii); - return rvlist; -} - - -/// template converter of a C++ map-like container to a python dictionary -template -::boost::python::dict -convertToPythonDict(const T& value) -{ - ::boost::python::dict rv; - typename T::const_iterator ii = value.begin(); - for (; ii != value.end(); ++ii) rv[ii->first] = ii->second; - return rv; -} - - -/// efficient conversion of Python object to a QuantityType -/// If obj wraps a QuantityType reference, return that reference. -/// Otherwise copy the obj values to rv and return rv. -::diffpy::srreal::QuantityType& -extractQuantityType(::boost::python::object obj, - ::diffpy::srreal::QuantityType& rv); - - -/// efficient conversion of Python object to a numpy array of doubles -NumPyArray_DoublePtr extractNumPyDoubleArray(::boost::python::object& obj); - - -/// extract double with a support for numpy numeric types -double extractdouble(::boost::python::object obj); - - -/// extract integer with a support for numpy.int types -int extractint(::boost::python::object obj); - - -/// extract a vector of integers from a numpy array, iterable or scalar -std::vector extractintvector(::boost::python::object obj); - - -/// helper for raising RuntimeError on a call of pure virtual function -void throwPureVirtualCalled(const char* fncname); - - -/// template class for getting overrides to pure virtual method -template -class wrapper_srreal : public ::boost::python::wrapper -{ - public: - - typedef T base; - - protected: - - ::boost::python::override - get_pure_virtual_override(const char* name) const - { - ::boost::python::override f = this->get_override(name); - if (!f) throwPureVirtualCalled(name); - return f; - } -}; - -} // namespace srrealmodule - -// Include shared wrapper definitions ---------------------------------------- - -#include "srreal_converters.ipp" - -#endif // SRREAL_CONVERTERS_HPP_INCLUDED diff --git a/src/extensions/srreal_converters.ipp b/src/extensions/srreal_converters.ipp deleted file mode 100644 index 6ceebe23..00000000 --- a/src/extensions/srreal_converters.ipp +++ /dev/null @@ -1,37 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2011 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Shared declarations of wrapper functions that convert to Python types. -* This file is always included from srreal_converters.hpp. -* -*****************************************************************************/ - -#ifndef SRREAL_CONVERTERS_IPP_INCLUDED -#define SRREAL_CONVERTERS_IPP_INCLUDED - -namespace srrealmodule { - -// definitions of shared template wrappers - -DECLARE_PYARRAY_METHOD_WRAPPER(value, value_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(distances, distances_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(sites0, sites0_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(sites1, sites1_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(directions, directions_asarray) -DECLARE_PYCHARARRAY_METHOD_WRAPPER(types0, types0_aschararray) -DECLARE_PYCHARARRAY_METHOD_WRAPPER(types1, types1_aschararray) - -} // namespace srrealmodule - -#endif // SRREAL_CONVERTERS_IPP_INCLUDED diff --git a/src/extensions/srreal_ext.cpp b/src/extensions/srreal_ext.cpp deleted file mode 100644 index 0bd4dbf4..00000000 --- a/src/extensions/srreal_ext.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* srreal_ext - boost python interface to the srreal C++ codes in libdiffpy -* -*****************************************************************************/ - -#include -#include -#include -#include -#include -#include "srreal_numpy_symbol.hpp" -#include - -// Declaration of the external wrappers -------------------------------------- - -namespace srrealmodule { - -void wrap_libdiffpy_version(); -void wrap_exceptions(); -void wrap_EventTicker(); -void wrap_Attributes(); -void wrap_StructureDifference(); -void wrap_StructureAdapter(); -void wrap_AtomicStructureAdapter(); -void wrap_ObjCrystAdapters(); -void wrap_BaseBondGenerator(); -void wrap_PairQuantity(); -void wrap_PeakWidthModel(); -void wrap_ScatteringFactorTable(); -void wrap_PeakProfile(); -void wrap_BVParametersTable(); -void wrap_BVSCalculator(); -void wrap_PDFBaseline(); -void wrap_PDFEnvelope(); -void wrap_PDFCalculators(); -void wrap_BondCalculator(); -void wrap_AtomRadiiTable(); -void wrap_OverlapCalculator(); - -} // namespace srrealmodule - -namespace { - -#if PY_MAJOR_VERSION >= 3 - void* initialize_numpy() { import_array(); return NULL; } -#else - void initialize_numpy() { import_array(); } -#endif - -} // namespace - -// Module Definitions -------------------------------------------------------- - -BOOST_PYTHON_MODULE(srreal_ext) -{ - using namespace srrealmodule; - // initialize numpy module - initialize_numpy(); - // execute external wrappers - wrap_libdiffpy_version(); - wrap_exceptions(); - wrap_EventTicker(); - wrap_Attributes(); - wrap_StructureDifference(); - wrap_StructureAdapter(); - wrap_AtomicStructureAdapter(); - wrap_ObjCrystAdapters(); - wrap_BaseBondGenerator(); - wrap_PairQuantity(); - wrap_PeakWidthModel(); - wrap_ScatteringFactorTable(); - wrap_PeakProfile(); - wrap_BVParametersTable(); - wrap_BVSCalculator(); - wrap_PDFBaseline(); - wrap_PDFEnvelope(); - wrap_PDFCalculators(); - wrap_BondCalculator(); - wrap_AtomRadiiTable(); - wrap_OverlapCalculator(); - // load Python modules that tweak the wrapped classes - using boost::python::object; - using boost::python::import; - using boost::python::scope; - using boost::python::extract; - using boost::python::dict; - object srreal = import("diffpy.srreal"); - if (!PyObject_HasAttrString(srreal.ptr(), "_final_imports")) - { - dict sysmods = extract(import("sys").attr("modules")); - sysmods.setdefault("diffpy.srreal.srreal_ext", scope()); - object import_now = - import("diffpy.srreal._final_imports").attr("import_now"); - import_now(); - } -} - -// End of file diff --git a/src/extensions/srreal_numpy_symbol.hpp b/src/extensions/srreal_numpy_symbol.hpp deleted file mode 100644 index c31cf476..00000000 --- a/src/extensions/srreal_numpy_symbol.hpp +++ /dev/null @@ -1,29 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Definition of the PY_ARRAY_UNIQUE_SYMBOL for the srreal extension module. -* -*****************************************************************************/ - -#ifndef SRREAL_NUMPY_SYMBOL_HPP_INCLUDED -#define SRREAL_NUMPY_SYMBOL_HPP_INCLUDED - -// Specify the version of NumPy API that will be used. -#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION - -// This macro is required for extension modules that are in several files. -// It must be defined before inclusion of numpy/arrayobject.h -#define PY_ARRAY_UNIQUE_SYMBOL DIFFPY_SRREAL_NUMPY_ARRAY_SYMBOL - -#endif // SRREAL_NUMPY_SYMBOL_HPP_INCLUDED diff --git a/src/extensions/srreal_pickling.cpp b/src/extensions/srreal_pickling.cpp deleted file mode 100644 index 39dff13e..00000000 --- a/src/extensions/srreal_pickling.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2013 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Pickling support that uses serialization of the libdiffpy classes. -* -*****************************************************************************/ - -#include "srreal_pickling.hpp" -#include -#include - -namespace srrealmodule { -namespace { - -using diffpy::srreal::StructureAdapterPtr; - -StructureAdapterPtr -createStructureAdapterFromString(const std::string& content) -{ - StructureAdapterPtr adpt; - diffpy::serialization_fromstring(adpt, content); - return adpt; -} - -} // namespace - -// Non-member functions for StructureAdapterPickleSuite ---------------------- - -boost::python::object -StructureAdapter_constructor() -{ - return boost::python::make_constructor(createStructureAdapterFromString); -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/srreal_pickling.hpp b/src/extensions/srreal_pickling.hpp deleted file mode 100644 index 17068f46..00000000 --- a/src/extensions/srreal_pickling.hpp +++ /dev/null @@ -1,259 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Pickling support that uses serialization of the libdiffpy classes. -* -*****************************************************************************/ - -#ifndef SRREAL_PICKLING_HPP_INCLUDED -#define SRREAL_PICKLING_HPP_INCLUDED - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -namespace srrealmodule { - -inline -void ensure_tuple_length(boost::python::tuple state, const int statelen) -{ - using namespace boost::python; - if (len(state) == statelen) return; - object emsg = ("expected %i-item tuple in call to " - "__setstate__; got %s" % make_tuple(statelen, state)); - PyErr_SetObject(PyExc_ValueError, emsg.ptr()); - throw_error_already_set(); -} - - -template -::boost::python::object serialization_tobytes(const T& tobj) -{ - std::string s = diffpy::serialization_tostring(tobj); - std::string::const_pointer pfirst = s.empty() ? NULL : &(s[0]); - boost::python::object rv( - boost::python::handle<>( - PyBytes_FromStringAndSize(pfirst, s.size())) - ); - return rv; -} - - -template -bool is_wrapper(::boost::python::object& obj) -{ - T* p = ::boost::python::extract(obj); - typedef ::boost::python::wrapper W; - bool rv = (dynamic_cast(p) != NULL); - return rv; -} - - -template -::boost::python::object resolve_state_object(::boost::python::object value) -{ - // return None if value holds a pristine C++ instance of T - ::boost::python::object rv; - if (is_wrapper(value)) rv = value; - return rv; -} - - -template -void assign_state_object(T target, ::boost::python::object value) -{ - if (!value.is_none()) target = value; -} - - -enum {DICT_IGNORE=false, DICT_PICKLE=true}; - -template -class SerializationPickleSuite : public boost::python::pickle_suite -{ - public: - - static boost::python::tuple getstate(boost::python::object obj) - { - using namespace std; - const T& tobj = boost::python::extract(obj); - boost::python::object content = serialization_tobytes(tobj); - boost::python::tuple rv = pickledict ? - boost::python::make_tuple(content, obj.attr("__dict__")) : - boost::python::make_tuple(content); - return rv; - } - - - static void setstate( - boost::python::object obj, boost::python::tuple state) - { - using namespace std; - using namespace boost::python; - T& tobj = extract(obj); - int statelen = pickledict ? 2 : 1; - ensure_tuple_length(state, statelen); - // load the C++ object - string content = extract(state[0]); - diffpy::serialization_fromstring(tobj, content); - // restore the object's __dict__ - if (pickledict) - { - dict d = extract(obj.attr("__dict__")); - d.update(state[1]); - } - } - - static bool getstate_manages_dict() { return pickledict; } - -}; // class SerializationPickleSuite - - -template -class PairQuantityPickleSuite : - public SerializationPickleSuite -{ - private: - - typedef SerializationPickleSuite Super; - - public: - - static boost::python::tuple getstate(boost::python::object obj) - { - using namespace boost::python; - using namespace diffpy::srreal; - // store the original structure object - object stru = obj.attr("getStructure")(); - // temporarily remove structure from the pair quantity - T& pq = extract(obj); - StructureAdapterPtr pstru = - replacePairQuantityStructure(pq, StructureAdapterPtr()); - object state0 = Super::getstate(obj); - // restore the original structure - replacePairQuantityStructure(pq, pstru); - tuple rv = make_tuple(state0, stru); - return rv; - } - - - static void setstate( - boost::python::object obj, boost::python::tuple state) - { - using namespace boost::python; - using namespace diffpy::srreal; - ensure_tuple_length(state, 2); - // restore the state using boost serialization - tuple st0 = extract(state[0]); - Super::setstate(obj, st0); - // restore the structure object - StructureAdapterPtr pstru = extract(state[1]); - T& pq = extract(obj); - replacePairQuantityStructure(pq, pstru); - } - -}; // class PairQuantityPickleSuite - - -template -class StructureAdapterPickleSuite : public boost::python::pickle_suite -{ - public: - - static boost::python::tuple getinitargs( - diffpy::srreal::StructureAdapterPtr adpt) - { - using namespace boost; - python::tuple rv; - // if adapter has been created from Python, we can use the default - // Python constructor, i.e., __init__ with no arguments. - if (frompython(adpt)) return rv; - // otherwise the instance is from a non-wrapped C++ adapter, - // and we need to reconstruct it using boost::serialization - python::object content = serialization_tobytes(adpt); - rv = python::make_tuple(content); - return rv; - } - - - static boost::python::tuple getstate(boost::python::object obj) - { - using namespace boost; - using namespace std; - using diffpy::srreal::StructureAdapterPtr; - StructureAdapterPtr adpt = - python::extract(obj); - python::object content; - // Store serialization data for a Python-built object - if (frompython(adpt)) - { - const T& tobj = boost::python::extract(obj); - content = serialization_tobytes(tobj); - } - python::tuple rv = - python::make_tuple(content, obj.attr("__dict__")); - return rv; - } - - - static void setstate( - boost::python::object obj, boost::python::tuple state) - { - using namespace std; - using namespace boost::python; - ensure_tuple_length(state, 2); - // Restore the C++ data from state[0] for Python built-objects. - // state[0] is None for C++ objects and there is no need to do - // anything as those were already restored by string constructor. - object st0 = state[0]; - if (!st0.is_none()) - { - T& tobj = extract(obj); - string content = extract(st0); - diffpy::serialization_fromstring(tobj, content); - } - // restore the object's __dict__ - dict d = extract(obj.attr("__dict__")); - d.update(state[1]); - } - - - static bool getstate_manages_dict() { return true; } - - - private: - - static bool frompython( - diffpy::srreal::StructureAdapterPtr adpt) - { - return bool(boost::dynamic_pointer_cast(adpt)); - } - -}; // class StructureAdapterPickleSuite - -/// Helper function for creating Python constructor from string -/// that restores c++ non-wrapped classes. -boost::python::object StructureAdapter_constructor(); - -} // namespace srrealmodule - -#endif // SRREAL_PICKLING_HPP_INCLUDED diff --git a/src/extensions/srreal_registry.cpp b/src/extensions/srreal_registry.cpp deleted file mode 100644 index 6a4df0c4..00000000 --- a/src/extensions/srreal_registry.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2016 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Utilities for wrapping classes that derive from HasClassRegistry. -* -*****************************************************************************/ - -#include -#include - -namespace srrealmodule { - -using namespace boost::python; - -void register_for_cleanup(PyObject* pobj) -{ - object obj(borrowed(pobj)); - object reg = import("diffpy.srreal._cleanup").attr("registerForCleanUp"); - reg(obj); -} - - -/// get dictionary of Python-defined docstrings for the cls class. -object get_registry_docstrings(object& cls) -{ - object mod = import("diffpy.srreal._docstrings"); - object getdocs = mod.attr("get_registry_docstrings"); - object rv = getdocs(cls); - return rv; -} - - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/srreal_registry.hpp b/src/extensions/srreal_registry.hpp deleted file mode 100644 index 7df825d9..00000000 --- a/src/extensions/srreal_registry.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2016 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Utilities for wrapping classes that derive from HasClassRegistry. -* -*****************************************************************************/ - -#ifndef SRREAL_REGISTRY_HPP_INCLUDED -#define SRREAL_REGISTRY_HPP_INCLUDED - -#include -#include - -namespace srrealmodule { - -/// helper for remembering instances of Python-derived class. -void register_for_cleanup(PyObject*); - - -/// template class for handling Python Wrapper classes in C++ class registry -template -class wrapper_registry_configurator -{ - typedef typename T::SharedPtr TSharedPtr; - typedef typename T::SharedPtr::element_type* TPtr; - - public: - - // constructor - wrapper_registry_configurator() : mcptr(0), mpyptr(0) { } - - // methods - /// the fetch method should be called only from the wrapped method - /// create() to remember pointers to the last Python object and - /// the C++ instance that it wraps. - TSharedPtr fetch(::boost::python::object& obj) const - { - TSharedPtr p = ::boost::python::extract(obj); - mcptr = p.get(); - mpyptr = obj.ptr(); - return p; - } - - /// the setup function should be executed just once from the - /// HasClassRegistry::setupRegisteredObject method in the wrapper - /// class. This ensures the Python object in a prototype factory - /// stays alive when the process is shut down. - void setup(TSharedPtr ptr) const - { - assert(mcptr && mcptr == ptr.get()); - register_for_cleanup(mpyptr); - mcptr = 0; - mpyptr = 0; - } - - private: - - // data - mutable TPtr mcptr; - mutable PyObject* mpyptr; -}; - - -/// retrieve a dictionary of Python-defined docstrings for the cls class. -::boost::python::object get_registry_docstrings(::boost::python::object& cls); - - -/// helper wrapper functions for return value conversions. - -template -::boost::python::object getAliasedTypes_asdict() -{ - return convertToPythonDict(W::getAliasedTypes()); -} - -template -::boost::python::object getRegisteredTypes_asset() -{ - return convertToPythonSet(W::getRegisteredTypes()); -} - - -/// template function that wraps HasClassRegistry methods -template -C& wrap_registry_methods(C& boostpythonclass) -{ - namespace bp = boost::python; - using namespace boost::python; - typedef typename C::wrapped_type::base B; - typedef extract CString; - // get docstrings for the class registry methods. - object d = get_registry_docstrings(boostpythonclass); - const char* doc_create = CString(d["create"]); - const char* doc_clone = CString(d["clone"]); - const char* doc_type = CString(d["type"]); - const char* doc__registerThisType = CString(d["_registerThisType"]); - const char* doc__aliasType = CString(d["_aliasType"]); - const char* doc__deregisterType = CString(d["_deregisterType"]); - const char* doc_createByType = CString(d["createByType"]); - const char* doc_isRegisteredType = CString(d["isRegisteredType"]); - const char* doc_getAliasedTypes = CString(d["getAliasedTypes"]); - const char* doc_getRegisteredTypes = CString(d["getRegisteredTypes"]); - // define the class registry related methods. - boostpythonclass - .def("create", &B::create, doc_create) - .def("clone", &B::clone, doc_clone) - .def("type", &B::type, - return_value_policy(), - doc_type) - .def("_registerThisType", &B::registerThisType, - doc__registerThisType) - .def("_aliasType", &B::aliasType, - (bp::arg("tp"), bp::arg("alias")), doc__aliasType) - .staticmethod("_aliasType") - .def("_deregisterType", &B::deregisterType, - bp::arg("tp"), doc__deregisterType) - .staticmethod("_deregisterType") - .def("createByType", &B::createByType, - bp::arg("tp"), doc_createByType) - .staticmethod("createByType") - .def("isRegisteredType", &B::isRegisteredType, - bp::arg("tp"), doc_isRegisteredType) - .staticmethod("isRegisteredType") - .def("getAliasedTypes", getAliasedTypes_asdict, - doc_getAliasedTypes) - .staticmethod("getAliasedTypes") - .def("getRegisteredTypes", getRegisteredTypes_asset, - doc_getRegisteredTypes) - .staticmethod("getRegisteredTypes") - ; - return boostpythonclass; -} - - -} // namespace srrealmodule - -#endif // SRREAL_REGISTRY_HPP_INCLUDED diff --git a/src/extensions/srreal_validators.cpp b/src/extensions/srreal_validators.cpp deleted file mode 100644 index 4a3cb217..00000000 --- a/src/extensions/srreal_validators.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2013 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Helper functions for argument checking. -* -*****************************************************************************/ - -#include -#include - -#include "srreal_validators.hpp" - -namespace srrealmodule { - -using namespace boost::python; - -void ensure_index_bounds(int idx, int lo, int hi) -{ - if (idx < lo || idx >= hi) - { - PyErr_SetString(PyExc_IndexError, "Index out of range."); - throw_error_already_set(); - } -} - - -void ensure_non_negative(int value) -{ - if (value < 0) - { - PyErr_SetString(PyExc_ValueError, "Value cannot be negative."); - throw_error_already_set(); - } -} - - -bool isiterable(boost::python::object obj) -{ - using boost::python::import; -#if PY_MAJOR_VERSION >= 3 - object Iterable = import("collections.abc").attr("Iterable"); -#else - object Iterable = import("collections").attr("Iterable"); -#endif - bool rv = (1 == PyObject_IsInstance(obj.ptr(), Iterable.ptr())); - return rv; -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/srreal_validators.hpp b/src/extensions/srreal_validators.hpp deleted file mode 100644 index f123498f..00000000 --- a/src/extensions/srreal_validators.hpp +++ /dev/null @@ -1,30 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2013 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Helper functions for argument checking. -* -*****************************************************************************/ - -#ifndef SRREAL_VALIDATORS_HPP_INCLUDED -#define SRREAL_VALIDATORS_HPP_INCLUDED - -namespace srrealmodule { - -void ensure_index_bounds(int idx, int lo, int hi); -void ensure_non_negative(int value); -bool isiterable(boost::python::object obj); - -} // namespace srrealmodule - -#endif // SRREAL_VALIDATORS_HPP_INCLUDED diff --git a/src/extensions/wrap_AtomRadiiTable.cpp b/src/extensions/wrap_AtomRadiiTable.cpp deleted file mode 100644 index ed91a8ac..00000000 --- a/src/extensions/wrap_AtomRadiiTable.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2011 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the AtomRadiiTable class. -* -*****************************************************************************/ - -#include -#include -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_registry.hpp" - -#include -#include - -namespace srrealmodule { -namespace nswrap_AtomRadiiTable { - -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_AtomRadiiTable = "\ -Base class for looking up empirical atom radii.\n\ -This class has virtual methods and cannot be used as is.\n\ -\n\ -A derived class has to overload the following methods:\n\ -\n\ - create(self)\n\ - clone(self)\n\ - type(self)\n\ - _standardLookup(self, smbl)\n\ -\n\ -Derived class can be added to the global registry of AtomRadiiTable\n\ -types by calling the _registerThisType method with any instance.\n\ -"; - -const char* doc_AtomRadiiTable_lookup = "\ -Return empirical radius of an atom in Angstroms.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope\n\ -\n\ -Return atom radius in Angstroms.\n\ -This method cannot be overloaded in Python.\n\ -"; - -const char* doc_AtomRadiiTable__standardLookup = "\ -Standard lookup of empirical atom radius.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope\n\ -\n\ -Return atom radius in Angstroms.\n\ -Raise ValueError for unknown atom symbol.\n\ -This method must be overloaded in a derived class.\n\ -"; - -const char* doc_AtomRadiiTable_setCustom = "\ -Define custom radius for a specified atom type.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope\n\ -radius -- custom radius that will be returned by the lookup method\n\ -\n\ -No return value.\n\ -"; - -const char* doc_AtomRadiiTable_fromString = "\ -Define custom radius for one or more atom types from string.\n\ -\n\ -s -- string with custom atom radii in 'A1:r1, A2:r2, ...' format.\n\ -\n\ -No return value.\n\ -Raise ValueError for an invalid string format.\n\ -"; - -const char* doc_AtomRadiiTable_resetCustom = "\ -Remove custom radius for the specified atom type.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope\n\ -\n\ -No return value.\n\ -"; - -const char* doc_AtomRadiiTable_resetAll = "\ -Reset all custom radii defined in this table.\n\ -"; - -const char* doc_AtomRadiiTable_getAllCustom = "\ -Return a dictionary of all custom atom radii defined in this table.\n\ -"; - -const char* doc_AtomRadiiTable_toString = "\ -Return string of all custom atom radii in 'A1:r1, A2:r2, ...' format.\n\ -\n\ -separator -- string separator between 'A1:r1' entries, by default ','\n\ -\n\ -Return string.\n\ -"; - -const char* doc_ConstantRadiiTable = "\ -Atom radii table with the same radius for all atoms, by default 0.\n\ -\n\ -See setDefault() for changing the default radius or setCustom()\n\ -and fromString() for setting a special radius for selected atoms.\n\ -"; - -const char* doc_ConstantRadiiTable_create = "\ -Return a new instance of ConstantRadiiTable.\n\ -"; - -const char* doc_ConstantRadiiTable_clone = "\ -Return a duplicate of this ConstantRadiiTable object\n\ -"; - -const char* doc_ConstantRadiiTable__standardLookup = "\ -Return empirical radius of the given atom in Angstroms.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope\n\ -\n\ -Return atom radius in Angstroms.\n\ -This method cannot be overloaded in Python.\n\ -"; - -const char* doc_ConstantRadiiTable_setDefault = "\ -Set radius that is by default returned for all atoms.\n\ -"; - -const char* doc_ConstantRadiiTable_getDefault = "\ -Return the value of the default atom radius.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -DECLARE_PYDICT_METHOD_WRAPPER(getAllCustom, getAllCustom_asdict) - -// Helper class for overloads of AtomRadiiTable methods from Python - -class AtomRadiiTableWrap : - public AtomRadiiTable, - public wrapper_srreal -{ - public: - - // HasClassRegistry methods - - AtomRadiiTablePtr create() const - { - object rv = this->get_pure_virtual_override("create")(); - return mconfigurator.fetch(rv); - } - - AtomRadiiTablePtr clone() const - { - return this->get_pure_virtual_override("clone")(); - } - - const std::string& type() const - { - object tp = this->get_pure_virtual_override("type")(); - mtype = extract(tp); - return mtype; - } - - // own methods - - double standardLookup(const std::string& smbl) const - { - return this->get_pure_virtual_override("_standardLookup")(smbl); - } - - protected: - - // HasClassRegistry method - - void setupRegisteredObject(AtomRadiiTablePtr p) const - { - mconfigurator.setup(p); - } - - private: - - mutable std::string mtype; - wrapper_registry_configurator mconfigurator; - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - using boost::serialization::base_object; - ar & base_object(*this); - } - -}; // class AtomRadiiTableWrap - -} // namespace nswrap_AtomRadiiTable - -// Wrapper definition -------------------------------------------------------- - -void wrap_AtomRadiiTable() -{ - using namespace nswrap_AtomRadiiTable; - using boost::noncopyable; - - class_ - atomradiitable("AtomRadiiTable", doc_AtomRadiiTable); - wrap_registry_methods(atomradiitable) - .def("lookup", - &AtomRadiiTable::lookup, arg("smbl"), - doc_AtomRadiiTable_lookup) - .def("_standardLookup", - &AtomRadiiTable::standardLookup, - arg("smbl"), doc_AtomRadiiTable__standardLookup) - .def("setCustom", - &AtomRadiiTable::setCustom, - (arg("smbl"), arg("radius")), - doc_AtomRadiiTable_setCustom) - .def("fromString", - &AtomRadiiTable::fromString, - doc_AtomRadiiTable_fromString) - .def("resetCustom", - &AtomRadiiTable::resetCustom, arg("smbl"), - doc_AtomRadiiTable_resetCustom) - .def("resetAll", - &AtomRadiiTable::resetAll, - doc_AtomRadiiTable_resetAll) - .def("getAllCustom", - getAllCustom_asdict, - doc_AtomRadiiTable_getAllCustom) - .def("toString", - &AtomRadiiTable::toString, arg("separator")=",", - doc_AtomRadiiTable_toString) - .def_pickle(SerializationPickleSuite()) - ; - - register_ptr_to_python(); - - class_ >( - "ConstantRadiiTable", doc_ConstantRadiiTable) - // docstring updates - .def("create", &ConstantRadiiTable::create, - doc_ConstantRadiiTable_create) - .def("clone", &ConstantRadiiTable::clone, - doc_ConstantRadiiTable_clone) - .def("_standardLookup", - &ConstantRadiiTable::standardLookup, - arg("smbl"), doc_ConstantRadiiTable__standardLookup) - // own methods - .def("setDefault", - &ConstantRadiiTable::setDefault, - arg("radius"), - doc_ConstantRadiiTable_setDefault) - .def("getDefault", - &ConstantRadiiTable::getDefault, - doc_ConstantRadiiTable_getDefault) - .def_pickle(SerializationPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// Serialization ------------------------------------------------------------- - -BOOST_CLASS_EXPORT(srrealmodule::nswrap_AtomRadiiTable::AtomRadiiTableWrap) - -// End of file diff --git a/src/extensions/wrap_AtomicStructureAdapter.cpp b/src/extensions/wrap_AtomicStructureAdapter.cpp deleted file mode 100644 index e3ce6b39..00000000 --- a/src/extensions/wrap_AtomicStructureAdapter.cpp +++ /dev/null @@ -1,708 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2013 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the Atom, AtomicStructureAdapter, PeriodicStructureAdapter -* and CrystalStructureAdapter classes. -* only for accessing the C++ created StructureAdapter instances and there -* is no support for method overrides from Python. -* -*****************************************************************************/ - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_validators.hpp" - -namespace srrealmodule { - -// declarations -void sync_StructureDifference(boost::python::object obj); - -namespace nswrap_AtomicStructureAdapter { - -using namespace boost; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -// class Atom - -const char* doc_Atom = "\ -Data for one atom site in AtomicStructureAdapter.\n\ -\n\ -Instance data:\n\ -\n\ -atomtype -- string symbol for element, ion or isotope\n\ -xyz_cartn -- Cartesian coordinates viewed as NumPy array\n\ -occupancy -- fractional occupancy of this atom site\n\ -anisotropy -- boolean flag for anisotropic displacements at this site\n\ -uij_cartn -- matrix of anisotropic displacements parameters viewed\n\ - as NumPy array\n\ -\n\ -Note xyz_cartn and uij_cartn are NumPy arrays with a direct\n\ -view to the data in C++ class. Do not resize or reshape.\n\ -"; - -const char* doc_Atom_init_copy = "\ -Make a deep copy of an existing Atom.\n\ -"; -const char* doc_Atom_xic = "Vector element in xyz_cartn."; -const char* doc_Atom_occ = "Fractional occupancy of this atom."; -const char* doc_Atom_anisotropy = - "Boolean flag for anisotropic displacements."; -const char* doc_Atom_uijc = "Matrix element in uij_cartn."; - -// class AtomicStructureAdapter - -const char* doc_AtomicStructureAdapter = "\ -Structure adapter for a non-periodic group of atoms.\n\ -\n\ -This class supports indexing and iteration similar to Python list.\n\ -"; - -const char* doc_AtomicStructureAdapter_clone = "\ -Return a deep copy of this AtomicStructureAdapter.\n\ -\n\ -This method can be overloaded in a derived class.\n\ -"; - -const char* doc_AtomicStructureAdapter_insert = "\ -Insert atom at a specified site index in this adapter.\n\ -\n\ -index -- integer index for adding the new atom. May be negative\n\ - as per Python indexing conventions.\n\ -atom -- Atom object to be inserted.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_AtomicStructureAdapter_append = "\ -Add atom to the end of this adapter.\n\ -\n\ -atom -- Atom object to be inserted.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_AtomicStructureAdapter_pop = "\ -Remove and return Atom at the specified site index.\n\ -\n\ -index -- integer index of the removed atom. May be negative\n\ - as per Python indexing conventions.\n\ -\n\ -Return the removed Atom.\n\ -"; - -const char* doc_AtomicStructureAdapter_clear = "\ -Remove all atoms from the structure.\n\ -"; - -const char* doc_AtomicStructureAdapter_reserve = "\ -Reserve memory for a specified number of atoms.\n\ -Although not required, calling this method can save memory and\n\ -avoid reallocation of Atom instances.\n\ -\n\ -sz -- expected number of atoms in this adapter.\n\ -\n\ -No return value.\n\ -"; - -// class PeriodicStructureAdapter - -const char* doc_PeriodicStructureAdapter = "\ -Group of atoms with periodic boundary conditions, but no\n\ -space group symmetry.\n\ -"; - -const char* doc_PeriodicStructureAdapter_clone = "\ -Return a deep copy of this PeriodicStructureAdapter.\n\ -\n\ -This method can be overloaded in a derived class.\n\ -"; - -const char* doc_PeriodicStructureAdapter_getLatPar = "\ -Get lattice parameters for the periodic unit cell.\n\ -\n\ -Return a tuple of (a, b, c, alpha, beta, gamma), where cell\n\ -angles are in degrees.\n\ -"; - -const char* doc_PeriodicStructureAdapter_setLatPar = "\ -Set lattice parameters of the periodic unit cell.\n\ -\n\ -a, b, c -- cell lengths in Angstroms.\n\ -alphadeg, betadeg, gammadeg -- cell angles in degrees.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_PeriodicStructureAdapter_toCartesian = "\ -Convert atom position and displacement parameters to Cartesian coordinates.\n\ -\n\ -atom -- Atom object to be converted to Cartesian coordinates.\n\ -\n\ -No return value. This updates the xyz_cartn and uij_cartn\n\ -attributes of the passed atom inplace.\n\ -"; - -const char* doc_PeriodicStructureAdapter_toFractional = "\ -Convert atom position and displacement parameters to fractional coordinates.\n\ -\n\ -atom -- Atom object to be converted to fractional coordinates.\n\ -\n\ -No return value. This updates the xyz_cartn and uij_cartn\n\ -attributes of the passed atom inplace.\n\ -"; - -// class CrystalStructureAdapter - -const char* doc_CrystalStructureAdapter = "\ -Structure with asymmetric unit cell and a list of space group symmetry\n\ -operations. The indexed atoms relate to the asymmetric unit cell.\n\ -"; - -const char* doc_CrystalStructureAdapter_clone = "\ -Return a deep copy of this CrystalStructureAdapter.\n\ -\n\ -This method can be overloaded in a derived class.\n\ -"; - -const char* doc_CrystalStructureAdapter_symmetryprecision = "\n\ -Distance threshold for assuming symmetry generated sites equal.\n\ -"; - -const char* doc_CrystalStructureAdapter_countSymOps = "\ -Return number of space group symmetry operations stored in the adapter.\n\ -"; - -const char* doc_CrystalStructureAdapter_clearSymOps = "\ -Clear all symmetry operations from the adapter.\n\ -"; - -const char* doc_CrystalStructureAdapter_addSymOp = "\ -Add one space group symmetry operation to the adapter.\n\ -\n\ -R -- rotation matrix for the symmetry operation.\n\ -t -- translation vector in the symmetry operation.\n\ -\n\ -No return value. R and t are in fractional coordinates.\n\ -"; - -const char* doc_CrystalStructureAdapter_getSymOp = "\ -Get rotation and translation for the specified symmetry operation.\n\ -\n\ -index -- zero based index of a previously defined symmetry operation.\n\ -\n\ -Return a tuple (R, t) of symmetry rotation matrix and translation\n\ -vector in fractional coordinate system.\n\ -"; - -const char* doc_CrystalStructureAdapter_getEquivalentAtoms = "\ -Return symmetry equivalent atoms for a site in the asymmetric unit.\n\ -\n\ -index -- zero-based index of an atom in the asymmetric unit.\n\ -\n\ -Return a list of all symmetry equivalent atoms in the periodic unit cell\n\ -Atom positions and displacement parameters are in Cartesian coordinates.\n\ -"; - -const char* doc_CrystalStructureAdapter_expandLatticeAtom = "\ -Perform symmetry expansion for an Atom in fractional coordinates.\n\ -\n\ -atom -- Atom object with xyz_cartn and uij_cartn referring to position\n\ - and displacement parameters in fractional coordinates\n\ -\n\ -Return a list of all symmetry equivalent atoms in the periodic unit cell\n\ -Positions and displacement parameters are in fractional coordinates.\n\ -"; - -const char* doc_CrystalStructureAdapter_updateSymmetryPositions = "\ -Force update of symmetry equivalent positions for the asymmetric unit.\n\ -\n\ -The getEquivalentAtoms function calls this automatically if internal\n\ -symmetry operations changed or if size of the asymmetric unit changed.\n\ -An explicit call may be necessary for a more subtle changes such as\n\ -moving one asymmetric site. The updateSymmetryPositions is always\n\ -implicitly called from createBondGenerator.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -// Wrapper helpers for the class Atom - -object get_xyz_cartn(Atom& a) -{ - return viewAsNumPyArray(a.xyz_cartn); -} - -void set_xyz_cartn(Atom& a, object value) -{ - assignR3Vector(a.xyz_cartn, value); -} - - -object get_uij_cartn(Atom& a) -{ - return viewAsNumPyArray(a.uij_cartn); -} - -void set_uij_cartn(Atom& a, object& value) -{ - assignR3Matrix(a.uij_cartn, value); -} - - -template -double get_xyz(const Atom& a) -{ - return a.xyz_cartn[i]; -} - -template -void set_xyz(Atom& a, object value) -{ - a.xyz_cartn[i] = extractdouble(value); -} - - -double get_occ(const Atom& a) -{ - return a.occupancy; -} - -void set_occ(Atom& a, object value) -{ - a.occupancy = extractdouble(value); -} - - -bool get_anisotropy(const Atom& a) -{ - return a.anisotropy; -} - -void set_anisotropy(Atom& a, object value) -{ - a.anisotropy = bool(value); -} - - -template -double get_uc(const Atom& a) -{ - assert(i <= j); - return a.uij_cartn(i, j); -} - -template -void set_uc(Atom& a, object value) -{ - assert(i <= j); - a.uij_cartn(i, j) = extractdouble(value); - if (i != j) a.uij_cartn(j, i) = a.uij_cartn(i, j); -} - -// template wrapper class for overloading of clone and _customPQConfig - -template -class MakeWrapper : public T, public wrapper_srreal -{ - public: - - StructureAdapterPtr clone() const - { - override f = this->get_override("clone"); - if (f) return f(); - else return this->default_clone(); - } - - StructureAdapterPtr default_clone() const - { - return this->T::clone(); - } - - - void customPQConfig(PairQuantity* pq) const - { - override f = this->get_override("_customPQConfig"); - if (f) f(ptr(pq)); - else this->default_customPQConfig(pq); - } - - void default_customPQConfig(PairQuantity* pq) const - { - this->T::customPQConfig(pq); - } - - - StructureDifference diff(StructureAdapterConstPtr other) const - { - override f = this->get_override("diff"); - if (f) - { - python::object sdobj = f(other); - sync_StructureDifference(sdobj); - StructureDifference& sd = - python::extract(sdobj); - return sd; - } - return this->default_diff(other); - } - - StructureDifference default_diff(StructureAdapterConstPtr other) const - { - return this->T::diff(other); - } - - private: - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - ar & boost::serialization::base_object(*this); - } - -}; // class MakeWrapper - -// Wrapper helpers for class AtomicStructureAdapter - -typedef MakeWrapper AtomicStructureAdapterWrap; -typedef boost::shared_ptr AtomicStructureAdapterWrapPtr; - -class atomadapter_indexing : public vector_indexing_suite< - AtomicStructureAdapter, false, atomadapter_indexing> -{ - public: - - typedef AtomicStructureAdapter Container; - - static object - get_slice(Container& container, index_type from, index_type to) - { - // make sure slice is of a correct type and has a copy - // of any additional structure data. - StructureAdapterPtr rv = container.clone(); - AtomicStructureAdapterPtr rva; - rva = boost::static_pointer_cast(rv); - // handle index ranges for a valid and empty slice - if (from <= to) - { - rva->erase(rva->begin() + to, rva->end()); - rva->erase(rva->begin(), rva->begin() + from); - } - else rva->clear(); - // save memory by making a new copy for short slices - const index_type halflength = rva->countSites() / 2; - const bool longslice = ((to - from) > halflength); - object pyrv(longslice ? rv : rv->clone()); - return pyrv; - } - - - static void - append(Container& container, data_type const& v) - { - container.append(v); - } - -}; - - -void atomadapter_insert(AtomicStructureAdapter& adpt, const Atom& a, int idx) -{ - ensure_index_bounds(idx, -int(adpt.size()), adpt.size() + 1); - int idx1 = (idx >= 0) ? idx : int(adpt.size()) - idx; - adpt.insert(idx1, a); -} - - -Atom atomadapter_pop(AtomicStructureAdapter& adpt, int idx) -{ - ensure_index_bounds(idx, -int(adpt.size()), adpt.size()); - int idx1 = (idx >= 0) ? idx : int(adpt.size()) - idx; - Atom a = adpt[idx1]; - adpt.erase(idx1); - return a; -} - - -void atomadapter_reserve(AtomicStructureAdapter& adpt, int sz) -{ - ensure_non_negative(sz); - adpt.reserve(sz); -} - -// Wrapper helpers for class PeriodicStructureAdapter - -typedef MakeWrapper PeriodicStructureAdapterWrap; -typedef boost::shared_ptr PeriodicStructureAdapterWrapPtr; - -python::tuple periodicadapter_getlatpar(const PeriodicStructureAdapter& adpt) -{ - const Lattice& L = adpt.getLattice(); - python::tuple rv = python::make_tuple( - L.a(), L.b(), L.c(), L.alpha(), L.beta(), L.gamma()); - return rv; -} - -// Wrapper helpers for class CrystalStructureAdapter - -typedef MakeWrapper CrystalStructureAdapterWrap; -typedef boost::shared_ptr CrystalStructureAdapterWrapPtr; - -double -crystaladapter_getsymmetryprecision(const CrystalStructureAdapter& adpt) -{ - return adpt.getSymmetryPrecision(); -} - - -void crystaladapter_addsymop(CrystalStructureAdapter& adpt, - python::object R, python::object t) -{ - static SymOpRotTrans op; - assignR3Matrix(op.R, R); - assignR3Vector(op.t, t); - adpt.addSymOp(op); -} - - -python::tuple -crystaladapter_getsymop(const CrystalStructureAdapter& adpt, int idx) -{ - ensure_index_bounds(idx, 0, adpt.countSymOps()); - const SymOpRotTrans& op = adpt.getSymOp(idx); - python::tuple rv = python::make_tuple( - convertToNumPyArray(op.R), convertToNumPyArray(op.t)); - return rv; -} - - -DECLARE_PYLIST_METHOD_WRAPPER1(getEquivalentAtoms, getEquivalentAtoms_aslist) - -python::object crystaladapter_getequivalentatoms( - const CrystalStructureAdapter& adpt, int idx) -{ - ensure_index_bounds(idx, 0, adpt.countSymOps()); - return getEquivalentAtoms_aslist(adpt, idx); -} - - -DECLARE_PYLIST_METHOD_WRAPPER1(expandLatticeAtom, expandLatticeAtom_aslist) - -} // namespace nswrap_AtomicStructureAdapter - -// declare shared docstrings from wrap_StructureAdapter.cpp - -extern const char* doc_StructureAdapter___init__fromstring; -extern const char* doc_StructureAdapter__customPQConfig; -extern const char* doc_StructureAdapter_diff; - -// Wrapper definitions ------------------------------------------------------- - -void wrap_AtomicStructureAdapter() -{ - namespace bp = boost::python; - using namespace nswrap_AtomicStructureAdapter; - using diffpy::srreal::hash_value; - - // class Atom - class_ atom_class("Atom", doc_Atom); - // first define copy constructor and property helper methods - atom_class - .def(init(bp::arg("atom"), doc_Atom_init_copy)) - .def(self == self) - .def(self != self) - .def(self < self) - .def(self > self) - .def(self <= self) - .def(self >= self) - .def("__hash__", hash_value) - .def("_get_xyz_cartn", - get_xyz_cartn, - with_custodian_and_ward_postcall<0,1>()) - .def("_get_uij_cartn", - get_uij_cartn, - with_custodian_and_ward_postcall<0,1>()) - ; - // now we can finalize the Atom class interface - atom_class - .def_readwrite("atomtype", &Atom::atomtype) - .add_property("xyz_cartn", - atom_class.attr("_get_xyz_cartn"), - set_xyz_cartn) - .add_property("xc", get_xyz<0>, set_xyz<0>, doc_Atom_xic) - .add_property("yc", get_xyz<1>, set_xyz<1>, doc_Atom_xic) - .add_property("zc", get_xyz<2>, set_xyz<2>, doc_Atom_xic) - .add_property("occupancy", get_occ, set_occ, doc_Atom_occ) - .add_property("anisotropy", get_anisotropy, set_anisotropy, - doc_Atom_anisotropy) - .add_property("uij_cartn", - atom_class.attr("_get_uij_cartn"), - set_uij_cartn) - .add_property("uc11", get_uc<0, 0>, set_uc<0, 0>, doc_Atom_uijc) - .add_property("uc22", get_uc<1, 1>, set_uc<1, 1>, doc_Atom_uijc) - .add_property("uc33", get_uc<2, 2>, set_uc<2, 2>, doc_Atom_uijc) - .add_property("uc12", get_uc<0, 1>, set_uc<0, 1>, doc_Atom_uijc) - .add_property("uc13", get_uc<0, 2>, set_uc<0, 2>, doc_Atom_uijc) - .add_property("uc23", get_uc<1, 2>, set_uc<1, 2>, doc_Atom_uijc) - .def_pickle(SerializationPickleSuite()) - ; - - // class AtomicStructureAdapter - class_, - noncopyable, AtomicStructureAdapterWrapPtr>( - "AtomicStructureAdapter", doc_AtomicStructureAdapter) - .def("__init__", StructureAdapter_constructor(), - doc_StructureAdapter___init__fromstring) - .def(atomadapter_indexing()) - .def(self == self) - .def(self != self) - .def("clone", - &AtomicStructureAdapter::clone, - &AtomicStructureAdapterWrap::default_clone, - doc_AtomicStructureAdapter_clone) - .def("_customPQConfig", - &AtomicStructureAdapter::customPQConfig, - &AtomicStructureAdapterWrap::default_customPQConfig, - python::arg("pqobj"), - doc_StructureAdapter__customPQConfig) - .def("diff", - &AtomicStructureAdapter::diff, - &AtomicStructureAdapterWrap::default_diff, - python::arg("other"), - doc_StructureAdapter_diff) - .def("insert", atomadapter_insert, - (bp::arg("index"), bp::arg("atom")), - doc_AtomicStructureAdapter_insert) - .def("append", &AtomicStructureAdapter::append, - doc_AtomicStructureAdapter_append) - .def("pop", atomadapter_pop, - bp::arg("index"), doc_AtomicStructureAdapter_pop) - .def("clear", &AtomicStructureAdapter::clear, - doc_AtomicStructureAdapter_clear) - .def("reserve", atomadapter_reserve, - bp::arg("sz"), doc_AtomicStructureAdapter_reserve) - .def_pickle(StructureAdapterPickleSuite()) - ; - - // class PeriodicStructureAdapter - class_, - noncopyable, PeriodicStructureAdapterWrapPtr>( - "PeriodicStructureAdapter", doc_PeriodicStructureAdapter) - .def("__init__", StructureAdapter_constructor(), - doc_StructureAdapter___init__fromstring) - .def(self == self) - .def(self != self) - .def("clone", - &PeriodicStructureAdapter::clone, - &PeriodicStructureAdapterWrap::default_clone, - doc_PeriodicStructureAdapter_clone) - .def("_customPQConfig", - &PeriodicStructureAdapter::customPQConfig, - &PeriodicStructureAdapterWrap::default_customPQConfig, - python::arg("pqobj"), - doc_StructureAdapter__customPQConfig) - .def("diff", - &PeriodicStructureAdapter::diff, - &PeriodicStructureAdapterWrap::default_diff, - python::arg("other"), - doc_StructureAdapter_diff) - .def("getLatPar", periodicadapter_getlatpar, - doc_PeriodicStructureAdapter_getLatPar) - .def("setLatPar", &PeriodicStructureAdapter::setLatPar, - (bp::arg("a"), bp::arg("b"), bp::arg("c"), - bp::arg("alphadeg"), bp::arg("betadeg"), bp::arg("gammadeg")), - doc_PeriodicStructureAdapter_setLatPar) - .def("toCartesian", &PeriodicStructureAdapter::toCartesian, - bp::arg("atom"), doc_PeriodicStructureAdapter_toCartesian) - .def("toFractional", &PeriodicStructureAdapter::toFractional, - bp::arg("atom"), doc_PeriodicStructureAdapter_toFractional) - .def_pickle(StructureAdapterPickleSuite()) - ; - - // class CrystalStructureAdapter - class_, - noncopyable, CrystalStructureAdapterWrapPtr>( - "CrystalStructureAdapter", doc_CrystalStructureAdapter) - .def("__init__", StructureAdapter_constructor(), - doc_StructureAdapter___init__fromstring) - .def(self == self) - .def(self != self) - .def("clone", - &CrystalStructureAdapter::clone, - &CrystalStructureAdapterWrap::default_clone, - doc_CrystalStructureAdapter_clone) - .def("_customPQConfig", - &CrystalStructureAdapter::customPQConfig, - &CrystalStructureAdapterWrap::default_customPQConfig, - python::arg("pqobj"), - doc_StructureAdapter__customPQConfig) - .def("diff", - &CrystalStructureAdapter::diff, - &CrystalStructureAdapterWrap::default_diff, - python::arg("other"), - doc_StructureAdapter_diff) - .add_property("symmetryprecision", - crystaladapter_getsymmetryprecision, - &CrystalStructureAdapter::setSymmetryPrecision, - doc_CrystalStructureAdapter_symmetryprecision) - .def("countSymOps", &CrystalStructureAdapter::countSymOps, - doc_CrystalStructureAdapter_countSymOps) - .def("clearSymOps", &CrystalStructureAdapter::clearSymOps, - doc_CrystalStructureAdapter_clearSymOps) - .def("addSymOp", crystaladapter_addsymop, - (bp::arg("R"), bp::arg("t")), - doc_CrystalStructureAdapter_addSymOp) - .def("getSymOp", crystaladapter_getsymop, bp::arg("index"), - doc_CrystalStructureAdapter_getSymOp) - .def("getEquivalentAtoms", - crystaladapter_getequivalentatoms, bp::arg("index"), - doc_CrystalStructureAdapter_getEquivalentAtoms) - .def("expandLatticeAtom", - expandLatticeAtom_aslist, - bp::arg("atom"), - doc_CrystalStructureAdapter_expandLatticeAtom) - .def("updateSymmetryPositions", - &CrystalStructureAdapter::updateSymmetryPositions, - doc_CrystalStructureAdapter_updateSymmetryPositions) - .def_pickle(StructureAdapterPickleSuite()) - ; - -} - -} // namespace srrealmodule - -using srrealmodule::nswrap_AtomicStructureAdapter::AtomicStructureAdapterWrap; -BOOST_CLASS_EXPORT(AtomicStructureAdapterWrap) - -using srrealmodule::nswrap_AtomicStructureAdapter::PeriodicStructureAdapterWrap; -BOOST_CLASS_EXPORT(PeriodicStructureAdapterWrap) - -using srrealmodule::nswrap_AtomicStructureAdapter::CrystalStructureAdapterWrap; -BOOST_CLASS_EXPORT(CrystalStructureAdapterWrap) - -// End of file diff --git a/src/extensions/wrap_Attributes.cpp b/src/extensions/wrap_Attributes.cpp deleted file mode 100644 index b574f48c..00000000 --- a/src/extensions/wrap_Attributes.cpp +++ /dev/null @@ -1,203 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the diffpy::Attributes class. -* -*****************************************************************************/ - -#include - -#include - -#include - -#include "srreal_converters.hpp" - -namespace srrealmodule { -namespace nswrap_Attributes { - -using std::string; -using namespace boost; -using namespace diffpy::attributes; - -// docstrings ---------------------------------------------------------------- - -const char* doc_Attributes = "\ -This class manages named C++ double attributes owned by an instance.\n\ -The derived objects own double attributes that can be looked up from C++\n\ -by name, without having to know a full C++ interface of their classes.\n\ -"; - -const char* doc_Attributes__getDoubleAttr = "\ -Return value of a named C++ double attribute owned by this object.\n\ -\n\ -name -- string name of a double attribute\n\ -\n\ -Return double.\n\ -Raise AttributeError for invalid name.\n\ -"; - -const char* doc_Attributes__setDoubleAttr = "\ -Set named C++ double attribute to the specified value.\n\ -\n\ -name -- string name of a double attribute\n\ -value -- new value of the attribute\n\ -\n\ -No return value.\n\ -Raise AttributeError for invalid name or read-only attribute.\n\ -"; - -const char* doc_Attributes__hasDoubleAttr = "\ -Check if named C++ double attribute exists.\n\ -\n\ -name -- string name of a double attribute\n\ -\n\ -Return bool.\n\ -"; - -const char* doc_Attributes__namesOfDoubleAttributes = "\ -Return set of C++ double attributes owned by this object.\n\ -"; - -const char* doc_Attributes__namesOfWritableDoubleAttributes = "\ -Return set of writable C++ double attributes related to this object.\n\ -"; - -const char* doc_Attributes__registerDoubleAttribute = "\ -Register a C++ double attribute that is defined in Python.\n\ -This must be called from the __init__ method of a Python class\n\ -that derives from the Attributes.\n\ -\n\ -name -- string name of a double attribute, must be a unique\n\ - attribute name for this instance\n\ -getter -- optional function that returns the attribute value\n\ -setter -- optional function that sets the attribute value.\n\ - The attribute is read-only when None.\n\ -\n\ -When both getter and setter are None, register standard Python\n\ -attribute access as a C++ double attribute.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -DECLARE_PYSET_METHOD_WRAPPER(namesOfDoubleAttributes, - namesOfDoubleAttributes_asset) -DECLARE_PYSET_METHOD_WRAPPER(namesOfWritableDoubleAttributes, - namesOfWritableDoubleAttributes_asset) - -// Helper class to handle double attributes defined from Python - -class PythonDoubleAttribute : public BaseDoubleAttribute -{ - public: - - // constructor - PythonDoubleAttribute(python::object owner, - python::object getter, python::object setter) - { - // PythonDoubleAttribute needs to know its Python owner, but it - // has to use a borrowed reference otherwise the owner would be - // never freed. We store a pointer to the raw object and create - // a borrowed boost python wrapper as necessary. - mowner = owner.ptr(); - mgetter = getter; - msetter = setter; - } - - - double getValue(const Attributes* obj) const - { - // verify that mowner is indeed the obj wrapper - python::object owner(python::borrowed(mowner)); - assert(obj == python::extract(owner)); - python::object pyrv = mgetter(owner); - double rv = python::extract(pyrv); - return rv; - } - - - void setValue(Attributes* obj, double value) - { - if (this->isreadonly()) throwDoubleAttributeReadOnly(); - // verify that mowner is indeed the obj wrapper - python::object owner(python::borrowed(mowner)); - assert(obj == python::extract(owner)); - msetter(owner, value); - } - - - bool isreadonly() const - { - return (msetter.is_none()); - } - - private: - - // data - PyObject* mowner; - python::object mgetter; - python::object msetter; - -}; // class PythonDoubleAttribute - - -void registerPythonDoubleAttribute(python::object owner, - const string& name, python::object g, python::object s) -{ - // when neither getter no setter are specified, - // make it use normal python attribute access - if (g.is_none() && s.is_none()) - { - python::object mod = python::import("diffpy.srreal.attributes"); - g = mod.attr("_pyattrgetter")(name); - s = mod.attr("_pyattrsetter")(name); - } - Attributes* cowner = python::extract(owner); - BaseDoubleAttribute* pa = new PythonDoubleAttribute(owner, g, s); - registerBaseDoubleAttribute(cowner, name, pa); -} - -} // namespace nswrap_Attributes - -// Wrapper definition -------------------------------------------------------- - -void wrap_Attributes() -{ - using namespace nswrap_Attributes; - using namespace boost::python; - const python::object None; - // ready for class definition - class_("Attributes", doc_Attributes) - .def("_getDoubleAttr", &Attributes::getDoubleAttr, - doc_Attributes__getDoubleAttr) - .def("_setDoubleAttr", &Attributes::setDoubleAttr, - doc_Attributes__setDoubleAttr) - .def("_hasDoubleAttr", &Attributes::hasDoubleAttr, - doc_Attributes__hasDoubleAttr) - .def("_namesOfDoubleAttributes", - namesOfDoubleAttributes_asset, - doc_Attributes__namesOfDoubleAttributes) - .def("_namesOfWritableDoubleAttributes", - namesOfWritableDoubleAttributes_asset, - doc_Attributes__namesOfWritableDoubleAttributes) - .def("_registerDoubleAttribute", - registerPythonDoubleAttribute, - (python::arg("getter")=None, python::arg("setter")=None), - doc_Attributes__registerDoubleAttribute) - ; -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_BVParametersTable.cpp b/src/extensions/wrap_BVParametersTable.cpp deleted file mode 100644 index 9022c55e..00000000 --- a/src/extensions/wrap_BVParametersTable.cpp +++ /dev/null @@ -1,338 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2011 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the BVParametersTable and BVParam classes. -* -*****************************************************************************/ - -#include -#include -#include -#include - -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" - -#include -#include - -#define BVPARMCIF "bvparm2011.cif" - -namespace srrealmodule { -namespace nswrap_BVParametersTable { - -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_BVParam = "\ -Storage of bond valence parameters for a given cation-anion pair.\n\ -"; - -const char* doc_BVParam___init__ = "\ -Initialize new instance of the BVParam class.\n\ -\n\ -atom0 -- symbol of the cation atom, no charge specification\n\ -valence0 -- integer cation valence, must be positive\n\ -atom1 -- symbol of the anion atom, no charge specification\n\ -valence1 -- integer anion valence, must be negative\n\ -Ro -- valence parameter Ro\n\ -B -- valence parameter B\n\ -ref_id -- optional reference code in " BVPARMCIF "\n\ -"; - -const char* doc_BVParam___repr__ = "\ -String representation of the BVParam object\n\ -"; - -const char* doc_BVParam_bondvalence = "\ -Bond valence of the specified distance in Angstroms.\n\ -"; - -const char* doc_BVParam_bondvalenceToDistance = "\ -Distance in Angstroms corresponding to specified bond valence.\n\ -"; - -const char* doc_BVParam_setFromCifLine = "\ -Update bond valence data from a string formatted as in " BVPARMCIF ".\n\ -"; - -const char* doc_BVParam_atom0 = "\ -Bare symbol of the cation atom without charge specification.\n\ -"; - -const char* doc_BVParam_valence0 = "\ -Positive integer valence of the cation.\n\ -"; - -const char* doc_BVParam_atom1 = "\ -Bare symbol of the anion atom without charge specification.\n\ -"; - -const char* doc_BVParam_valence1 = "\ -Negative integer valence of the anion.\n\ -"; - -const char* doc_BVParam_Ro = "\ -Bond valence parameter Ro in Angstroms.\n\ -"; - -const char* doc_BVParam_B = "\ -Bond valence parameter B in Angstroms.\n\ -"; - -const char* doc_BVParam_ref_id = "\ -code of the reference paper in " BVPARMCIF ".\n\ -"; - -const char* doc_BVParametersTable = "\ -Lookup table for bond valence parameters of a cation-anion pairs.\n\ -"; - -const char* doc_BVParametersTable_none = "\ -Singleton instance of void bond valence parameters.\n\ -Also returned by 'lookup' when valence data do not exist.\n\ -"; - -const char* doc_BVParametersTable_getAtomValence = "\ -Return signed valence for the specified atom or ion symbol.\n\ -\n\ -Return valence previously defined by setAtomValence or\n\ -interpret the charge suffix, for example, use -2 for \"S2-\".\n\ -"; - -const char* doc_BVParametersTable_setAtomValence = "\ -Define custom valence for the specified atom or ion symbol.\n\ -\n\ -smbl -- string symbol of atom or ion, for example \"F\".\n\ -value -- signed valence to be used for the symbol, e.g., -1.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BVParametersTable_resetAtomValences = "\ -Unset any custom valences defined by setAtomValence.\n\ -\n\ -Valences are thereafter obtained from charge suffixes only.\n\ -"; - -const char* doc_BVParametersTable_lookup1 = "\ -Lookup bond valence parameters by a BVParam instance.\n\ -\n\ -bvparam -- BVParam object. The only attributes considered for\n\ - lookup are atom0, valence0, atom1, valence1.\n\ -\n\ -Return a BVParam object with the looked up data.\n\ -Return BVParametersTable.none() if bond valence data do not exist.\n\ -"; - -const char* doc_BVParametersTable_lookup2 = "\ -Lookup bond valence parameters by cation-anion pair.\n\ -The cation-anion order may be flipped.\n\ -\n\ -smbl0 -- symbol of the first ion with charge, e.g., \"Na+\"\n\ -smbl1 -- symbol of the second ion with charge, e.g., \"O2-\"\n\ -\n\ -Return a BVParam object with the looked up data.\n\ -Return BVParametersTable.none() if bond valence data do not exist.\n\ -"; - -const char* doc_BVParametersTable_lookup4 = "\ -Lookup bond valence parameters by cation-anion pair.\n\ -The cation-anion order may be flipped.\n\ -\n\ -atom0 -- bare symbol of the cation atom\n\ -valence0 -- positive integer cation valence\n\ -atom1 -- bare symbol of the anion atom\n\ -valence1 -- negative integer anion valence\n\ -\n\ -Return a BVParam object with the looked up data.\n\ -Return BVParametersTable.none() if bond valence data do not exist.\n\ -"; - -const char* doc_BVParametersTable_setCustom1 = "\ -Insert custom bond valence data to the table.\n\ -\n\ -bvparam -- BVParam object with the custom bond valence data.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BVParametersTable_setCustom6 = "\ -Insert custom bond valence data to the table.\n\ -\n\ -atom0 -- bare symbol of the cation atom\n\ -valence0 -- positive integer cation valence\n\ -atom1 -- bare symbol of the anion atom\n\ -valence1 -- negative integer anion valence\n\ -Ro -- valence parameter Ro in Angstroms\n\ -B -- valence parameter B in Angstroms\n\ -ref_id -- optional reference code in " BVPARMCIF "\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BVParametersTable_resetCustom1 = "\ -Remove custom bond valence data for the specified cation-anion pair.\n\ -\n\ -bvparam -- BVParam object. The only attributes considered for\n\ - custom entry lookup are atom0, valence0, atom1, valence1.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BVParametersTable_resetCustom4 = "\ -Remove custom bond valence data for the specified cation-anion pair.\n\ -The cation-anion order may be flipped.\n\ -\n\ -atom0 -- bare symbol of the cation atom\n\ -valence0 -- positive integer cation valence\n\ -atom1 -- bare symbol of the anion atom\n\ -valence1 -- negative integer anion valence\n\ -\n\ -No return value.\n\ -"; -const char* doc_BVParametersTable_resetAll = "\ -Remove all custom bond valence data defined in this table.\n\ -"; - -const char* doc_BVParametersTable_getAll = "\ -Return all bond valence parameter values in this table.\n\ -\n\ -Return a set of BVParam objects.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(setcustom6, setCustom, 6, 7) -DECLARE_PYSET_METHOD_WRAPPER(getAll, getAll_asset) - -object repr_BVParam(const BVParam& bp) -{ - if (bp == BVParametersTable::none()) return object("BVParam()"); - object rv = ("BVParam(%r, %i, %r, %i, Ro=%s, B=%s, ref_id=%r)" % - make_tuple(bp.matom0, bp.mvalence0, bp.matom1, bp.mvalence1, - bp.mRo, bp.mB, bp.mref_id)); - return rv; -} - - -object singleton_none() -{ - const char* nameofnone = "__BVParam_singleton_none"; - object mod = import("diffpy.srreal.srreal_ext"); - static bool noneassigned = false; - if (!noneassigned) - { - mod.attr(nameofnone) = object(BVParametersTable::none()); - noneassigned = true; - } - return mod.attr(nameofnone); -} - -} // namespace nswrap_BVParametersTable - -// Wrapper definition -------------------------------------------------------- - -void wrap_BVParametersTable() -{ - using namespace nswrap_BVParametersTable; - using std::string; - - class_("BVParam", doc_BVParam) - .def(init(doc_BVParam___init__, - (arg("atom0"), arg("valence0"), - arg("atom1"), arg("valence1"), arg("Ro")=0.0, arg("B")=0.0, - arg("ref_id")=""))) - .def("__repr__", repr_BVParam, doc_BVParam___repr__) - .def(self == self) - .def(self != self) - .def("bondvalence", &BVParam::bondvalence, - arg("distance"), doc_BVParam_bondvalence) - .def("bondvalenceToDistance", &BVParam::bondvalenceToDistance, - arg("valence"), doc_BVParam_bondvalenceToDistance) - .def("setFromCifLine", &BVParam::setFromCifLine, - doc_BVParam_setFromCifLine) - .def_readonly("atom0", &BVParam::matom0, doc_BVParam_atom0) - .def_readonly("valence0", &BVParam::mvalence0, doc_BVParam_valence0) - .def_readonly("atom1", &BVParam::matom1, doc_BVParam_atom1) - .def_readonly("valence1", &BVParam::mvalence1, doc_BVParam_valence1) - .def_readwrite("Ro", &BVParam::mRo, doc_BVParam_Ro) - .def_readwrite("B", &BVParam::mB, doc_BVParam_B) - .def_readwrite("ref_id", &BVParam::mref_id, doc_BVParam_ref_id) - .def_pickle(SerializationPickleSuite()) - ; - - typedef const BVParam&(BVParametersTable::*bptb_bvparam_1)( - const BVParam&) const; - typedef const BVParam&(BVParametersTable::*bptb_bvparam_2)( - const string&, const string&) const; - typedef const BVParam&(BVParametersTable::*bptb_bvparam_4)( - const string&, int, const string&, int) const; - typedef void(BVParametersTable::*bptb_void_1)( - const BVParam&); - typedef void(BVParametersTable::*bptb_void_4)( - const string&, int, const string&, int); - - class_("BVParametersTable", doc_BVParametersTable) - .def("none", singleton_none, doc_BVParametersTable_none) - .staticmethod("none") - .def("getAtomValence", &BVParametersTable::getAtomValence, - arg("smbl"), - doc_BVParametersTable_getAtomValence) - .def("setAtomValence", &BVParametersTable::setAtomValence, - (arg("smbl"), arg("value")), - doc_BVParametersTable_setAtomValence) - .def("resetAtomValences", &BVParametersTable::resetAtomValences, - doc_BVParametersTable_resetAtomValences) - .def("lookup", bptb_bvparam_1(&BVParametersTable::lookup), - arg("bvparam"), doc_BVParametersTable_lookup1, - return_value_policy()) - .def("lookup", bptb_bvparam_2(&BVParametersTable::lookup), - (arg("smbl0"), arg("smbl1")), - doc_BVParametersTable_lookup2, - return_value_policy()) - .def("lookup", bptb_bvparam_4(&BVParametersTable::lookup), - (arg("atom0"), arg("valence0"), arg("atom1"), arg("valence1")), - doc_BVParametersTable_lookup4, - return_value_policy()) - .def("setCustom", bptb_void_1(&BVParametersTable::setCustom), - arg("bvparm"), doc_BVParametersTable_setCustom1) - .def("setCustom", (void(BVParametersTable::*)(const string&, int, - const string&, int, double, double, string)) NULL, - setcustom6((arg("atom0"), arg("valence0"), arg("atom1"), arg("valence1"), - arg("Ro"), arg("B"), arg("ref_id")=""), - doc_BVParametersTable_setCustom6)) - .def("resetCustom", bptb_void_1(&BVParametersTable::resetCustom), - doc_BVParametersTable_resetCustom1) - .def("resetCustom", bptb_void_4(&BVParametersTable::resetCustom), - (arg("atom0"), arg("valence0"), arg("atom1"), arg("valence1")), - doc_BVParametersTable_resetCustom4) - .def("resetAll", &BVParametersTable::resetAll, - doc_BVParametersTable_resetAll) - .def("getAll", getAll_asset, - doc_BVParametersTable_getAll) - .def_pickle(SerializationPickleSuite()) - ; - - register_ptr_to_python(); -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_BVSCalculator.cpp b/src/extensions/wrap_BVSCalculator.cpp deleted file mode 100644 index 1096b0cb..00000000 --- a/src/extensions/wrap_BVSCalculator.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the BVSCalculator class. -* -*****************************************************************************/ - -#include - -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" - -namespace srrealmodule { -namespace nswrap_BVSCalculator { - -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_BVSCalculator = "\ -Calculator of bond valence sums in the specified structure.\n\ -"; - -const char* doc_BVSCalculator_value = "\ -Return bond valence sums per each atom site in the structure.\n\ -"; - -const char* doc_BVSCalculator_valences = "\ -Return valences expected at each site of the evaluated structure.\n\ -"; - -const char* doc_BVSCalculator_bvdiff = "\ -Difference between expected and calculated valence magnitudes at each site.\n\ -Positive for underbonding, negative for overbonding.\n\ -"; - -const char* doc_BVSCalculator_bvmsdiff = "\ -Mean square difference between expected and calculated valences.\n\ -Adjusted for multiplicity and occupancy of atom sites in the structure.\n\ -"; - -const char* doc_BVSCalculator_bvrmsdiff = "\ -Root mean square difference between expected and calculated valences.\n\ -Adjusted for multiplicity and occupancy of atom sites in the structure.\n\ -"; - -const char* doc_BVSCalculator_bvparamtable = "\ -BVParametersTable object used for bond valence parameters lookup.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -DECLARE_PYARRAY_METHOD_WRAPPER(valences, valences_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(bvdiff, bvdiff_asarray) - -BVParametersTablePtr getbvparamtable(BVSCalculator& obj) -{ - return obj.getBVParamTable(); -} - -void setbvparamtable(BVSCalculator& obj, BVParametersTablePtr bptb) -{ - obj.setBVParamTable(bptb); -} - -} // namespace nswrap_BVSCalculator - -// Wrapper definition -------------------------------------------------------- - -void wrap_BVSCalculator() -{ - using namespace nswrap_BVSCalculator; - - class_ >("BVSCalculator", - doc_BVSCalculator) - .add_property("value", value_asarray, - doc_BVSCalculator_value) - .add_property("valences", valences_asarray, - doc_BVSCalculator_valences) - .add_property("bvdiff", bvdiff_asarray, - doc_BVSCalculator_bvdiff) - .add_property("bvmsdiff", &BVSCalculator::bvmsdiff, - doc_BVSCalculator_bvmsdiff) - .add_property("bvrmsdiff", &BVSCalculator::bvrmsdiff, - doc_BVSCalculator_bvrmsdiff) - .add_property("bvparamtable", getbvparamtable, setbvparamtable, - doc_BVSCalculator_bvparamtable) - .def_pickle(PairQuantityPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_BaseBondGenerator.cpp b/src/extensions/wrap_BaseBondGenerator.cpp deleted file mode 100644 index 87c2295c..00000000 --- a/src/extensions/wrap_BaseBondGenerator.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the BaseBondGenerator class. So far the wrapper is intended -* only for accessing the C++ created BaseBondGenerator instances and there -* is no support for method overrides from Python. -* -*****************************************************************************/ - -#include -#include -#include -#include - -#include - -#include -#include - -#include "srreal_converters.hpp" - -namespace srrealmodule { -namespace nswrap_BaseBondGenerator { - -// docstrings ---------------------------------------------------------------- - -const char* doc_BaseBondGenerator = "\ -This class generates atom pairs in the structure within specified distance\n\ -bounds and returns the associated atom-pair data. The generator walks over\n\ -all neighbors of the anchor site accounting for symmetry and periodicity of\n\ -the structure object.\n\ -"; - -const char* doc_BaseBondGenerator_rewind = "\ -Reset generator to the first atom pair containing the anchor atom.\n\ -"; - -const char* doc_BaseBondGenerator_finished = "\ -Return True if there are no more atom pairs containing the anchor atom.\n\ -"; - -const char* doc_BaseBondGenerator_next = "\ -Advance to the next bond of the anchor atom.\n\ -"; - -const char* doc_BaseBondGenerator_selectAnchorSite = "\ -Select the anchor site of the bond generator.\n\ -\n\ -anchor -- integer index of the anchor site\n\ -\n\ -No return value. Must be followed by a rewind call to get a valid state.\n\ -"; - -const char* doc_BaseBondGenerator_selectSiteRange = "\ -Select a range of neighbor sites for the anchor atom bonds.\n\ -\n\ -first -- integer index of the first neighbor site\n\ -last -- index of the last neighbor site, not included\n\ -\n\ -No return value. Must be followed by a rewind call to get a valid state.\n\ -"; - -const char* doc_BaseBondGenerator_setRmin = "\ -Select minimum distance for the generated bonds.\n\ -\n\ -rmin -- the minimum distance\n\ -\n\ -No return value. Must be followed by a rewind call to get a valid state.\n\ -"; - -const char* doc_BaseBondGenerator_setRmax = "\ -Select the maximum distance limit of the generated bonds.\n\ -\n\ -rmax -- the maximum distance\n\ -\n\ -No return value. Must be followed by a rewind call to get a valid state.\n\ -"; - -const char* doc_BaseBondGenerator_getRmin = "\ -Return the minimum length of the generated bonds.\n\ -"; - -const char* doc_BaseBondGenerator_getRmax = "\ -Return the maximum length of the generated bonds.\n\ -"; - -const char* doc_BaseBondGenerator_site0 = "\ -Anchor site index of the current bond.\n\ -"; - -const char* doc_BaseBondGenerator_site1 = "\ -Neighbor site index of the current bond.\n\ -"; - -const char* doc_BaseBondGenerator_multiplicity = "\ -Symmetry multiplicity of the anchor site.\n\ -"; - -const char* doc_BaseBondGenerator_r0 = "\ -Cartesian coordinates of the anchor site.\n\ -"; - -const char* doc_BaseBondGenerator_r1 = "\ -Cartesian coordinates of the current neighbor site, these can\n\ -be adjusted for symmetry operations and periodic translations.\n\ -"; - -const char* doc_BaseBondGenerator_distance = "\ -Current distance between anchor and neighbor site.\n\ -"; - -const char* doc_BaseBondGenerator_r01 = "\ -Cartesian direction from anchor to neighbor site.\n\ -"; - -const char* doc_BaseBondGenerator_Ucartesian0 = "\ -Cartesian anisotropic displacement parameters matrix at the anchor site.\n\ -Returns a 3x3 numpy array.\n\ -"; - -const char* doc_BaseBondGenerator_Ucartesian1 = "\ -Cartesian anisotropic displacement parameters matrix at the neighbor site.\n\ -This can be adjusted for symmetry rotations at the neighbor site.\n\ -Returns a 3x3 numpy array.\n\ -"; - -const char* doc_BaseBondGenerator_msd = "\ -Mean square displacement along the direction from anchor to neighbor site.\n\ -This is proportional to the sum of Ucartesian0 and Ucartesian1 matrices.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -DECLARE_PYARRAY_METHOD_WRAPPER(r0, r0_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(r1, r1_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(r01, r01_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(Ucartesian0, Ucartesian0_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(Ucartesian1, Ucartesian1_asarray) - -} // namespace nswrap_BaseBondGenerator - -// Wrapper definition -------------------------------------------------------- - -void wrap_BaseBondGenerator() -{ - using namespace boost::python; - using namespace diffpy::srreal; - using namespace nswrap_BaseBondGenerator; - - class_("BaseBondGenerator", doc_BaseBondGenerator, - init()) - .def("rewind", &BaseBondGenerator::rewind, - doc_BaseBondGenerator_rewind) - .def("finished", &BaseBondGenerator::finished, - doc_BaseBondGenerator_finished) - .def("next", &BaseBondGenerator::next, - doc_BaseBondGenerator_next) - .def("selectAnchorSite", &BaseBondGenerator::selectAnchorSite, - arg("anchor"), doc_BaseBondGenerator_selectAnchorSite) - .def("selectSiteRange", &BaseBondGenerator::selectSiteRange, - (arg("first"), arg("last")), - doc_BaseBondGenerator_selectSiteRange) - .def("setRmin", &BaseBondGenerator::setRmin, - arg("rmin"), doc_BaseBondGenerator_setRmin) - .def("setRmax", &BaseBondGenerator::setRmax, - arg("rmax"), doc_BaseBondGenerator_setRmax) - .def("getRmin", &BaseBondGenerator::getRmin, - return_value_policy(), - doc_BaseBondGenerator_getRmin) - .def("getRmax", &BaseBondGenerator::getRmax, - return_value_policy(), - doc_BaseBondGenerator_getRmax) - .def("site0", &BaseBondGenerator::site0, - doc_BaseBondGenerator_site0) - .def("site1", &BaseBondGenerator::site1, - doc_BaseBondGenerator_site1) - .def("multiplicity", &BaseBondGenerator::multiplicity, - doc_BaseBondGenerator_multiplicity) - .def("r0", r0_asarray, - doc_BaseBondGenerator_r0) - .def("r1", r1_asarray, - doc_BaseBondGenerator_r1) - .def("distance", &BaseBondGenerator::distance, - return_value_policy(), - doc_BaseBondGenerator_distance) - .def("r01", r01_asarray, - doc_BaseBondGenerator_r01) - .def("Ucartesian0", Ucartesian0_asarray, - doc_BaseBondGenerator_Ucartesian0) - .def("Ucartesian1", Ucartesian1_asarray, - doc_BaseBondGenerator_Ucartesian1) - .def("msd", &BaseBondGenerator::msd, - doc_BaseBondGenerator_msd) - ; - - register_ptr_to_python(); -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_BondCalculator.cpp b/src/extensions/wrap_BondCalculator.cpp deleted file mode 100644 index 7b317188..00000000 --- a/src/extensions/wrap_BondCalculator.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2011 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the BondCalculator class. -* -*****************************************************************************/ - -#include - -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" - -namespace srrealmodule { -namespace nswrap_BondCalculator { - -namespace bp = boost::python; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_BondCalculator = "\ -Calculator of bond distances in a specified structure.\n\ -"; - -const char* doc_BondCalculator_distances = "\ -Array of sorted bond distances in the evaluated structure.\n\ -"; - -const char* doc_BondCalculator_directions = "\ -List of bond directions in the evaluated structure.\n\ -"; - -const char* doc_BondCalculator_sites0 = "\ -List of zero-based indices of the first site in the pair.\n\ -"; - -const char* doc_BondCalculator_sites1 = "\ -List of zero-based indices of the second site in the pair.\n\ -"; - -const char* doc_BondCalculator_types0 = "\ -List of atom symbols for the first site in all pairs.\n\ -"; - -const char* doc_BondCalculator_types1 = "\ -List of atom symbols for the second site in all pairs.\n\ -"; - -const char* doc_BondCalculator_filterCone = "\ -Setup an additive bond filter in a specified direction cone.\n\ -Second and further calls create more filters that permit more bonds.\n\ -Use filterOff to create exclusive filter in a new direction.\n\ -\n\ -cartesiandir -- cone axis in Cartesian coordinates,\n\ - list, tuple or array.\n\ -degrees -- cone angle in degrees\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BondCalculator_filterOff = "\ -Turn off bond filtering and destroy all cone filters.\n\ -Permit all bonds in further calculations. Also used to create\n\ -exclusive cone filter in a new direction.\n\ -"; - -// wrappers ------------------------------------------------------------------ - - -void filter_cone(BondCalculator& obj, - object cartesiandir, double degrees) -{ - if (len(cartesiandir) != 3) - { - const char* emsg = "cartesiandir must be a 3-element array."; - PyErr_SetString(PyExc_ValueError, emsg); - bp::throw_error_already_set(); - } - R3::Vector cdir; - cdir[0] = extract(cartesiandir[0]); - cdir[1] = extract(cartesiandir[1]); - cdir[2] = extract(cartesiandir[2]); - obj.filterCone(cdir, degrees); -} - -} // namespace nswrap_BondCalculator - -// Wrapper definition -------------------------------------------------------- - -void wrap_BondCalculator() -{ - using namespace nswrap_BondCalculator; - - class_ - >("BondCalculator", doc_BondCalculator) - .add_property("distances", - distances_asarray, - doc_BondCalculator_distances) - .add_property("directions", - directions_asarray, - doc_BondCalculator_directions) - .add_property("sites0", - sites0_asarray, - doc_BondCalculator_sites0) - .add_property("sites1", - sites1_asarray, - doc_BondCalculator_sites1) - .add_property("types0", - types0_aschararray, - doc_BondCalculator_types0) - .add_property("types1", - types1_aschararray, - doc_BondCalculator_types1) - .def("filterCone", filter_cone, - (bp::arg("cartesiandir"), bp::arg("degrees")), - doc_BondCalculator_filterCone) - .def("filterOff", &BondCalculator::filterOff, - doc_BondCalculator_filterOff) - .def_pickle(PairQuantityPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_EventTicker.cpp b/src/extensions/wrap_EventTicker.cpp deleted file mode 100644 index b26bedfb..00000000 --- a/src/extensions/wrap_EventTicker.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2013 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the EventTicker class. -* -*****************************************************************************/ - -#include - -#include - -#include "srreal_pickling.hpp" - -namespace srrealmodule { -namespace nswrap_EventTicker { - -using namespace boost; -using diffpy::eventticker::EventTicker; - -// docstrings ---------------------------------------------------------------- - -const char* doc_EventTicker = "\ -Class for storing modification 'times' of dependent objects\n\ -The default EventTicker object is initialized to a zero time.\n\ -"; - -const char* doc_EventTicker_cp = "\ -Constructor EventTicker at the same modification time as the source.\n\ -"; - -const char* doc_EventTicker___repr__ = "\ -String representation of the EventTicker object\n\ -"; - -const char* doc_EventTicker_click = "\ -Increment ticker value to the latest unique time.\n\ -"; - -const char* doc_EventTicker_updateFrom = "\ -Update ticker time to the value of other, newer ticker.\n\ -Keep original value if the other ticker is older.\n\ -\n\ -other -- instance of another EventTicker object\n\ -\n\ -No return value.\n\ -"; - -const char* doc_EventTicker__value = "\ -Return the internal time for this ticker. This is a tuple of 2 integers,\n\ -where the latter is the total number of click calls at the last update\n\ -and the first one is zero unless there was an integer overflow.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -// getter for the _value property - -python::tuple gettickervalue(const EventTicker& tc) -{ - EventTicker::value_type v = tc.value(); - return python::make_tuple(v.first, v.second); -} - -// representation of EventTicker objects - -python::object repr_EventTicker(const EventTicker& tc) -{ - python::object rv = ("EventTicker(%i, %i)" % gettickervalue(tc)); - return rv; -} - -} // namespace nswrap_EventTicker - -// Wrapper definition -------------------------------------------------------- - -void wrap_EventTicker() -{ - using namespace nswrap_EventTicker; - using namespace boost::python; - - class_("EventTicker", doc_EventTicker) - .def(init(doc_EventTicker_cp)) - .def("__repr__", repr_EventTicker, doc_EventTicker___repr__) - .def(self < self) - .def(self <= self) - .def(self > self) - .def(self >= self) - .def(self == self) - .def(self != self) - .def("click", &EventTicker::click, - doc_EventTicker_click) - .def("updateFrom", &EventTicker::updateFrom, - python::arg("other"), - doc_EventTicker_updateFrom) - .add_property("_value", gettickervalue, - doc_EventTicker__value) - .def_pickle(SerializationPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_ObjCrystAdapters.cpp b/src/extensions/wrap_ObjCrystAdapters.cpp deleted file mode 100644 index 02553850..00000000 --- a/src/extensions/wrap_ObjCrystAdapters.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2014 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Support Crystal and Molecule objects from pyobjcryst if libdiffpy -* has been built with ObjCryst support. -* -*****************************************************************************/ - -#include - -#include - -#include -#include - -#ifdef DIFFPY_HAS_OBJCRYST -#include -#endif - -namespace srrealmodule { -namespace nswrap_ObjCrystAdapters { - -using namespace boost; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -// class Atom - -const char* doc_convertObjCrystMolecule = "\ -Convert pyobjcryst Molecule object to AtomicStructureAdapter.\n\ -Instance data:\n\ -\n\ -molecule -- instance of pyobjcryst Molecule object\n\ -\n\ -Return AtomicStructureAdapter.\n\ -Raise TypeError if ObjCryst was not available at compile time.\n\ -"; - -const char* doc_convertObjCrystCrystal = "\ -Convert pyobjcryst Crystal object to PeriodicStructureAdapter.\n\ -Instance data:\n\ -\n\ -molecule -- instance of pyobjcryst Crystal object\n\ -\n\ -Return PeriodicStructureAdapter.\n\ -Raise TypeError if ObjCryst was not available at compile time.\n\ -"; - -// ObjCryst supported -------------------------------------------------------- - -#ifdef DIFFPY_HAS_OBJCRYST - -using ObjCryst::Molecule; -using ObjCryst::Crystal; - -StructureAdapterPtr convertObjCrystMolecule(const Molecule& mol) -{ - return createStructureAdapter(mol); -} - -StructureAdapterPtr convertObjCrystCrystal(const Crystal& mol) -{ - return createStructureAdapter(mol); -} - -// ObjCryst not available ---------------------------------------------------- - -#else - -StructureAdapterPtr convertObjCrystMolecule(python::object mol) -{ - std::string emsg = "ObjCryst support not available."; - PyErr_SetString(PyExc_TypeError, emsg.c_str()); - boost::python::throw_error_already_set(); - abort(); -} - -StructureAdapterPtr convertObjCrystCrystal(python::object cryst) -{ - // raise the same exception as for the Molecule - return convertObjCrystMolecule(cryst); -} - -#endif // DIFFPY_HAS_OBJCRYST - -} // namespace nswrap_ObjCrystAdapters - -// Wrapper definitions ------------------------------------------------------- - -void wrap_ObjCrystAdapters() -{ - using namespace nswrap_ObjCrystAdapters; - using namespace boost::python; - - def("convertObjCrystMolecule", - convertObjCrystMolecule, doc_convertObjCrystMolecule); - def("convertObjCrystCrystal", - convertObjCrystCrystal, doc_convertObjCrystCrystal); - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_OverlapCalculator.cpp b/src/extensions/wrap_OverlapCalculator.cpp deleted file mode 100644 index 4fef2dff..00000000 --- a/src/extensions/wrap_OverlapCalculator.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2011 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the OverlapCalculator class. -* -*****************************************************************************/ - -#include - -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" - -namespace srrealmodule { -namespace nswrap_OverlapCalculator { - -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_OverlapCalculator = "\ -Calculate the overlap of atom radii and coordination numbers at each site.\n\ -"; - -const char* doc_OverlapCalculator_overlaps = "\ -Magnitudes of all non-zero atom radii overlaps in the structure.\n\ -"; - -const char* doc_OverlapCalculator_distances = "\ -Distances of all overlapping atom pairs in the structure.\n\ -"; - -const char* doc_OverlapCalculator_directions = "\ -Directions from the first to the second atom in the overlapping pairs.\n\ -Returns an Nx3 array.\n\ -"; - -const char* doc_OverlapCalculator_sites0 = "\ -Indices of all first sites of the overlapping pairs.\n\ -"; - -const char* doc_OverlapCalculator_sites1 = "\ -Indices of all second sites of the overlapping pairs.\n\ -"; - -const char* doc_OverlapCalculator_types0 = "\ -List of atom symbols of all first sites of the overlapping pairs.\n\ -"; - -const char* doc_OverlapCalculator_types1 = "\ -List of atom symbols of all second sites of the overlapping pairs.\n\ -"; - -const char* doc_OverlapCalculator_sitesquareoverlaps = "\ -Sum of squared overlaps per each site in the structure.\n\ -"; - -const char* doc_OverlapCalculator_totalsquareoverlap = "\ -Total sum of squared overlaps in the structure adjusted\n\ -for site multiplicities and occupancies.\n\ -"; - -const char* doc_OverlapCalculator_meansquareoverlap = "\ -Total square overlap per one atom in the structure.\n\ -"; - -const char* doc_OverlapCalculator_flipDiffTotal = "\ -Calculate change of the totalsquareoverlap after flipping the atom types\n\ -at the i and j sites.\n\ -\n\ -i -- zero-based index of the first site\n\ -j -- zero-based index of the second site\n\ -\n\ -Return float.\n\ -"; - -const char* doc_OverlapCalculator_flipDiffMean = "\ -Calculate change of the meansquareoverlap after flipping the atom types\n\ -at the i and j sites.\n\ -\n\ -i -- zero-based index of the first site\n\ -j -- zero-based index of the second site\n\ -\n\ -Return float.\n\ -"; - -const char* doc_OverlapCalculator_gradients = "\ -Gradients of the totalsquareoverlap per each site in the structure.\n\ -Returns an Nx3 array.\n\ -"; - -const char* doc_OverlapCalculator_getNeighborSites = "\ -Get indices of all sites that neighbor with the specified site,\n\ -either directly or as periodic or symmetry images. Atoms are\n\ -assumed neighbors if they have non-zero overlap.\n\ -\n\ -i -- zero-based index of the evaluated site\n\ -\n\ -Return a set of integer indices, this may include i.\n\ -"; - -const char* doc_OverlapCalculator_coordinations = "\ -Return coordination numbers per each site in the structure.\n\ -These may be non-integer if there are sites with partial occupancies.\n\ -"; - -const char* doc_OverlapCalculator_coordinationByTypes = "\ -Evaluate neighbor types and their occupancies at the specified site.\n\ -\n\ -i -- zero-based index of the evaluated site\n\ -\n\ -Return a dictionary where the keys are atom type strings and the values\n\ -their total occupancies.\n\ -"; - -const char* doc_OverlapCalculator_neighborhoods = "\ -Return all sets of connected site indices in the structure.\n\ -Sites are assumed in the same neighborhood if they have overlapping\n\ -neighbors or can be connected through neighbor links. There are no\n\ -overlapping pairs between sites from different neighborhoods.\n\ -\n\ -Return a list of site indices sets.\n\ -"; - -const char* doc_OverlapCalculator_atomradiitable = "\ -AtomRadiiTable object used for radius lookup.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -DECLARE_PYARRAY_METHOD_WRAPPER(overlaps, overlaps_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(siteSquareOverlaps, siteSquareOverlaps_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(gradients, gradients_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(coordinations, coordinations_asarray) -DECLARE_PYDICT_METHOD_WRAPPER1(coordinationByTypes, coordinationByTypes_asdict) -DECLARE_PYLISTSET_METHOD_WRAPPER(neighborhoods, neighborhoods_aslistset) - -AtomRadiiTablePtr getatomradiitable(OverlapCalculator& obj) -{ - return obj.getAtomRadiiTable(); -} - -DECLARE_BYTYPE_SETTER_WRAPPER(setAtomRadiiTable, setatomradiitable) - - -double flip_diff_total(const OverlapCalculator& obj, object i, object j) -{ - int i1 = extractint(i); - int j1 = extractint(j); - return obj.flipDiffTotal(i1, j1); -} - - -double flip_diff_mean(const OverlapCalculator& obj, object i, object j) -{ - int i1 = extractint(i); - int j1 = extractint(j); - return obj.flipDiffMean(i1, j1); -} - - -object get_neighbor_sites(const OverlapCalculator& obj, object i) -{ - int i1 = extractint(i); - object rv = convertToPythonSet(obj.getNeighborSites(i1)); - return rv; -} - - -class OverlapCalculatorPickleSuite : - public PairQuantityPickleSuite -{ - private: - - typedef PairQuantityPickleSuite Super; - - public: - - static boost::python::tuple getstate(boost::python::object obj) - { - namespace bp = boost::python; - bp::object tb = obj.attr("atomradiitable"); - bp::tuple rv = bp::make_tuple( - Super::getstate(obj), - resolve_state_object(tb) - ); - return rv; - } - - - static void setstate( - boost::python::object obj, boost::python::tuple state) - { - namespace bp = boost::python; - ensure_tuple_length(state, 2); - // restore the state using boost serialization - bp::tuple st0 = bp::extract(state[0]); - Super::setstate(obj, st0); - // atomradiitable is present only when restoring Python class - assign_state_object(obj.attr("atomradiitable"), state[1]); - } -}; - -} // namespace nswrap_OverlapCalculator - -// Wrapper definition -------------------------------------------------------- - -void wrap_OverlapCalculator() -{ - using namespace nswrap_OverlapCalculator; - - class_ >("OverlapCalculator", - doc_OverlapCalculator) - .add_property("overlaps", - overlaps_asarray, - doc_OverlapCalculator_overlaps) - .add_property("distances", - distances_asarray, - doc_OverlapCalculator_distances) - .add_property("directions", - directions_asarray, - doc_OverlapCalculator_directions) - .add_property("sites0", - sites0_asarray, - doc_OverlapCalculator_sites0) - .add_property("sites1", - sites1_asarray, - doc_OverlapCalculator_sites1) - .add_property("types0", - types0_aschararray, - doc_OverlapCalculator_types0) - .add_property("types1", - types1_aschararray, - doc_OverlapCalculator_types1) - .add_property("sitesquareoverlaps", - siteSquareOverlaps_asarray, - doc_OverlapCalculator_sitesquareoverlaps) - .add_property("totalsquareoverlap", - &OverlapCalculator::totalSquareOverlap, - doc_OverlapCalculator_totalsquareoverlap) - .add_property("meansquareoverlap", - &OverlapCalculator::meanSquareOverlap, - doc_OverlapCalculator_meansquareoverlap) - .def("flipDiffTotal", - flip_diff_total, - (arg("i"), arg("j")), - doc_OverlapCalculator_flipDiffTotal) - .def("flipDiffMean", - flip_diff_mean, - doc_OverlapCalculator_flipDiffMean) - .add_property("gradients", - gradients_asarray, - doc_OverlapCalculator_gradients) - .def("getNeighborSites", - get_neighbor_sites, - arg("i"), - doc_OverlapCalculator_getNeighborSites) - .add_property("coordinations", - coordinations_asarray, - doc_OverlapCalculator_coordinations) - .def("coordinationByTypes", - coordinationByTypes_asdict, - arg("i"), - doc_OverlapCalculator_coordinationByTypes) - .add_property("neighborhoods", - neighborhoods_aslistset, - doc_OverlapCalculator_neighborhoods) - .add_property("atomradiitable", - getatomradiitable, - setatomradiitable, - doc_OverlapCalculator_atomradiitable) - .def_pickle(OverlapCalculatorPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_PDFBaseline.cpp b/src/extensions/wrap_PDFBaseline.cpp deleted file mode 100644 index 90120045..00000000 --- a/src/extensions/wrap_PDFBaseline.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the PDFBaseline class. The business methods can be overloaded -* from Python to create custom PDF baseline functions. -* -*****************************************************************************/ - -#include -#include -#include -#include - -#include -#include -#include - -#include "srreal_numpy_symbol.hpp" -// numpy/arrayobject.h needs to be included after srreal_numpy_symbol.hpp, -// which defines PY_ARRAY_UNIQUE_SYMBOL. NO_IMPORT_ARRAY indicates -// import_array will be called in the extension module initializer. -#define NO_IMPORT_ARRAY -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_registry.hpp" - -namespace srrealmodule { -namespace nswrap_PDFBaseline { - -using namespace boost; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_PDFBaseline = "\ -Base class and registry for functions that calculate PDF baseline.\n\ -"; - -const char* doc_PDFBaseline___call__ = "\ -Calculate PDF baseline at the specified r.\n\ -\n\ -r -- atom distance in Angstroms where the baseline is calculated.\n\ - Float or NumPy array.\n\ -\n\ -Return float or NumPy array.\n\ -"; - -const char* doc_ZeroBaseline = "\ -Trivial baseline function that is always zero, no baseline.\n\ -"; - -const char* doc_LinearBaseline = "\ -PDF baseline function equal to (slope * r).\n\ -"; - -// wrappers ------------------------------------------------------------------ - -// Helper class allows overload of the PDFBaseline methods from Python. - -class PDFBaselineWrap : - public PDFBaseline, - public wrapper_srreal -{ - public: - - // HasClassRegistry methods - - PDFBaselinePtr create() const - { - object rv = this->get_pure_virtual_override("create")(); - return mconfigurator.fetch(rv); - } - - PDFBaselinePtr clone() const - { - return this->get_pure_virtual_override("clone")(); - } - - const std::string& type() const - { - python::object tp = this->get_pure_virtual_override("type")(); - mtype = python::extract(tp); - return mtype; - } - - // own methods - - double operator()(const double& x) const - { - return this->get_pure_virtual_override("__call__")(x); - } - - protected: - - // HasClassRegistry method - - void setupRegisteredObject(PDFBaselinePtr p) const - { - mconfigurator.setup(p); - } - - private: - - mutable std::string mtype; - wrapper_registry_configurator mconfigurator; - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - using boost::serialization::base_object; - ar & base_object(*this); - } - -}; // class PDFBaselineWrap - - -object callnparray(const PDFBaseline* obj, object& x) -{ - NumPyArray_DoublePtr xx = extractNumPyDoubleArray(x); - NumPyArray_DoublePtr yy = createNumPyDoubleArrayLike(xx.first); - double* src = xx.second; - double* last = xx.second + PyArray_Size(xx.first.ptr()); - double* dst = yy.second; - for (; src != last; ++src, ++dst) *dst = (*obj)(*src); - return yy.first; -} - -} // namespace nswrap_PDFBaseline - -// Wrapper definition -------------------------------------------------------- - -void wrap_PDFBaseline() -{ - using namespace nswrap_PDFBaseline; - using diffpy::Attributes; - namespace bp = boost::python; - - class_, noncopyable> - pdfbaseline("PDFBaseline", doc_PDFBaseline); - wrap_registry_methods(pdfbaseline) - .def("__call__", callnparray, - bp::arg("r_array")) - .def("__call__", &PDFBaseline::operator(), - bp::arg("r"), doc_PDFBaseline___call__) - .def_pickle(SerializationPickleSuite()) - ; - - register_ptr_to_python(); - - class_ >( - "ZeroBaseline", doc_ZeroBaseline) - .def_pickle(SerializationPickleSuite()); - class_ >( - "LinearBaseline", doc_ZeroBaseline) - .def_pickle(SerializationPickleSuite()); - -} - -} // namespace srrealmodule - -// Serialization ------------------------------------------------------------- - -BOOST_CLASS_EXPORT(srrealmodule::nswrap_PDFBaseline::PDFBaselineWrap) - -// End of file diff --git a/src/extensions/wrap_PDFCalculators.cpp b/src/extensions/wrap_PDFCalculators.cpp deleted file mode 100644 index df4cdd22..00000000 --- a/src/extensions/wrap_PDFCalculators.cpp +++ /dev/null @@ -1,490 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to DebyePDFCalculator and PDFCalculator classes. -* -*****************************************************************************/ - -#include -#include -#include - -#include -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" - -namespace srrealmodule { -namespace nswrap_PDFCalculators { - -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_PDFCommon_pdf = "\ -An array of PDF values in the form of G = 4*pi*r(rho - rho0) in A**-2.\n\ -"; - -const char* doc_PDFCommon_rdf = "\ -An array of the last RDF values in A**-1.\n\ -"; - -const char* doc_PDFCommon_rgrid = "\ -An array of r-values in Angstrom. This is a uniformly spaced array of\n\ -rstep multiples that are greater or equal to rmin and smaller than rmax.\n\ -"; - -const char* doc_PDFCommon_fq = "\ -An array of F values in 1/A that can be Fourier transformed to G(r).\n\ -"; - -const char* doc_PDFCommon_qgrid = "\ -An array of Q-values in 1/A. This is a uniformly spaced array of qstep\n\ -values that start at 0/A and are smaller than qmax.\n\ -"; - -const char* doc_PDFCommon_envelopes = "\ -A tuple of PDFEnvelope instances used for calculating scaling envelope.\n\ -This property can be assigned an iterable of PDFEnvelope objects.\n\ -"; - -const char* doc_PDFCommon_usedenvelopetypes = "\ -A tuple of string types of the used PDFEnvelope instances, read-only.\n\ -"; - -const char* doc_PDFCommon_addEnvelope = "\ -Add a PDFEnvelope object as another scaling function.\n\ -This replaces any existing PDFEnvelope of the same string type.\n\ -\n\ -envlp -- instance of PDFEnvelope that defines the scaling function or\n\ - a string type for a registered PDFEnvelope class.\n\ - Use PDFEnvelope.getRegisteredTypes for the available\n\ - string values.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_PDFCommon_popEnvelope = "\ -Remove PDFEnvelope object from an internal list of scaling functions.\n\ -\n\ -envlp -- instance of PDFEnvelope object or a string type of a registered\n\ - PDFEnvelope class to be removed. No action if envlp is not\n\ - present in the calculator. See the 'envelopes' attribute for a\n\ - tuple of active PDFEnvelope instances or the 'usedenvelopetypes'\n\ - attribute for the corresponding string types.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_PDFCommon_getEnvelope = "\ -Retrieve an active PDFEnvelope object by its string type.\n\ -\n\ -tp -- string type of a PDFEnvelope object that is present in\n\ - the calculator. See the 'usedenvelopetypes' attribute\n\ - for the present string types.\n\ -\n\ -Return a PDFEnvelope instance.\n\ -Raise ValueError it type tp is not present.\n\ -"; - -const char* doc_PDFCommon_clearEnvelopes = "\ -Remove all PDFEnvelope scaling functions from the calculator.\n\ -"; - -const char* doc_DebyePDFCalculator = "\ -Calculate PDF using the Debye scattering equation.\n\ -"; - -const char* doc_DebyePDFCalculator_setOptimumQstep = "\ -Use the optimum qstep value equal to the Nyquist step of pi/rmaxext,\n\ -where rmaxext is rmax extended for termination ripples and peak tails.\n\ -The qstep value depends on rmax when active. This is disabled after\n\ -explicit qstep assignment, which makes qstep independent of rmax.\n\ -"; - -const char* doc_DebyePDFCalculator_isOptimumQstep = "\ -Return True if qstep is set to an optimum, rmax-dependent value.\n\ -Return False if qstep was overridden by the user.\n\ -"; - -const char* doc_PDFCalculator = "\ -Calculate PDF using the real-space summation of PeakProfile functions.\n\ -"; - -const char* doc_PDFCalculator_peakprofile = "\ -Instance of PeakProfile that calculates the real-space profile for\n\ -a single atom-pair contribution. This can be assigned either a\n\ -PeakProfile-derived object or a string type of a registered PeakProfile\n\ -class. Use PeakProfile.getRegisteredTypes() for the allowed values.\n\ -"; - -const char* doc_PDFCalculator_baseline = "\ -Instance of PDFBaseline that calculates unscaled baseline at r.\n\ -The baseline property can be assigned either a PDFBaseline-derived\n\ -object or a string type of a registered PDFBaseline class.\n\ -Use PDFBaseline.getRegisteredTypes() for the set of allowed values.\n\ -"; - -const char* doc_fftftog = "\ -Perform sine-fast Fourier transform from F(Q) to G(r).\n\ -The length of the output array is padded to the next power of 2.\n\ -\n\ -f -- array of the F values on a regular Q-space grid.\n\ -qstep -- spacing in the Q-space grid, this is used for proper\n\ - scaling of the output array.\n\ -qmin -- optional starting point of the Q-space grid.\n\ -\n\ -Return a tuple of (g, rstep). These can be used with the complementary\n\ -fftgtof function to recover the original signal f.\n\ -"; - -const char* doc_fftgtof = "\ -Perform sine-fast Fourier transform from G(r) to F(Q).\n\ -The length of the output array is padded to the next power of 2.\n\ -\n\ -g -- array of the G values on a regular r-space grid.\n\ -rstep -- spacing in the r-space grid, this is used for proper\n\ - scaling of the output array.\n\ -rmin -- optional starting point of the r-space grid.\n\ -\n\ -Return a tuple of (f, qstep). These can be used with the complementary\n\ -fftftog function to recover the original signal g.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -DECLARE_PYARRAY_METHOD_WRAPPER(getPDF, getPDF_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(getRDF, getRDF_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(getRgrid, getRgrid_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(getF, getF_asarray) -DECLARE_PYARRAY_METHOD_WRAPPER(getQgrid, getQgrid_asarray) -DECLARE_PYLIST_METHOD_WRAPPER(usedEnvelopeTypes, usedEnvelopeTypes_aslist) - -// wrappers for the peakprofile property - -PeakProfilePtr getpeakprofile(PDFCalculator& obj) -{ - return obj.getPeakProfile(); -} - -DECLARE_BYTYPE_SETTER_WRAPPER(setPeakProfile, setpeakprofile) - -// wrappers for the baseline property - -PDFBaselinePtr getbaseline(PDFCalculator& obj) -{ - return obj.getBaseline(); -} - -DECLARE_BYTYPE_SETTER_WRAPPER(setBaseline, setbaseline) - -// wrappers for the envelopes property - -PDFEnvelopePtr pyobjtoenvelope(object evp) -{ - extract tp(evp); - if (tp.check()) return PDFEnvelope::createByType(tp()); - PDFEnvelopePtr rv = extract(evp); - return rv; -} - - -template -tuple getenvelopes(T& obj) -{ - std::set etps = obj.usedEnvelopeTypes(); - std::set::const_iterator tpi; - list elst; - for (tpi = etps.begin(); tpi != etps.end(); ++tpi) - { - elst.append(obj.getEnvelopeByType(*tpi)); - } - tuple rv(elst); - return rv; -} - -template -void setenvelopes(T& obj, object evps) -{ - stl_input_iterator eit(evps), end; - // first check if all evps items can be converted to PDFEnvelopePtr - std::list elst; - for (; eit != end; ++eit) elst.push_back(pyobjtoenvelope(*eit)); - // if that worked, overwrite the original envelopes - obj.clearEnvelopes(); - std::list::iterator eii = elst.begin(); - for (; eii != elst.end(); ++eii) obj.addEnvelope(*eii); -} - -// wrapper for the usedenvelopetypes - -template -tuple getusedenvelopetypes(T& obj) -{ - tuple rv(usedEnvelopeTypes_aslist(obj)); - return rv; -} - -template -void addenvelope(T& obj, object evp) -{ - PDFEnvelopePtr e = pyobjtoenvelope(evp); - obj.addEnvelope(e); -} - -template -void popenvelope(T& obj, object evp) -{ - extract tp(evp); - if (tp.check()) obj.popEnvelopeByType(tp()); - else - { - PDFEnvelopePtr e = extract(evp); - obj.popEnvelope(e); - } -} - -template -PDFEnvelopePtr getoneenvelope(T& obj, const std::string& tp) -{ - return obj.getEnvelopeByType(tp); -} - - -// wrap shared methods and attributes of PDFCalculators - -template -C& wrap_PDFCommon(C& boostpythonclass) -{ - namespace bp = boost::python; - typedef typename C::wrapped_type W; - boostpythonclass - // result vectors - .add_property("pdf", getPDF_asarray, - doc_PDFCommon_pdf) - .add_property("rdf", getRDF_asarray, - doc_PDFCommon_rdf) - .add_property("rgrid", getRgrid_asarray, - doc_PDFCommon_rgrid) - .add_property("fq", getF_asarray, - doc_PDFCommon_fq) - .add_property("qgrid", getQgrid_asarray, - doc_PDFCommon_qgrid) - // PDF envelopes - .add_property("envelopes", - getenvelopes, setenvelopes, - doc_PDFCommon_envelopes) - .add_property("usedenvelopetypes", - getusedenvelopetypes, - doc_PDFCommon_usedenvelopetypes) - .def("addEnvelope", addenvelope, - bp::arg("envlp"), doc_PDFCommon_addEnvelope) - .def("popEnvelope", popenvelope, - doc_PDFCommon_popEnvelope) - .def("getEnvelope", getoneenvelope, - bp::arg("tp"), doc_PDFCommon_getEnvelope) - .def("clearEnvelopes", &W::clearEnvelopes, - doc_PDFCommon_clearEnvelopes) - ; - return boostpythonclass; -} - -// local helper for converting python object to a quantity type - -tuple fftftog_array_step(object f, double qstep, double qmin) -{ - QuantityType f0; - const QuantityType& f1 = extractQuantityType(f, f0); - QuantityType g = fftftog(f1, qstep, qmin); - object ga = convertToNumPyArray(g); - double qmaxpad = g.size() * qstep; - double rstep = (qmaxpad > 0) ? (M_PI / qmaxpad) : 0.0; - return make_tuple(ga, rstep); -} - - -tuple fftgtof_array_step(object g, double rstep, double rmin) -{ - QuantityType g0; - const QuantityType& g1 = extractQuantityType(g, g0); - QuantityType f = fftgtof(g1, rstep, rmin); - object fa = convertToNumPyArray(f); - double rmaxpad = f.size() * rstep; - double qstep = (rmaxpad > 0) ? (M_PI / rmaxpad) : 0.0; - return make_tuple(fa, qstep); -} - -// pickling support ---------------------------------------------------------- - -template -tuple getstate_super(object& obj) -{ - // obtain C++ state without PDFEnvelopes - object envlps = obj.attr("envelopes"); - obj.attr("clearEnvelopes")(); - assert(len(obj.attr("envelopes")) == 0); - tuple rv(make_tuple(Super::getstate(obj))); - obj.attr("envelopes") = envlps; - assert(len(obj.attr("envelopes")) == len(envlps)); - return rv; -} - - -tuple getstate_common(object& obj) -{ - auto resolve_pwm = resolve_state_object; - auto resolve_sft = resolve_state_object; - tuple rv = make_tuple( - resolve_pwm(obj.attr("peakwidthmodel")), - resolve_sft(obj.attr("scatteringfactortable")), - obj.attr("envelopes") - ); - return rv; -} - - -template -void setstate_common(object& obj, Iter& st) -{ - assign_state_object(obj.attr("peakwidthmodel"), *(++st)); - assign_state_object(obj.attr("scatteringfactortable"), *(++st)); - assert(len(obj.attr("envelopes")) == 0); - obj.attr("envelopes") = *(++st); -} - - -class DebyePDFCalculatorPickleSuite : - public PairQuantityPickleSuite -{ - private: - - typedef PairQuantityPickleSuite Super; - - public: - - static tuple getstate(object obj) - { - tuple rv( - getstate_super(obj) + - getstate_common(obj) - ); - return rv; - } - - - static void setstate(object obj, tuple state) - { - ensure_tuple_length(state, 4); - // restore the state using boost serialization - tuple st0 = extract(state[0]); - Super::setstate(obj, st0); - // other items are non-None only when restoring Python class - stl_input_iterator st(state); - setstate_common(obj, st); - } -}; - - -class PDFCalculatorPickleSuite : - public PairQuantityPickleSuite -{ - private: - - typedef PairQuantityPickleSuite Super; - - public: - - static tuple getstate(object obj) - { - tuple mystate = make_tuple( - resolve_state_object(obj.attr("peakprofile")), - resolve_state_object(obj.attr("baseline")) - ); - tuple rv( - getstate_super(obj) + - getstate_common(obj) + - mystate - ); - return rv; - } - - - static void setstate(object obj, tuple state) - { - ensure_tuple_length(state, 6); - // restore the state using boost serialization - tuple st0 = extract(state[0]); - Super::setstate(obj, st0); - // other items are non-None only when restoring Python class - stl_input_iterator st(state); - setstate_common(obj, st); - assign_state_object(obj.attr("peakprofile"), *(++st)); - assign_state_object(obj.attr("baseline"), *(++st)); - } -}; - -} // namespace nswrap_PDFCalculators - -// Wrapper definition -------------------------------------------------------- - -void wrap_PDFCalculators() -{ - using namespace nswrap_PDFCalculators; - namespace bp = boost::python; - - // DebyePDFCalculator - class_ > - dbpdfc_class("DebyePDFCalculator", doc_DebyePDFCalculator); - wrap_PDFCommon(dbpdfc_class) - .def("setOptimumQstep", &DebyePDFCalculator::setOptimumQstep, - doc_DebyePDFCalculator_setOptimumQstep) - .def("isOptimumQstep", &DebyePDFCalculator::isOptimumQstep, - doc_DebyePDFCalculator_isOptimumQstep) - .def_pickle(DebyePDFCalculatorPickleSuite()) - ; - - // PDFCalculator - class_ > - pdfc_class("PDFCalculator", doc_PDFCalculator); - wrap_PDFCommon(pdfc_class) - // PDF peak profile - .add_property("peakprofile", - getpeakprofile, - setpeakprofile, - doc_PDFCalculator_peakprofile) - // PDF baseline - .add_property("baseline", - getbaseline, - setbaseline, - doc_PDFCalculator_baseline) - .def_pickle(PDFCalculatorPickleSuite()) - ; - - // FFT functions - def("fftftog", fftftog_array_step, - (bp::arg("f"), bp::arg("qstep"), bp::arg("qmin")=0.0), - doc_fftftog); - def("fftgtof", fftgtof_array_step, - (bp::arg("g"), bp::arg("rstep"), bp::arg("rmin")=0.0), - doc_fftgtof); - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_PDFEnvelope.cpp b/src/extensions/wrap_PDFEnvelope.cpp deleted file mode 100644 index 54c9d37e..00000000 --- a/src/extensions/wrap_PDFEnvelope.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the PDFEnvelope class. The business methods can be overloaded -* from Python to create custom PDF envelope functions. -* -*****************************************************************************/ - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "srreal_numpy_symbol.hpp" -// numpy/arrayobject.h needs to be included after srreal_numpy_symbol.hpp, -// which defines PY_ARRAY_UNIQUE_SYMBOL. NO_IMPORT_ARRAY indicates -// import_array will be called in the extension module initializer. -#define NO_IMPORT_ARRAY -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_registry.hpp" - -namespace srrealmodule { -namespace nswrap_PDFEnvelope { - -using namespace boost; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_PDFEnvelope = "\ -Base class and registry for functions that return PDF scaling envelopes.\n\ -"; - -const char* doc_PDFEnvelope___call__ = "\ -Calculate PDF envelope at the specified r.\n\ -\n\ -r -- atom distance in Angstroms where the scale envelope is evaluated.\n\ - Float or NumPy array.\n\ -\n\ -Return float or NumPy array.\n\ -"; - -const char* doc_QResolutionEnvelope = "\ -Gaussian dampening envelope function due to limited Q-resolution.\n\ -\n\ -Returns exp(-qdamp * x**2).\n\ -Returns 1 when qdamp is zero or negative.\n\ -"; - -const char* doc_ScaleEnvelope = "\ -Uniform scaling envelope function.\n\ -\n\ -Returns scale.\n\ -"; - -const char* doc_SphericalShapeEnvelope = "\ -Dampening PDF envelope due to finite spherical particle shape.\n\ -\n\ -Returns (1 - 1.5*tau + 0.5*tau**3), where tau = x/spdiameter.\n\ -Returns 1 when spdiameter <= 0.\n\ -"; - -const char* doc_StepCutEnvelope = "\n\ -Step function damping envelope.\n\ -\n\ -Returns 1 when x <= stepcut or if stepcut <= 0.\n\ -Returns 0 when x > stepcut.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -// Helper class allows overload of the PDFEnvelope methods from Python. - -class PDFEnvelopeWrap : - public PDFEnvelope, - public wrapper_srreal -{ - public: - - // HasClassRegistry methods - - PDFEnvelopePtr create() const - { - object rv = this->get_pure_virtual_override("create")(); - return mconfigurator.fetch(rv); - } - - PDFEnvelopePtr clone() const - { - return this->get_pure_virtual_override("clone")(); - } - - const std::string& type() const - { - python::object tp = this->get_pure_virtual_override("type")(); - mtype = python::extract(tp); - return mtype; - } - - // own methods - - double operator()(const double& x) const - { - return this->get_pure_virtual_override("__call__")(x); - } - - protected: - - // HasClassRegistry method - - void setupRegisteredObject(PDFEnvelopePtr p) const - { - mconfigurator.setup(p); - } - - private: - - mutable std::string mtype; - wrapper_registry_configurator mconfigurator; - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - using boost::serialization::base_object; - ar & base_object(*this); - } - -}; // class PDFEnvelopeWrap - - -object callnparray(const PDFEnvelope* obj, object& x) -{ - NumPyArray_DoublePtr xx = extractNumPyDoubleArray(x); - NumPyArray_DoublePtr yy = createNumPyDoubleArrayLike(xx.first); - double* src = xx.second; - double* last = xx.second + PyArray_Size(xx.first.ptr()); - double* dst = yy.second; - for (; src != last; ++src, ++dst) *dst = (*obj)(*src); - return yy.first; -} - -} // namespace nswrap_PDFEnvelope - -// Wrapper definition -------------------------------------------------------- - -void wrap_PDFEnvelope() -{ - using namespace nswrap_PDFEnvelope; - using diffpy::Attributes; - namespace bp = boost::python; - - class_, noncopyable> - pdfenvelope("PDFEnvelope", doc_PDFEnvelope); - wrap_registry_methods(pdfenvelope) - .def("__call__", callnparray, - bp::arg("r_array")) - .def("__call__", &PDFEnvelope::operator(), - bp::arg("r"), doc_PDFEnvelope___call__) - .def_pickle(SerializationPickleSuite()) - ; - - register_ptr_to_python(); - - class_ >( - "QResolutionEnvelope", doc_QResolutionEnvelope) - .def_pickle(SerializationPickleSuite()) - ; - class_ >( - "ScaleEnvelope", doc_ScaleEnvelope) - .def_pickle(SerializationPickleSuite()) - ; - class_ >( - "SphericalShapeEnvelope", doc_SphericalShapeEnvelope) - .def_pickle(SerializationPickleSuite()) - ; - class_ >( - "StepCutEnvelope", doc_StepCutEnvelope) - .def_pickle(SerializationPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// Serialization ------------------------------------------------------------- - -BOOST_CLASS_EXPORT(srrealmodule::nswrap_PDFEnvelope::PDFEnvelopeWrap) - -// End of file diff --git a/src/extensions/wrap_PairQuantity.cpp b/src/extensions/wrap_PairQuantity.cpp deleted file mode 100644 index d3403ce5..00000000 --- a/src/extensions/wrap_PairQuantity.cpp +++ /dev/null @@ -1,896 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the PairQuantity class. The business protected methods -* can be overridden from Python to create custom calculator. -* The class provides bindings to the eval and value methods for all derived -* calculators and also the double attributes access that is inherited from -* the Attributes wrapper in wrap_Attributes. -* -* Exported classes in Python: -* -* class QuantityType -- wrapped std::vector -* -* class BasePairQuantity -- base class to all calculators in Python - -* class PairQuantity -- derived class with publicized protected methods -* _addPairContribution, _resetValue, etc. Allows their override from Python. -* -*****************************************************************************/ - -#include -#include -#include -#include -#include - -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_validators.hpp" - -#include - -namespace boost { -namespace python { - -struct make_pybytes -{ - PyObject* operator()(const std::string& s) const - { - std::string::const_pointer pfirst = s.empty() ? NULL : &(s[0]); - PyObject* rv = PyBytes_FromStringAndSize(pfirst, s.size()); - return rv; - } - - - const PyTypeObject* get_pytype() const - { - return &PyBytes_Type; - } -}; - - -struct copy_string_to_pybytes -{ - template - struct apply - { - // Fail if this result conversion is used for function - // that does not return std::string. - BOOST_MPL_ASSERT(( is_same )); - typedef make_pybytes type; - }; -}; - -} // namespace python -} // namespace boost - -namespace srrealmodule { -namespace nswrap_PairQuantity { - -using namespace boost; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_BasePairQuantity_eval = "\ -Calculate a pair quantity for the specified structure.\n\ -\n\ -stru -- structure object that can be converted to StructureAdapter.\n\ - Use the last structure when None.\n\ -\n\ -Return a copy of the internal total contributions.\n\ -May need to be further transformed to get the desired value.\n\ -"; - -const char* doc_BasePairQuantity_value = "\ -Internal vector of total contributions as numpy array.\n\ -"; - -const char* doc_BasePairQuantity__mergeParallelData = "\ -Process raw results string from a parallel job and add them to this instance.\n\ -\n\ -pdata -- raw data string from the parallel _getParallelData function.\n\ - The actual processing of pdata happens in _executeParallelMerge.\n\ -ncpu -- number of parallel jobs. The finishValue method is called after\n\ - merging ncpu parallel values.\n\ -\n\ -No return value. For parallel calculation this method has to be executed\n\ -exactly ncpu times in the master object after the resetValue call.\n\ -Raise RuntimeError if called too many times.\n\ -"; - -const char* doc_BasePairQuantity__getParallelData = "\ -Return raw results string from a parallel job.\n\ -"; - -const char* doc_BasePairQuantity_setStructure = "\ -Assign structure to be evaluated without executing the calculation.\n\ -This zeros the internal values array and updates the pair mask data.\n\ -\n\ -stru -- structure object that can be converted to StructureAdapter.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BasePairQuantity_getStructure = "\ -The StructureAdapter instance of the last evaluated structure.\n\ -"; - -const char* doc_BasePairQuantity__setupParallelRun = "\ -Configure this object for a partial calculation in a parallel run.\n\ -\n\ -cpuindex -- integer from 0 to ncpu-1 that identifies the partial\n\ - calculation to be evaluated.\n\ -ncpu -- number of parallel processes or the total number of\n\ - partial calculations. Must be at least one.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BasePairQuantity_evaluatortype = "\ -String type of preferred evaluation procedure.\n\ -\n\ -Possible values are 'BASIC', 'OPTIMIZED', and 'CHECK'. The value is\n\ -always calculated from scratch when 'BASIC'. The 'OPTIMIZED' evaluation\n\ -updates the existing results by recalculating only the contributions\n\ -from changed atoms. The 'CHECK' evaluation verifies that 'OPTIMIZED'\n\ -and 'BASIC' results are equal. It is intended only for debugging\n\ -purposes.\n\ -\n\ -See also evaluatortypeused.\n\ -"; - -const char* doc_BasePairQuantity_evaluatortypeused = "\ -String type of evaluation procedure used in the last calculation.\n\ -\n\ -Possible values are 'BASIC', 'OPTIMIZED', 'CHECK', and 'NONE'\n\ -when calculator that has not been used yet.\n\ -"; - -const char* doc_BasePairQuantity_maskAllPairs = "\ -Set the calculation mask for all atom pairs in the structure.\n\ -\n\ -mask -- True if all pairs should be included, False if excluded.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BasePairQuantity_invertMask = "\ -Invert mask that controls which atom pairs should be included.\n\ -"; - -const char* doc_BasePairQuantity_setPairMask = "\ -Include or exclude specified atom pairs in the calculation.\n\ -The pair masking is exclusively based either on site indices\n\ -or atom types. This function applies index-based masking and\n\ -cancels any type-based masks.\n\ -\n\ -i -- zero based index of the first site in the pair.\n\ - Can be also an iterable of indices or a string 'all' or 'ALL',\n\ - which select all sites in the structure.\n\ -j -- index of the second site in the pair. Can be an iterable\n\ - or string 'all', just like argument i\n\ -mask -- mask of the atom pair i, j, True if included, False if excluded.\n\ -others -- optional mask applied to all other pairs. Ignored when None.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BasePairQuantity_getPairMask = "\ -Return calculation mask for a pair of atom indices.\n\ -\n\ -i -- zero based index of the first site in the pair\n\ -j -- zero based index of the second site in the pair\n\ -\n\ -Return boolean mask. Note the value may be incorrect, because type-based\n\ -masking is applied with a delay. The value is guaranteed correct after\n\ -a call of setStructure or eval methods.\n\ -"; - -const char* doc_BasePairQuantity_setTypeMask = "\ -Include or exclude specified atom-type pairs in the calculation.\n\ -The pair masking is exclusively based either on site indices\n\ -or atom types. This function applies type-based masking and\n\ -cancels any previous index-based masks.\n\ -\n\ -tpi -- first atom type in the pair, string or an iterable of strings.\n\ - When 'all' or 'ALL', tpi refers to all sites in the structure.\n\ -tpj -- second atom type in the pair, string or an iterable of strings.\n\ - When 'all' or 'ALL', tpj refers to all sites in the structure.\n\ -mask -- mask for the atom types pair.\n\ - True if included, False if excluded.\n\ -others -- optional mask applied to all other pairs. Ignored when None.\n\ -\n\ -No return value.\n\ -"; - -const char* doc_BasePairQuantity_getTypeMask = "\ -Return calculation mask for a pair of atom types.\n\ -\n\ -tpi -- element symbol of the first type in the pair.\n\ -tpj -- element symbol of the second type in the pair.\n\ -\n\ -Return boolean mask. The value is meaningless for index-based\n\ -masking. Use getTypeMask('', '') to get the default pair mask.\n\ -"; - -const char* doc_BasePairQuantity_ticker = "\ -Return EventTicker object with the last configuration change time.\n\ -\n\ -The ticker should be clicked on every configuration change that\n\ -requires reevaluation of the PairQuantity even for an unchanged\n\ -structure.\n\ -"; - -const char* doc_BasePairQuantity_copy = "\ -Return a deep copy of this PairQuantity object.\n\ -"; - -const char* doc_PairQuantity = "\ -Base class for Python defined pair quantity calculators.\n\ -No action by default. Concrete calculators must override the\n\ -_addPairContribution method to get some results.\n\ -"; - -const char* doc_PairQuantity_ticker = "\ -Return EventTicker object with the last configuration change time.\n\ -\n\ -The ticker should be clicked on every configuration change that\n\ -requires reevaluation of the PairQuantity even for an unchanged\n\ -structure.\n\ -\n\ -This method can be overridden in the derived class.\n\ -"; - -const char* doc_PairQuantity__getParallelData = "\ -Return raw results string from a parallel job.\n\ -By default a serialized content of the internal values array.\n\ -This can be added to the master object values by calling\n\ -PairQuantity._executeParallelMerge.\n\ -\n\ -This method can be overridden in the derived class.\n\ -"; - -const char* doc_PairQuantity__resizeValue = "\ -Resize the internal contributions array to the specified size.\n\ -\n\ -sz -- new length of the internal array.\n\ -\n\ -No return value. This method can be overridden in the derived class.\n\ -"; - -const char* doc_PairQuantity__resetValue = "\ -Reset all contribution in the internal array to zero.\n\ -\n\ -No return value. This method can be overridden in the derived class.\n\ -For parallel calculations this resets the count of merged parallel\n\ -results to zero.\n\ -"; - -const char* doc_PairQuantity__configureBondGenerator = "\ -Configure bond generator just before the start of summation.\n\ -The default method sets the upper and lower limits for the pair\n\ -distances. A method override can be used to apply a different\n\ -distance range.\n\ -\n\ -bnds -- instance of BaseBondGenerator to be configured\n\ -\n\ -No return value. This method can be overridden in the derived class.\n\ -"; - -const char* doc_PairQuantity__addPairContribution = "\ -Process pair contribution at a unique bond generator state.\n\ -No action by default, needs to be overridden to do something.\n\ -\n\ -bnds -- instance of BaseBondGenerator holding data for\n\ - a particular pair of atoms during summation.\n\ -sumscale -- integer scaling for this contribution passed from\n\ - PQEvaluator. Equals 1 if bnds.site0() == bnds.site1(),\n\ - 2 otherwise. Can be negative when contribution is\n\ - removed for fast quantity updates.\n\ -\n\ -No return value. This method is executed for every atom pair in the structure.\n\ -"; - -const char* doc_PairQuantity__executeParallelMerge = "\ -Process raw results string from a parallel job and add them to this instance.\n\ -By default converts the string to an array an adds it to the internal values.\n\ -This method should be never used directly, it is instead called by the\n\ -_mergeParallelData method.\n\ -\n\ -pdata -- raw data string from the parallel _getParallelData function.\n\ -\n\ -No return value. This method can be overridden in the derived class.\n\ -"; - -const char* doc_PairQuantity__finishValue = "\ -Final processing of the results after iteration over all pairs.\n\ -This is for operations that are not suitable in the _addPairContribution\n\ -method, for example sorting.\n\ -\n\ -No return value. This method can be overridden in the derived class.\n\ -No action by default.\n\ -"; - -const char* doc_PairQuantity__stashPartialValue = "\ -Save results from unchanged part of the structure in OPTIMIZED evaluation.\n\ -\n\ -This method gets called in OPTIMIZED calculation just before assigning\n\ -the new structure, which implicitly calls _resetValue. The method must\n\ -store internal partial results, for example as private class attributes.\n\ -The accompanying function _restorePartialValue then recovers the stored\n\ -values to undo the _resetValue effects.\n\ -\n\ -No return value. This method must be overridden in the derived class to\n\ -support OPTIMIZED evaluation.\n\ -\n\ -See also _restorePartialValue.\n\ -"; - -const char* doc_PairQuantity__restorePartialValue = "\ -Restore partial results from unchanged sub-structure in OPTIMIZED evaluation.\n\ -\n\ -This method is executed in OPTIMIZED calculation after assignment of the\n\ -new Structure and the implicit call of _resetValue. The method must\n\ -restore internal results that were saved before by _stashPartialValue.\n\ -\n\ -No return value. This method must be overridden in the derived class to\n\ -support OPTIMIZED evaluation.\n\ -\n\ -See also _stashPartialValue.\n\ -"; - -const char* doc_PairQuantity__value = "\ -Reference to the internal vector of total contributions.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -// representation of QuantityType objects -python::object repr_QuantityType(const QuantityType& v) -{ - python::object rv = ("QuantityType%r" % - python::make_tuple(python::tuple(v))); - return rv; -} - - -// PairQuantity::eval is a template non-constant method and -// needs an explicit wrapper function. - -python::object eval_asarray(PairQuantity& obj, python::object& a) -{ - QuantityType value = (a.is_none()) ? obj.eval() : obj.eval(a); - python::object rv = convertToNumPyArray(value); - return rv; -} - -// support for the evaluatortype property - -const char* evtp_NONE = "NONE"; -const char* evtp_BASIC = "BASIC"; -const char* evtp_OPTIMIZED = "OPTIMIZED"; -const char* evtp_CHECK = "CHECK"; - -std::string stringevaluatortype(PQEvaluatorType tp) -{ - switch (tp) - { - case NONE: - return evtp_NONE; - case BASIC: - return evtp_BASIC; - case OPTIMIZED: - return evtp_OPTIMIZED; - case CHECK: - return evtp_CHECK; - } - const char* emsg = "Unknown internal value of PQEvaluatorType."; - PyErr_SetString(PyExc_NotImplementedError, emsg); - throw_error_already_set(); - abort(); -} - - -std::string getevaluatortype(const PairQuantity& obj) -{ - return stringevaluatortype(obj.getEvaluatorType()); -} - - -void setevaluatortype(PairQuantity& pq, const std::string& tp) -{ - if (tp == evtp_BASIC) return pq.setEvaluatorType(BASIC); - if (tp == evtp_OPTIMIZED) return pq.setEvaluatorType(OPTIMIZED); - if (tp == evtp_CHECK) return pq.setEvaluatorType(CHECK); - python::object emsg = ("evaluatortype must be one of %r." % - python::make_tuple(python::make_tuple( - evtp_BASIC, evtp_OPTIMIZED, evtp_CHECK))); - PyErr_SetObject(PyExc_ValueError, emsg.ptr()); - throw_error_already_set(); -} - -// support for the evaluatortypeused read-only property - -std::string getevaluatortypeused(const PairQuantity& obj) -{ - return stringevaluatortype(obj.getEvaluatorTypeUsed()); -} - -// support "all", "ALL" and integer iterables in setPairMask - -std::vector parsepairindex(python::object i) -{ - std::vector rv; - // string equal "all" or "ALL" - python::extract gets(i); - if (gets.check()) - { - python::str lc_all(PairQuantity::ALLATOMSSTR); - python::str uc_all = lc_all.upper(); - if (i != lc_all && i != uc_all) - { - python::object emsg = ("String argument must be %r or %r." % - python::make_tuple(lc_all, uc_all)); - PyErr_SetObject(PyExc_ValueError, emsg.ptr()); - throw_error_already_set(); - } - rv.push_back(PairQuantity::ALLATOMSINT); - return rv; - } - // otherwise translate to a vector of integers - rv = extractintvector(i); - return rv; -} - -// support string iterables in setTypeMask - -std::vector parsepairtypes( - python::extract& getsmbli, python::object smbli) -{ - std::vector rv; - if (getsmbli.check()) - { - rv.push_back(getsmbli()); - } - else - { - python::stl_input_iterator first(smbli), last; - rv.assign(first, last); - } - return rv; -} - - -void mask_all_pairs(PairQuantity& obj, python::object msk) -{ - bool mask = msk; - obj.maskAllPairs(mask); -} - - -void set_pair_mask(PairQuantity& obj, - python::object i, python::object j, python::object msk, - python::object others) -{ - if (!others.is_none()) mask_all_pairs(obj, others); - bool mask = msk; - // short circuit for normal call with scalar values - if (!isiterable(i) && !isiterable(j)) - { - const int i1 = extractint(i); - const int j1 = extractint(j); - obj.setPairMask(i1, j1, mask); - return; - } - std::vector iindices = parsepairindex(i); - std::vector jindices = parsepairindex(j); - std::vector::const_iterator ii, jj; - for (ii = iindices.begin(); ii != iindices.end(); ++ii) - { - for (jj = jindices.begin(); jj != jindices.end(); ++jj) - { - obj.setPairMask(*ii, *jj, mask); - } - } -} - - -void set_type_mask(PairQuantity& obj, - python::object smbli, python::object smblj, python::object msk, - python::object others) -{ - using namespace std; - if (!others.is_none()) mask_all_pairs(obj, others); - python::extract getsmbli(smbli); - python::extract getsmblj(smblj); - bool mask = msk; - // short circuit for normal call - if (getsmbli.check() && getsmblj.check()) - { - obj.setTypeMask(getsmbli(), getsmblj(), mask); - return; - } - vector isymbols = parsepairtypes(getsmbli, smbli); - vector jsymbols = parsepairtypes(getsmblj, smblj); - vector::const_iterator tii, tjj; - for (tii = isymbols.begin(); tii != isymbols.end(); ++tii) - { - for (tjj = jsymbols.begin(); tjj != jsymbols.end(); ++tjj) - { - obj.setTypeMask(*tii, *tjj, mask); - } - } -} - - -// provide a copy method for convenient deepcopy of the object - -python::object pqcopy(python::object pqobj) -{ - python::object copy = python::import("copy").attr("copy"); - python::object rv = copy(pqobj); - return rv; -} - -// Helper C++ class for publicizing the protected methods. - -class PairQuantityExposed : public PairQuantity -{ - public: - - // non-constant version suitable for exposing mvalue in Python - QuantityType& value() - { - return mvalue; - } - - - void resizeValue(size_t sz) - { - this->PairQuantity::resizeValue(sz); - } - - - void resetValue() - { - this->PairQuantity::resetValue(); - } - - - void configureBondGenerator(BaseBondGenerator& bnds) const - { - this->PairQuantity::configureBondGenerator(bnds); - } - - - void addPairContribution(const BaseBondGenerator& bnds, int sumscale) - { - this->PairQuantity::addPairContribution(bnds, sumscale); - } - - - void executeParallelMerge(const std::string& pdata) - { - this->PairQuantity::executeParallelMerge(pdata); - } - - - void finishValue() - { - this->PairQuantity::finishValue(); - } - - - void stashPartialValue() - { - this->PairQuantity::stashPartialValue(); - } - - - void restorePartialValue() - { - this->PairQuantity::restorePartialValue(); - } - -}; - - -// The second helper class allows override of the exposed PairQuantity -// methods from Python. - -class PairQuantityWrap : - public PairQuantityExposed, - public wrapper -{ - public: - - // Make getParallelData overridable from Python. - - std::string getParallelData() const - { - override f = this->get_override("_getParallelData"); - if (f) return f(); - return this->default_getParallelData(); - } - - std::string default_getParallelData() const - { - return this->PairQuantityExposed::getParallelData(); - } - - // Make the ticker method overridable from Python - - diffpy::eventticker::EventTicker& ticker() const - { - using diffpy::eventticker::EventTicker; - override f = this->get_override("ticker"); - if (f) - { - // avoid "dangling reference error" when used from C++ - object ptic = f(); - return extract(ptic); - } - return this->default_ticker(); - } - - diffpy::eventticker::EventTicker& default_ticker() const - { - return this->PairQuantityExposed::ticker(); - } - - // Make the protected virtual methods public so they - // can be exported to Python and overridden as well. - - void resizeValue(size_t sz) - { - override f = this->get_override("_resizeValue"); - if (f) f(sz); - else this->default_resizeValue(sz); - } - - void default_resizeValue(size_t sz) - { - this->PairQuantityExposed::resizeValue(sz); - } - - - void resetValue() - { - override f = this->get_override("_resetValue"); - if (f) f(); - else this->default_resetValue(); - } - - void default_resetValue() - { - this->PairQuantityExposed::resetValue(); - } - - - void configureBondGenerator(BaseBondGenerator& bnds) const - { - override f = this->get_override("_configureBondGenerator"); - if (f) f(ptr(&bnds)); - else this->default_configureBondGenerator(bnds); - } - - void default_configureBondGenerator(BaseBondGenerator& bnds) const - { - this->PairQuantityExposed::configureBondGenerator(bnds); - } - - - void addPairContribution(const BaseBondGenerator& bnds, - int summationscale) - { - override f = this->get_override("_addPairContribution"); - if (f) f(ptr(&bnds), summationscale); - else this->default_addPairContribution(bnds, summationscale); - } - - void default_addPairContribution(const BaseBondGenerator& bnds, - int summationscale) - { - this->PairQuantityExposed::addPairContribution(bnds, summationscale); - } - - - void executeParallelMerge(const std::string& pdata) - { - override f = this->get_override("_executeParallelMerge"); - if (f) f(pdata); - else this->default_executeParallelMerge(pdata); - } - - void default_executeParallelMerge(const std::string& pdata) - { - this->PairQuantityExposed::executeParallelMerge(pdata); - } - - - void finishValue() - { - override f = this->get_override("_finishValue"); - if (f) f(); - else this->default_finishValue(); - } - - void default_finishValue() - { - this->PairQuantityExposed::finishValue(); - } - - - void stashPartialValue() - { - override f = this->get_override("_stashPartialValue"); - if (f) f(); - else this->default_stashPartialValue(); - } - - void default_stashPartialValue() - { - this->PairQuantityExposed::stashPartialValue(); - } - - - void restorePartialValue() - { - override f = this->get_override("_restorePartialValue"); - if (f) f(); - else this->default_restorePartialValue(); - } - - void default_restorePartialValue() - { - this->PairQuantityExposed::restorePartialValue(); - } - -}; // class PairQuantityWrap - -} // namespace nswrap_PairQuantity - -// Wrapper definition -------------------------------------------------------- - -void wrap_PairQuantity() -{ - using namespace nswrap_PairQuantity; - using diffpy::Attributes; - const python::object None; - - typedef StructureAdapterPtr&(PairQuantity::*getstru)(); - - class_("QuantityType") - .def(vector_indexing_suite()) - .def("__repr__", repr_QuantityType) - ; - - class_ >("BasePairQuantity") - .def("eval", eval_asarray, python::arg("stru")=None, - doc_BasePairQuantity_eval) - .add_property("value", value_asarray, - doc_BasePairQuantity_value) - .def("_mergeParallelData", &PairQuantity::mergeParallelData, - (python::arg("pdata"), python::arg("ncpu")), - doc_BasePairQuantity__mergeParallelData) - .def("_getParallelData", &PairQuantity::getParallelData, - return_value_policy(), - doc_BasePairQuantity__getParallelData) - .def("setStructure", &PairQuantity::setStructure, - python::arg("stru"), - doc_BasePairQuantity_setStructure) - .def("getStructure", getstru(&PairQuantity::getStructure), - return_value_policy(), - doc_BasePairQuantity_getStructure) - .def("_setupParallelRun", &PairQuantity::setupParallelRun, - (python::arg("cpuindex"), python::arg("ncpu")), - doc_BasePairQuantity__setupParallelRun) - .add_property("evaluatortype", - getevaluatortype, setevaluatortype, - doc_BasePairQuantity_evaluatortype) - .add_property("evaluatortypeused", - getevaluatortypeused, - doc_BasePairQuantity_evaluatortypeused) - .def("maskAllPairs", mask_all_pairs, - python::arg("mask"), - doc_BasePairQuantity_maskAllPairs) - .def("invertMask", &PairQuantity::invertMask, - doc_BasePairQuantity_invertMask) - .def("setPairMask", set_pair_mask, - (python::arg("i"), python::arg("j"), python::arg("mask"), - python::arg("others")=None), - doc_BasePairQuantity_setPairMask) - .def("getPairMask", &PairQuantity::getPairMask, - (python::arg("i"), python::arg("j")), - doc_BasePairQuantity_getPairMask) - .def("setTypeMask", set_type_mask, - (python::arg("tpi"), python::arg("tpj"), python::arg("mask"), - python::arg("others")=None), - doc_BasePairQuantity_setTypeMask) - .def("getTypeMask", &PairQuantity::getTypeMask, - (python::arg("tpi"), python::arg("tpj")), - doc_BasePairQuantity_getTypeMask) - .def("ticker", &PairQuantity::ticker, - return_internal_reference<>(), - doc_BasePairQuantity_ticker) - .def("copy", pqcopy, - doc_BasePairQuantity_copy) - ; - - class_, - noncopyable>("PairQuantity", doc_PairQuantity) - .def("ticker", - &PairQuantityExposed::ticker, - &PairQuantityWrap::default_ticker, - return_internal_reference<>(), - doc_PairQuantity_ticker) - .def("_getParallelData", - &PairQuantityExposed::getParallelData, - &PairQuantityWrap::default_getParallelData, - return_value_policy(), - doc_PairQuantity__getParallelData) - .def("_resizeValue", - &PairQuantityExposed::resizeValue, - &PairQuantityWrap::default_resizeValue, - python::arg("sz"), - doc_PairQuantity__resizeValue) - .def("_resetValue", - &PairQuantityExposed::resetValue, - &PairQuantityWrap::default_resetValue, - doc_PairQuantity__resetValue) - .def("_configureBondGenerator", - &PairQuantityExposed::configureBondGenerator, - &PairQuantityWrap::default_configureBondGenerator, - python::arg("bnds"), - doc_PairQuantity__configureBondGenerator) - .def("_addPairContribution", - &PairQuantityExposed::addPairContribution, - &PairQuantityWrap::default_addPairContribution, - (python::arg("bnds"), python::arg("sumscale")), - doc_PairQuantity__addPairContribution) - .def("_executeParallelMerge", - &PairQuantityExposed::executeParallelMerge, - &PairQuantityWrap::default_executeParallelMerge, - python::arg("pdata"), - doc_PairQuantity__executeParallelMerge) - .def("_finishValue", - &PairQuantityExposed::finishValue, - &PairQuantityWrap::default_finishValue, - doc_PairQuantity__finishValue) - .def("_stashPartialValue", - &PairQuantityExposed::stashPartialValue, - &PairQuantityWrap::default_stashPartialValue, - doc_PairQuantity__stashPartialValue) - .def("_restorePartialValue", - &PairQuantityExposed::restorePartialValue, - &PairQuantityWrap::default_restorePartialValue, - doc_PairQuantity__restorePartialValue) - .add_property("_value", make_function(&PairQuantityWrap::value, - return_internal_reference<>()), - doc_PairQuantity__value) - // classes PairQuantityExposed, PairQuantityWrap add no members, - // therefore we can create pickle suite from C++ base class. - .def_pickle(PairQuantityPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_PeakProfile.cpp b/src/extensions/wrap_PeakProfile.cpp deleted file mode 100644 index ac0c1ce1..00000000 --- a/src/extensions/wrap_PeakProfile.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the PeakProfile class. The business methods can be overridden -* from Python to create custom peak profiles. This may be however quite slow. -* -*****************************************************************************/ - -#include -#include -#include -#include - -#include - -#include -#include -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_registry.hpp" - -namespace srrealmodule { -namespace nswrap_PeakProfile { - -using namespace boost; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_PeakProfile = "\ -Base class and registry for PDF peak profile functions.\n\ -The peak profile functions must be centered at 0 and their integrated\n\ -area must be 1.\n\ -"; - -const char* doc_PeakProfile___call__ = "\ -Evaluate peak profile function for a given position and peak width.\n\ -\n\ -x -- coordinate where the profile function is evaluated.\n\ - x is always relative to the peak center, i.e., the profile function\n\ - must be centered at 0.\n\ -fwhm -- Full Width at Half Maximum of the profile function.\n\ -\n\ -Return float.\n\ -"; - -const char* doc_PeakProfile_xboundlo = "\ -Lower x-bound where profile function becomes smaller than precision.\n\ -The bound is evaluated relative to profile maximum, i.e., for each x below\n\ -xboundlo the profile function must be smaller than (peakprecision * maximum).\n\ -\n\ -fwhm -- Full Width at Half Maximum of the profile function\n\ -\n\ -Return float. See also the peakprecision property.\n\ -"; - -const char* doc_PeakProfile_xboundhi = "\ -Upper x-bound where profile function becomes smaller than precision.\n\ -The bound is evaluated relative to profile maximum, i.e., for each x above\n\ -xboundhi the profile function must be smaller than (peakprecision * maximum).\n\ -\n\ -fwhm -- Full Width at Half Maximum of the profile function\n\ -\n\ -Return float. See also the peakprecision property.\n\ -"; - -const char* doc_PeakProfile_ticker = "\ -Return EventTicker that marks last modification time of this object.\n\ -This ticker object is used in fast PDF update, to check if PeakProfile\n\ -has changed since the last calculation. The ticker.click() method needs\n\ -to be therefore called after every change in PeakProfile configuration.\n\ -\n\ -Return EventTicker object.\n\ -This method can be overridden in a Python-derived class.\n\ -"; - -const char* doc_PeakProfile__registerThisType = "\ -Add this class to the global registry of PeakProfile types.\n\ -\n\ -This method must be called once after definition of the derived\n\ -class to support pickling and the createByType factory.\n\ -"; - -const char* doc_GaussianProfile = "\ -Gaussian profile function.\n\ -"; - -const char* doc_CroppedGaussianProfile = "\ -Gaussian function cropped to zero at its crossing with peakprecision.\n\ -\n\ -The profile is also rescaled to keep the integrated area of 1.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -// Support for override of PeakProfile methods from Python. - -class PeakProfileWrap : - public PeakProfile, - public wrapper_srreal -{ - public: - - // HasClassRegistry methods - - PeakProfilePtr create() const - { - object rv = this->get_pure_virtual_override("create")(); - return mconfigurator.fetch(rv); - } - - PeakProfilePtr clone() const - { - return this->get_pure_virtual_override("clone")(); - } - - - const std::string& type() const - { - python::object tp = this->get_pure_virtual_override("type")(); - mtype = python::extract(tp); - return mtype; - } - - // own methods - - double operator()(double x, double fwhm) const - { - return this->get_pure_virtual_override("__call__")(x, fwhm); - } - - double xboundlo(double fwhm) const - { - return this->get_pure_virtual_override("xboundlo")(fwhm); - } - - double xboundhi(double fwhm) const - { - return this->get_pure_virtual_override("xboundhi")(fwhm); - } - - // Support for ticker override from Python. - - diffpy::eventticker::EventTicker& ticker() const - { - using diffpy::eventticker::EventTicker; - override f = this->get_override("ticker"); - if (f) - { - // avoid "dangling reference error" when used from C++ - python::object ptic = f(); - return python::extract(ptic); - } - return this->default_ticker(); - } - - diffpy::eventticker::EventTicker& default_ticker() const - { - return this->PeakProfile::ticker(); - } - - protected: - - // HasClassRegistry method - - void setupRegisteredObject(PeakProfilePtr p) const - { - mconfigurator.setup(p); - } - - private: - - mutable std::string mtype; - wrapper_registry_configurator mconfigurator; - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - using boost::serialization::base_object; - ar & base_object(*this); - } - -}; // class PeakProfileWrap - -} // namespace nswrap_PeakProfile - -// Wrapper definition -------------------------------------------------------- - -void wrap_PeakProfile() -{ - using namespace nswrap_PeakProfile; - using diffpy::Attributes; - namespace bp = boost::python; - - class_, noncopyable> - peakprofile("PeakProfile", doc_PeakProfile); - wrap_registry_methods(peakprofile) - .def("__call__", &PeakProfile::operator(), - (bp::arg("x"), bp::arg("fwhm")), doc_PeakProfile___call__) - .def("xboundlo", &PeakProfile::xboundlo, - bp::arg("fwhm"), doc_PeakProfile_xboundlo) - .def("xboundhi", &PeakProfile::xboundhi, - bp::arg("fwhm"), doc_PeakProfile_xboundhi) - .def("ticker", - &PeakProfile::ticker, - &PeakProfileWrap::default_ticker, - return_internal_reference<>(), - doc_PeakProfile_ticker) - .def_pickle(SerializationPickleSuite()) - ; - - register_ptr_to_python(); - - class_ >( - "GaussianProfile", doc_GaussianProfile) - .def_pickle(SerializationPickleSuite()) - ; - - class_ >( - "CroppedGaussianProfile", doc_CroppedGaussianProfile) - .def_pickle(SerializationPickleSuite()) - ; - -} - -} // namespace srrealmodule - -// Serialization ------------------------------------------------------------- - -BOOST_CLASS_EXPORT(srrealmodule::nswrap_PeakProfile::PeakProfileWrap) - -// End of file diff --git a/src/extensions/wrap_PeakWidthModel.cpp b/src/extensions/wrap_PeakWidthModel.cpp deleted file mode 100644 index 21bfac74..00000000 --- a/src/extensions/wrap_PeakWidthModel.cpp +++ /dev/null @@ -1,279 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the PeakWidthModel class. The business methods can be overridden -* from Python to create custom peak widths. This may be however quite slow. -* -*****************************************************************************/ - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_registry.hpp" - -namespace srrealmodule { -namespace nswrap_PeakWidthModel { - -using namespace boost; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_PeakWidthModel = "\ -Base class for functors that calculate the PDF peak widths.\n\ -Peak width is defined as full width at half maximum (FWHM).\n\ -"; - -const char* doc_PeakWidthModel_calculate = "\ -Calculate the FWHM peak width for the specified bond.\n\ -\n\ -bnds -- instance of BaseBondGenerator with the current bond data.\n\ -\n\ -Return float.\n\ -This method must be overridden in a derived class.\n\ -"; - -const char* doc_PeakWidthModel_maxWidth = "\ -Return maximum peak width for the specified structure and distance range\n\ -\n\ -stru -- StructureAdapter object or an object convertible to StructureAdapter.\n\ -rmin -- lower bound for the PDF calculation\n\ -rmax -- upper bound for the PDF calculation\n\ - isotropically vibrating atoms this\n\ -\n\ -Return float.\n\ -"; - -const char* doc_PeakWidthModel_ticker = "\ -Return EventTicker that marks last modification time of this object.\n\ -This ticker object is used in fast PDF update, to check if PeakWidthModel\n\ -has changed since the last calculation. The ticker.click() method needs\n\ -to be therefore called after every change in PeakWidthModel configuration.\n\ -\n\ -Return EventTicker object.\n\ -This method can be overridden in a Python-derived class.\n\ -"; - -const char* doc_ConstantPeakWidth = "\ -Peak width model returning constant width.\n\ -"; - -const char* doc_DebyeWallerPeakWidth = "\ -Calculate PDF peak width from a Debye-Waller model of atom vibrations.\n\ -This returns mean-square displacement of atoms in the pair along their\n\ -bond scaled as FWHM. The atom displacements are assumed independent.\n\ -"; - -const char* doc_JeongPeakWidth = "\ -Calculate PDF peak width assuming I.-K. Jeong model of correlated motion.\n\ -This returns mean-square displacement of atoms in the pair along their\n\ -bond corrected for correlated motion and data noise at high-Q by a scaling\n\ -factor sqrt(1 - delta1/r - delta2/r**2 + (qbroad * r)**2).\n\ -"; - -const char* doc_PeakWidthModelOwner = "\ -Base class for classes that own PeakWidthModel instance.\n\ -"; - -const char* doc_PeakWidthModelOwner_peakwidthmodel = "\ -PeakWidthModel object used for calculating the FWHM of the PDF peaks.\n\ -This attribute can be assigned either a PeakWidthModel-derived object\n\ -or a string name of a registered PeakWidthModel class.\n\ -Use PeakWidthModel.getRegisteredTypes() for a set of registered names.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -double maxwidthwithpystructure(const PeakWidthModel& pwm, - python::object stru, double rmin, double rmax) -{ - StructureAdapterPtr adpt = createStructureAdapter(stru); - double rv = pwm.maxWidth(adpt, rmin, rmax); - return rv; -} - -// wrappers for the peakwidthmodel property - -PeakWidthModelPtr getpwmodel(PeakWidthModelOwner& obj) -{ - return obj.getPeakWidthModel(); -} - -DECLARE_BYTYPE_SETTER_WRAPPER(setPeakWidthModel, setpwmodel) - -// Support for Python override of the PeakWidthModel methods. - -class PeakWidthModelWrap : - public PeakWidthModel, - public wrapper_srreal -{ - public: - - // HasClassRegistry methods - - PeakWidthModelPtr create() const - { - object rv = this->get_pure_virtual_override("create")(); - return mconfigurator.fetch(rv); - } - - PeakWidthModelPtr clone() const - { - return this->get_pure_virtual_override("clone")(); - } - - const std::string& type() const - { - python::object tp = this->get_pure_virtual_override("type")(); - mtype = python::extract(tp); - return mtype; - } - - // own methods - - double calculate(const BaseBondGenerator& bnds) const - { - return this->get_pure_virtual_override("calculate")(ptr(&bnds)); - } - - double maxWidth(StructureAdapterPtr stru, - double rmin, double rmax) const - { - override f = this->get_pure_virtual_override("maxWidth"); - return f(stru, rmin, rmax); - } - - // Make the ticker method overridable from Python - - diffpy::eventticker::EventTicker& ticker() const - { - using diffpy::eventticker::EventTicker; - override f = this->get_override("ticker"); - if (f) - { - // avoid "dangling reference error" when used from C++ - python::object ptic = f(); - return python::extract(ptic); - } - return this->default_ticker(); - } - - diffpy::eventticker::EventTicker& default_ticker() const - { - return this->PeakWidthModel::ticker(); - } - - protected: - - // HasClassRegistry method - - void setupRegisteredObject(PeakWidthModelPtr p) const - { - mconfigurator.setup(p); - } - - private: - - mutable std::string mtype; - wrapper_registry_configurator mconfigurator; - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - using boost::serialization::base_object; - ar & base_object(*this); - } - -}; // class PeakWidthModelWrap - -} // namespace nswrap_PeakWidthModel - -// Wrapper definition -------------------------------------------------------- - -void wrap_PeakWidthModel() -{ - namespace bp = boost::python; - using namespace nswrap_PeakWidthModel; - using diffpy::Attributes; - - class_, noncopyable> - peakwidthmodel("PeakWidthModel", doc_PeakWidthModel); - wrap_registry_methods(peakwidthmodel) - .def("calculate", - &PeakWidthModel::calculate, - bp::arg("bnds"), - doc_PeakWidthModel_calculate) - .def("maxWidth", - &PeakWidthModel::maxWidth, - (bp::arg("stru"), bp::arg("rmin"), bp::arg("rmax")), - doc_PeakWidthModel_maxWidth) - .def("maxWidth", - maxwidthwithpystructure, - (bp::arg("stru"), bp::arg("rmin"), bp::arg("rmax"))) - .def("ticker", - &PeakWidthModel::ticker, - &PeakWidthModelWrap::default_ticker, - return_internal_reference<>(), - doc_PeakWidthModel_ticker) - .def_pickle(SerializationPickleSuite()) - ; - - register_ptr_to_python(); - - class_ >( - "ConstantPeakWidth", doc_ConstantPeakWidth) - .def_pickle(SerializationPickleSuite()) - ; - - class_ >( - "DebyeWallerPeakWidth", doc_DebyeWallerPeakWidth) - .def_pickle(SerializationPickleSuite()) - ; - - class_ >( - "JeongPeakWidth", doc_JeongPeakWidth) - .def_pickle(SerializationPickleSuite()) - ; - - class_("PeakWidthModelOwner", doc_PeakWidthModelOwner) - .add_property("peakwidthmodel", - getpwmodel, - setpwmodel, - doc_PeakWidthModelOwner_peakwidthmodel) - ; -} - -} // namespace srrealmodule - -// Serialization ------------------------------------------------------------- - -BOOST_CLASS_EXPORT(srrealmodule::nswrap_PeakWidthModel::PeakWidthModelWrap) - -// End of file diff --git a/src/extensions/wrap_ScatteringFactorTable.cpp b/src/extensions/wrap_ScatteringFactorTable.cpp deleted file mode 100644 index d7e1875c..00000000 --- a/src/extensions/wrap_ScatteringFactorTable.cpp +++ /dev/null @@ -1,440 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the ScatteringFactorTable class. The business methods can be -* overridden from Python to return custom scattering factor values. -* -*****************************************************************************/ - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "srreal_numpy_symbol.hpp" -// numpy/arrayobject.h needs to be included after srreal_numpy_symbol.hpp, -// which defines PY_ARRAY_UNIQUE_SYMBOL. NO_IMPORT_ARRAY indicates -// import_array will be called in the extension module initializer. -#define NO_IMPORT_ARRAY -#include - - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" -#include "srreal_registry.hpp" - -namespace srrealmodule { -namespace nswrap_ScatteringFactorTable { - -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings - -const char* doc_ScatteringFactorTable = "\ -Base class for looking up scattering factors by atom symbols.\n\ -This class has virtual methods and cannot be used as is.\n\ -\n\ -A derived class has to override the following methods:\n\ -\n\ - create(self)\n\ - clone(self)\n\ - type(self)\n\ - radiationType(self)\n\ - _standardLookup(self, smbl, q)\n\ -\n\ -Derived class can be added to the global registry of ScatteringFactorTable\n\ -types by calling the _registerThisType method with any instance.\n\ -"; - -const char* doc_ScatteringFactorTable_radiationType = "\ -Return a string identifying the radiation type.\n\ -'X' for x-rays, 'N' for neutrons.\n\ -This method must be overridden in a derived class.\n\ -"; - -const char* doc_ScatteringFactorTable_lookup = "\ -Scattering factor of a specified atom at Q in 1/A. The standard value\n\ -can be redefined using the setCustomAs method.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope.\n\ -Q -- Q value in inverse Angstroms, by default 0.\n\ - Q can be either float or NumPy array.\n\ -\n\ -Return float or NumPy array of the same shape as Q.\n\ -No support for Python override.\n\ -"; - -const char* doc_ScatteringFactorTable__standardLookup = "\ -Standard value of the atom scattering factor at given Q in 1/A.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope.\n\ -q -- scattering vector amplitude in 1/A.\n\ -\n\ -Return float.\n\ -Raise ValueError for unknown atom symbol.\n\ -This method must be overridden in a derived class.\n\ -"; - -const char* doc_ScatteringFactorTable_setCustomAs2 = "\ -Define custom alias for the specified atom symbol.\n\ -Example: setCustomAs('12-C', 'C') will declare the same\n\ -scattering factors for '12-C' as for 'C'.\n\ -\n\ -smbl -- custom string alias for an existing standard symbol.\n\ -src -- standard atom symbol (cannot be another alias).\n\ -\n\ -No return value. No support for Python override.\n\ -"; - -const char* doc_ScatteringFactorTable_setCustomAs4 = "\ -Define custom scattering factor for the specified atom symbol.\n\ -The custom value is calculated by rescaling standard value\n\ -from a source atom type.\n\ -\n\ -smbl -- string symbol of the atom with custom scattering factor.\n\ -src -- atom symbol for the source standard scattering factor.\n\ -sf -- new scattering factor value, defaults to the standard src factor.\n\ -q -- optional Q value for the new custom scattering factor.\n\ - The internal scaling of the standard value is calculated at this Q.\n\ -\n\ -No return value. No support for Python override.\n\ -"; - -const char* doc_ScatteringFactorTable_resetCustom = "\ -Revert scattering factor for the specified symbol to a standard value.\n\ -\n\ -smbl -- string symbol for atom, ion or isotope.\n\ -\n\ -No return value. No support for Python override.\n\ -"; - -const char* doc_ScatteringFactorTable_resetAll = "\ -Reset all custom scattering factor values.\n\ -\n\ -No return value. No support for Python override.\n\ -"; - -const char* doc_ScatteringFactorTable_getCustomSymbols = "\ -Return a set of all atom symbols with custom scattering factors.\n\ -"; - -const char* doc_ScatteringFactorTable_ticker = "\ -Return EventTicker that marks last modification time of this object.\n\ -This ticker object is used in fast PDF update, to check if scattering\n\ -factors changed since the last calculation. The ticker.click() method\n\ -thus needs to be used for _standardLookup that returns variable values.\n\ -\n\ -Return EventTicker object.\n\ -This method can be overridden in a Python-derived class.\n\ -"; - -const char* doc_ScatteringFactorTableOwner = "\ -Base class for classes that own ScatteringFactorTable instance.\n\ -"; - -const char* doc_ScatteringFactorTableOwner_scatteringfactortable = "\ -ScatteringFactorTable object used for a lookup of scattering factors.\n\ -This can be also set with the setScatteringFactorTableByType method.\n\ -"; - -const char* doc_ScatteringFactorTableOwner_setScatteringFactorTableByType = "\ -Set internal ScatteringFactorTable according to specified string type.\n\ -\n\ -tp -- string identifier of a registered ScatteringFactorTable type.\n\ - Use ScatteringFactorTable.getRegisteredTypes for the allowed values.\n\ -\n\ -Deprecated: This method is deprecated and will be removed in the 2.0.0 release.\n\ -Use direct assignment to the `scatteringfactortable` property instead, for example:\n\ - obj.scatteringfactortable = SFTNeutron()\n\ -No return value.\n\ -"; - -const char* doc_ScatteringFactorTableOwner_getRadiationType = "\ -Return string identifying the radiation type.\n\ -'X' for x-rays, 'N' for neutrons.\n\ -"; - -const char* doc_SFTXray = "\ -X-ray scattering factors table.\n\ -\n\ -Q-dependence of scattering factors is calculated using\n\ -Waasmaier - Kirfel approximation valid up to Q=75/A.\n\ -"; - -const char* doc_SFTElectron = "\ -Electron scattering factors table.\n\ -\n\ -Q-dependence is derived from X-ray scattering factors according\n\ -to the International Tables Volume C.\n\ -"; - -const char* doc_SFTNeutron = "\ -Table of neutron scattering lengths in fm.\n\ -"; - -const char* doc_SFTElectronNumber = "\ -Table of electron numbers for elements and ions.\n\ -\n\ -Can be used as Q-indendent scattering factors for X-rays.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -DECLARE_PYSET_METHOD_WRAPPER(getCustomSymbols, getCustomSymbols_asset) - -// wrappers for the scatteringfactortable property - -ScatteringFactorTablePtr getsftable(ScatteringFactorTableOwner& obj) -{ - return obj.getScatteringFactorTable(); -} - -DECLARE_BYTYPE_SETTER_WRAPPER(setScatteringFactorTable, setsftable) - -// Helper class to support Python override of ScatteringFactorTable methods - -class ScatteringFactorTableWrap : - public ScatteringFactorTable, - public wrapper_srreal -{ - public: - - // Copy Constructor - - ScatteringFactorTableWrap() { } - - ScatteringFactorTableWrap(const ScatteringFactorTable& src) - { - ScatteringFactorTable& thistable = *this; - // workaround for weird implicit ScatteringFactorTable::operator= - // in g++ Red Hat 4.7.2-2, which must have non-constant argument. - thistable = const_cast(src); - } - - // HasClassRegistry methods - - ScatteringFactorTablePtr create() const - { - object rv = this->get_pure_virtual_override("create")(); - return mconfigurator.fetch(rv); - } - - ScatteringFactorTablePtr clone() const - { - return this->get_pure_virtual_override("clone")(); - } - - const std::string& type() const - { - object tp = this->get_pure_virtual_override("type")(); - mtype = extract(tp); - return mtype; - } - - // own methods - - const std::string& radiationType() const - { - object tp = this->get_pure_virtual_override("radiationType")(); - mradiationtype = extract(tp); - return mradiationtype; - } - - double standardLookup(const std::string& smbl, double q) const - { - return this->get_pure_virtual_override("_standardLookup")(smbl, q); - } - - - // Make the ticker method overridable from Python - - diffpy::eventticker::EventTicker& ticker() const - { - using diffpy::eventticker::EventTicker; - override f = this->get_override("ticker"); - if (f) - { - // avoid "dangling reference error" when used from C++ - object ptic = f(); - return extract(ptic); - } - return this->default_ticker(); - } - - diffpy::eventticker::EventTicker& default_ticker() const - { - return this->ScatteringFactorTable::ticker(); - } - - protected: - - // HasClassRegistry method - - void setupRegisteredObject(ScatteringFactorTablePtr p) const - { - mconfigurator.setup(p); - } - - private: - - mutable std::string mtype; - mutable std::string mradiationtype; - wrapper_registry_configurator mconfigurator; - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - using boost::serialization::base_object; - ar & base_object(*this); - } - -}; // class ScatteringFactorTableWrap - -object lookupnparray(const ScatteringFactorTable& sftb, - std::string smbl, object& qobj) -{ - NumPyArray_DoublePtr aa = extractNumPyDoubleArray(qobj); - NumPyArray_DoublePtr bb = createNumPyDoubleArrayLike(aa.first); - double* src = aa.second; - double* last = aa.second + PyArray_Size(aa.first.ptr()); - double* dst = bb.second; - for (; src != last; ++src, ++dst) - { - *dst = sftb.lookup(smbl, *src); - } - return bb.first; -} - - -} // namespace nswrap_ScatteringFactorTable - -// Wrapper definition -------------------------------------------------------- - -void wrap_ScatteringFactorTable() -{ - namespace bp = boost::python; - using boost::noncopyable; - using namespace nswrap_ScatteringFactorTable; - typedef ScatteringFactorTableOwner SFTOwner; - - class_ - sftb("ScatteringFactorTable", doc_ScatteringFactorTable); - wrap_registry_methods(sftb) - .def("radiationType", - &ScatteringFactorTable::radiationType, - return_value_policy(), - doc_ScatteringFactorTable_radiationType) - .def("lookup", - lookupnparray, - (bp::arg("smbl"), bp::arg("qarray"))) - .def("lookup", - &ScatteringFactorTable::lookup, - (bp::arg("smbl"), bp::arg("q")=0.0), - doc_ScatteringFactorTable_lookup) - .def("_standardLookup", - &ScatteringFactorTable::standardLookup, - (bp::arg("smbl"), bp::arg("q")), - doc_ScatteringFactorTable__standardLookup) - - .def("setCustomAs", (void (ScatteringFactorTable::*) - (const std::string&, const std::string&)) - &ScatteringFactorTable::setCustomAs, - (bp::arg("smbl"), bp::arg("src")), - doc_ScatteringFactorTable_setCustomAs2) - .def("setCustomAs", (void (ScatteringFactorTable::*) - (const std::string&, const std::string&, double, double)) - &ScatteringFactorTable::setCustomAs, - (bp::arg("smbl"), bp::arg("src"), - bp::arg("sf"), bp::arg("q")=0.0), - doc_ScatteringFactorTable_setCustomAs4) - - .def("resetCustom", &ScatteringFactorTable::resetCustom, - bp::arg("smbl"), doc_ScatteringFactorTable_resetCustom) - .def("resetAll", &ScatteringFactorTable::resetAll, - doc_ScatteringFactorTable_resetAll) - .def("getCustomSymbols", getCustomSymbols_asset, - doc_ScatteringFactorTable_getCustomSymbols) - .def("ticker", - &ScatteringFactorTable::ticker, - &ScatteringFactorTableWrap::default_ticker, - return_internal_reference<>(), - doc_ScatteringFactorTable_ticker) - .def_pickle(SerializationPickleSuite()) - ; - - register_ptr_to_python(); - - class_ >( - "SFTXray", doc_SFTXray) - .def_pickle(SerializationPickleSuite()); - class_ >( - "SFTElectron", doc_SFTElectron) - .def_pickle(SerializationPickleSuite()); - class_ >( - "SFTNeutron", doc_SFTNeutron) - .def_pickle(SerializationPickleSuite()); - class_ >( - "SFTElectronNumber", doc_SFTElectronNumber) - .def_pickle(SerializationPickleSuite()); - - class_("ScatteringFactorTableOwner", - doc_ScatteringFactorTableOwner) - .add_property("scatteringfactortable", - getsftable, - setsftable, - doc_ScatteringFactorTableOwner_scatteringfactortable) - // deprecated: prefer assigning the `scatteringfactortable` property - .def("setScatteringFactorTableByType", - +[](SFTOwner& obj, const std::string& tp) - { - namespace bp = boost::python; - try - { - bp::object warnings = bp::import("warnings"); - bp::object builtins = bp::import("builtins"); - bp::object DeprecationWarning = builtins.attr("DeprecationWarning"); - warnings.attr("warn")( - std::string("setScatteringFactorTableByType is deprecated; " - "assign the 'scatteringfactortable' property directly, for example:\n" - "obj.scatteringfactortable = SFTNeutron()"), - DeprecationWarning, - 2); - } - catch (...) { /* don't let warnings break the binding */ } - obj.setScatteringFactorTableByType(tp); - }, - bp::arg("tp"), - doc_ScatteringFactorTableOwner_setScatteringFactorTableByType) - .def("getRadiationType", - &SFTOwner::getRadiationType, - return_value_policy(), - doc_ScatteringFactorTableOwner_getRadiationType) - ; -} - -} // namespace srrealmodule - -// Serialization ------------------------------------------------------------- - -BOOST_CLASS_EXPORT(srrealmodule::nswrap_ScatteringFactorTable::ScatteringFactorTableWrap) - -// End of file diff --git a/src/extensions/wrap_StructureAdapter.cpp b/src/extensions/wrap_StructureAdapter.cpp deleted file mode 100644 index 7a1a60c5..00000000 --- a/src/extensions/wrap_StructureAdapter.cpp +++ /dev/null @@ -1,583 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal by DANSE Diffraction group -* Simon J. L. Billinge -* (c) 2010 The Trustees of Columbia University -* in the City of New York. All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE_DANSE.txt for license information. -* -****************************************************************************** -* -* Bindings to the StructureAdapter class. So far the wrapper is intended -* only for accessing the C++ created StructureAdapter instances and there -* is no support for method overrides from Python. -* -*****************************************************************************/ - -#include -#include -#include -#include -#include - -#include "srreal_converters.hpp" -#include "srreal_pickling.hpp" - -#include -#include -#include -#include -#include - -namespace srrealmodule { - -// declarations -void sync_StructureDifference(boost::python::object obj); - -namespace nswrap_StructureAdapter { - -using namespace boost; -using namespace boost::python; -using namespace diffpy::srreal; - -// docstrings ---------------------------------------------------------------- - -const char* doc_StructureAdapter = "\ -An adaptor to structure representation compatible with PairQuantity.\n\ -This class provides a uniform interface to structure data that is\n\ -understood by all PairQuantity calculators.\n\ -"; - -const char* doc_StructureAdapter___init__fromstring = "\ -Construct StructureAdapter object from a string. This is used\n\ -internally by the pickle protocol and should not be called directly.\n\ -"; - -const char* doc_StructureAdapter_clone = "\ -Return a deep copy of this StructureAdapter instance.\n\ -\n\ -This method must be overloaded in a derived class.\n\ -"; - -const char* doc_StructureAdapter_createBondGenerator = "\ -Create a bond generator instance linked to this structure adapter\n\ -\n\ -Return a BaseBondGenerator object.\n\ -"; - -const char* doc_StructureAdapter_countSites = "\ -Return number of symmetry independent atom sites in the structure.\n\ -"; - -const char* doc_StructureAdapter_totalOccupancy = "\ -Return total atom occupancy in the structure accounting for symmetry\n\ -multiplicity and fractional occupancies.\n\ -"; - -const char* doc_StructureAdapter_numberDensity = "\ -Number density of atoms in periodic crystal structures.\n\ -Return zero for non-periodic structures.\n\ -"; - -const char* doc_StructureAdapter_siteAtomType = "\ -Element, isotope or ion symbol at the specified atom site.\n\ -\n\ -i -- zero-based atom site index.\n\ -\n\ -Return a string symbol.\n\ -"; - -const char* doc_StructureAdapter_siteCartesianPosition = "\ -Return absolute cartesian coordinates of the specified atom site.\n\ -\n\ -i -- zero-based atom site index.\n\ -\n\ -Return an array of 3 cartesian positions.\n\ -"; - -const char* doc_StructureAdapter_siteMultiplicity = "\ -Symmetry multiplicity of the specified atom site in the structure.\n\ -\n\ -i -- zero-based atom site index.\n\ -\n\ -Return integer multiplicity.\n\ -"; - -const char* doc_StructureAdapter_siteOccupancy = "\ -Fractional occupancy of the specified site in the structure.\n\ -\n\ -i -- zero-based atom site index.\n\ -\n\ -Return float.\n\ -"; - -const char* doc_StructureAdapter_siteAnisotropy = "\ -Flag for anisotropic displacement parameters at the specified site.\n\ -\n\ -i -- zero-based atom site index.\n\ -\n\ -Return boolean flag.\n\ -"; - -const char* doc_StructureAdapter_siteCartesianUij = "\ -Matrix of displacement parameters expressed in cartesian coordinates.\n\ -\n\ -i -- zero-based atom site index.\n\ -\n\ -Return a 3 by 3 array.\n\ -"; - -const char* doc_StructureAdapter__customPQConfig = "\ -Support for optional custom configuration of the PairQuantity object.\n\ -This method is called from the setStructure and eval methods of the owner\n\ -PairQuantity object.\n\ -\n\ -pqobj -- the owner PairQuantity object. The function should check for the\n\ - exact type of pqobj and apply configuration accordingly.\n\ -\n\ -No return value. This method can be overloaded in a derived class.\n\ -No action by default.\n\ -"; - -const char* doc_StructureAdapter_diff = "\ -Evaluate difference between this and other StructureAdapter.\n\ -\n\ -other -- another StructureAdapter instance to compare with self\n\ -\n\ -Return StructureDifference object sd, where sd.stru0 is self,\n\ -sd.stru1 other, sd.pop0 are indices of atom sites that are in self,\n\ -but not in the other and sd.add1 atom indices that are only in self.\n\ -This method can be overloaded in a derived class.\n\ -"; - -const char* doc_NoMetaStructureAdapter = "\ -StructureAdapter proxy which disables _customPQConfig method.\n\ -"; - -const char* doc_NoMetaStructureAdapter_init = "\ -Create proxy to StructureAdapter that disables _customPQConfig.\n\ -\n\ -adapter -- StructureAdapter object to be proxied. The new adapter\n\ - will avoid calling of adapter._customPQConfig method.\n\ -"; - -const char* doc_NoSymmetryStructureAdapter = "\ -StructureAdapter proxy which disables crystal and periodic symmetry.\n\ -"; - -const char* doc_NoSymmetryStructureAdapter_init = "\ -Create proxy to StructureAdapter that disables symmetry expansion.\n\ -\n\ -adapter -- StructureAdapter object to be proxied. Any iteration over\n\ - atom pairs from periodic or space-group symmetry will be\n\ - disabled in the proxy adapter.\n\ -"; - -const char* doc_nometa = "\ -Return a proxy to StructureAdapter with _customPQConfig method disabled.\n\ -This creates a thin wrapper over a source StructureAdapter object that\n\ -disables _customPQConfig.\n\ -\n\ -stru -- StructureAdapter object or an object convertible to StructureAdapter.\n\ -\n\ -Return a proxy StructureAdapter with disabled _customPQConfig.\n\ -"; - -const char* doc_nosymmetry = "\ -Return a proxy StructureAdapter with crystal symmetry disabled.\n\ -For crystals the new adapter generates bonds only within the asymmetric\n\ -unit ignoring any translational or other symmetries.\n\ -\n\ -stru -- StructureAdapter object or an object convertible to StructureAdapter.\n\ -\n\ -Return a proxy StructureAdapter with disabled symmetry expansion.\n\ -"; - -const char* doc__emptyStructureAdapter = "\ -Factory for an empty structure singleton.\n\ -\n\ -Return a singleton instance of empty StructureAdapter.\n\ -"; - -// Local Helpers - forward declarations -------------------------------------- - -namespace { - -void checkindex(const StructureAdapter& adpt, int i); - -} // namespace - -// wrappers ------------------------------------------------------------------ - -const std::string& siteAtomType_safe(const StructureAdapter& adpt, int i) -{ - checkindex(adpt, i); - return adpt.siteAtomType(i); -} - - -DECLARE_PYARRAY_METHOD_WRAPPER1(siteCartesianPosition, - siteCartesianPosition_asarray) - -python::object siteCartesianPosition_safe(const StructureAdapter& adpt, int i) -{ - checkindex(adpt, i); - return siteCartesianPosition_asarray(adpt, i); -} - - -int siteMultiplicity_safe(const StructureAdapter& adpt, int i) -{ - checkindex(adpt, i); - return adpt.siteMultiplicity(i); -} - - -double siteOccupancy_safe(const StructureAdapter& adpt, int i) -{ - checkindex(adpt, i); - return adpt.siteOccupancy(i); -} - - -bool siteAnisotropy_safe(const StructureAdapter& adpt, int i) -{ - checkindex(adpt, i); - return adpt.siteAnisotropy(i); -} - - -DECLARE_PYARRAY_METHOD_WRAPPER1(siteCartesianUij, - siteCartesianUij_asarray) - -python::object siteCartesianUij_safe(const StructureAdapter& adpt, int i) -{ - checkindex(adpt, i); - return siteCartesianUij_asarray(adpt, i); -} - -// Helper class necessary for wrapping a pure virtual methods - -class StructureAdapterWrap : - public StructureAdapter, - public wrapper_srreal -{ - public: - - StructureAdapterPtr clone() const - { - return this->get_pure_virtual_override("clone")(); - } - - - BaseBondGeneratorPtr createBondGenerator() const - { - return this->get_pure_virtual_override("createBondGenerator")(); - } - - - int countSites() const - { - return this->get_pure_virtual_override("countSites")(); - } - - - double totalOccupancy() const - { - override f = this->get_override("totalOccupancy"); - if (f) return f(); - return this->default_totalOccupancy(); - } - - double default_totalOccupancy() const - { - return this->StructureAdapter::totalOccupancy(); - } - - - double numberDensity() const - { - override f = this->get_override("numberDensity"); - if (f) return f(); - return this->default_numberDensity(); - } - - double default_numberDensity() const - { - return this->StructureAdapter::numberDensity(); - } - - - const std::string& siteAtomType(int idx) const - { - static std::string rv; - override f = this->get_override("siteAtomType"); - if (f) - { - python::object atp = f(idx); - rv = python::extract(atp); - return rv; - } - return this->default_siteAtomType(idx); - } - - const std::string& default_siteAtomType(int idx) const - { - return this->StructureAdapter::siteAtomType(idx); - } - - - const R3::Vector& siteCartesianPosition(int idx) const - { - static R3::Vector rv; - python::object pos = - this->get_pure_virtual_override("siteCartesianPosition")(idx); - for (int i = 0; i < R3::Ndim; ++i) - { - rv[i] = python::extract(pos[i]); - } - return rv; - } - - - int siteMultiplicity(int idx) const - { - override f = this->get_override("siteMultiplicity"); - if (f) return f(idx); - return this->default_siteMultiplicity(idx); - } - - int default_siteMultiplicity(int idx) const - { - return this->StructureAdapter::siteMultiplicity(idx); - } - - - double siteOccupancy(int idx) const - { - override f = this->get_override("siteOccupancy"); - if (f) return f(idx); - return this->default_siteOccupancy(idx); - } - - double default_siteOccupancy(int idx) const - { - return this->StructureAdapter::siteOccupancy(idx); - } - - - bool siteAnisotropy(int idx) const - { - return this->get_pure_virtual_override("siteAnisotropy")(idx); - } - - - const R3::Matrix& siteCartesianUij(int idx) const - { - static R3::Matrix rv; - python::object uij = - this->get_pure_virtual_override("siteCartesianUij")(idx); - for (int i = 0; i < R3::Ndim; ++i) - { - for (int j = 0; j < R3::Ndim; ++j) - { - rv(i, j) = python::extract(uij[i][j]); - } - } - return rv; - } - - - void customPQConfig(PairQuantity* pq) const - { - override f = this->get_override("_customPQConfig"); - if (f) f(ptr(pq)); - else this->default_customPQConfig(pq); - } - - void default_customPQConfig(PairQuantity* pq) const - { - this->StructureAdapter::customPQConfig(pq); - } - - - StructureDifference diff(StructureAdapterConstPtr other) const - { - override f = this->get_override("diff"); - if (f) - { - python::object sdobj = f(other); - sync_StructureDifference(sdobj); - StructureDifference& sd = - python::extract(sdobj); - return sd; - } - return this->default_diff(other); - } - - StructureDifference default_diff(StructureAdapterConstPtr other) const - { - return this->StructureAdapter::diff(other); - } - - private: - - // serialization - friend class boost::serialization::access; - template - void serialize(Archive& ar, const unsigned int version) - { - ar & boost::serialization::base_object(*this); - } - -}; // class StructureAdapterWrap - - -template -class StructureProxyPickleSuite : public boost::python::pickle_suite -{ - public: - - static boost::python::tuple getinitargs( - diffpy::srreal::StructureAdapterPtr adpt) - { - using namespace boost; - shared_ptr tadpt = dynamic_pointer_cast(adpt); - StructureAdapterPtr srcadpt = tadpt->getSourceStructure(); - python::tuple rv = python::make_tuple(srcadpt); - return rv; - } - -}; - -// Local Helpers ------------------------------------------------------------- - -namespace { - -void checkindex(const StructureAdapter& adpt, int i) -{ - // Leave it up to Python wrapped classes to handle possible index issues. - if (dynamic_cast(&adpt)) return; - // Prevent out-of-bounds crash from C++ objects. - if (0 <= i && i < adpt.countSites()) return; - PyErr_SetString(PyExc_IndexError, "Index out of range."); - throw_error_already_set(); -} - -} // namespace - - -} // namespace nswrap_StructureAdapter - -// Wrapper definition -------------------------------------------------------- - -void wrap_StructureAdapter() -{ - using namespace nswrap_StructureAdapter; - - class_( - "StructureAdapter", doc_StructureAdapter) - .def("__init__", StructureAdapter_constructor(), - doc_StructureAdapter___init__fromstring) - .def("clone", - &StructureAdapter::clone, - doc_StructureAdapter_clone) - .def("createBondGenerator", - &StructureAdapter::createBondGenerator, - doc_StructureAdapter_createBondGenerator) - .def("countSites", &StructureAdapter::countSites, - doc_StructureAdapter_countSites) - .def("totalOccupancy", - &StructureAdapter::totalOccupancy, - &StructureAdapterWrap::default_totalOccupancy, - doc_StructureAdapter_totalOccupancy) - .def("numberDensity", &StructureAdapter::numberDensity, - &StructureAdapterWrap::default_numberDensity, - doc_StructureAdapter_numberDensity) - .def("siteAtomType", - siteAtomType_safe, - return_value_policy(), - doc_StructureAdapter_siteAtomType) - .def("siteAtomType", - &StructureAdapterWrap::default_siteAtomType, - return_value_policy()) - .def("siteCartesianPosition", - siteCartesianPosition_safe, - doc_StructureAdapter_siteCartesianPosition) - .def("siteMultiplicity", - siteMultiplicity_safe, - doc_StructureAdapter_siteMultiplicity) - .def("siteMultiplicity", - &StructureAdapterWrap::default_siteMultiplicity) - .def("siteOccupancy", - siteOccupancy_safe, - doc_StructureAdapter_siteOccupancy) - .def("siteOccupancy", - &StructureAdapterWrap::default_siteOccupancy) - .def("siteAnisotropy", - siteAnisotropy_safe, - doc_StructureAdapter_siteAnisotropy) - .def("siteCartesianUij", - siteCartesianUij_safe, - doc_StructureAdapter_siteCartesianUij) - .def("_customPQConfig", - &StructureAdapter::customPQConfig, - &StructureAdapterWrap::default_customPQConfig, - python::arg("pqobj"), - doc_StructureAdapter__customPQConfig) - .def("diff", - &StructureAdapter::diff, - &StructureAdapterWrap::default_diff, - python::arg("other"), - doc_StructureAdapter_diff) - .def_pickle(StructureAdapterPickleSuite()) - ; - - register_ptr_to_python(); - implicitly_convertible(); - - typedef boost::shared_ptr - NoMetaStructureAdapterPtr; - class_, NoMetaStructureAdapterPtr>( - "NoMetaStructureAdapter", doc_NoMetaStructureAdapter) - .def(init(python::arg("adapter"), - doc_NoMetaStructureAdapter_init)) - .def_pickle(StructureProxyPickleSuite()) - ; - - typedef boost::shared_ptr - NoSymmetryStructureAdapterPtr; - class_, NoSymmetryStructureAdapterPtr>( - "NoSymmetryStructureAdapter", doc_NoSymmetryStructureAdapter) - .def(init(python::arg("adapter"), - doc_NoSymmetryStructureAdapter_init)) - .def_pickle(StructureProxyPickleSuite()) - ; - - def("nometa", nometa, doc_nometa); - def("nosymmetry", nosymmetry, doc_nosymmetry); - def("_emptyStructureAdapter", emptyStructureAdapter, - doc__emptyStructureAdapter); -} - -// Export shared docstrings - -const char* doc_StructureAdapter___init__fromstring = - nswrap_StructureAdapter::doc_StructureAdapter___init__fromstring; -const char* doc_StructureAdapter__customPQConfig = - nswrap_StructureAdapter::doc_StructureAdapter__customPQConfig; -const char* doc_StructureAdapter_diff = - nswrap_StructureAdapter::doc_StructureAdapter_diff; - -} // namespace srrealmodule - -using srrealmodule::nswrap_StructureAdapter::StructureAdapterWrap; -BOOST_CLASS_EXPORT(StructureAdapterWrap) - -// End of file diff --git a/src/extensions/wrap_StructureDifference.cpp b/src/extensions/wrap_StructureDifference.cpp deleted file mode 100644 index 0515cb6e..00000000 --- a/src/extensions/wrap_StructureDifference.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2014 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Wrap StructureDifference class for expressing differences between two -* StructureAdapter objects. -* -*****************************************************************************/ - -#include -#include - -#include - -#include -#include - -#include "srreal_converters.hpp" - -namespace srrealmodule { - -// declarations -void sync_StructureDifference(boost::python::object obj); - -namespace nswrap_StructureDifference { - -using namespace boost; -using namespace diffpy::srreal; -using boost::python::slice; - -// docstrings ---------------------------------------------------------------- - -const char* doc_StructureDifference = "\ -Class for expressing difference between two StructureAdapter objects.\n\ -\n\ -Attributes:\n\ -\n\ -stru0 -- old StructureAdapter instance\n\ -stru1 -- new StructureAdapter instance\n\ -pop0 -- list of indices of atoms that are only in stru0\n\ -add1 -- indices of atoms that are only in stru1\n\ -"; - -const char* doc_StructureDifference_init_copy = "\ -Create a copy of an existing StructureDifference object sd.\n\ -"; - -const char* doc_StructureDifference_init_structures = "\ -Create StructureDifference for comparing stru0 (old) and stru1 (new).\n\ -"; - -const char* doc_StructureDifference_diffmethod = "\ -Read-only string type of C++ difference algorithm that was used to compare\n\ -the structures. Possible values are ('NONE', 'SIDEBYSIDE', 'SORTED').\n\ -"; - -const char* doc_StructureDifference_allowsfastupdate = "\ -Return True if PairQuantity evaluated for stru0 can be fast-updated\n\ -for structure stru1. Fast update is done by removal of contributions\n\ -from stru0 atoms at indices pop0 and addition of add1 atoms in stru1.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -python::list get_pop0(python::object obj) -{ - python::object pypop0 = obj.attr("_pop0"); - if (pypop0.is_none()) - { - const StructureDifference& sd = - python::extract(obj); - pypop0 = obj.attr("_pop0") = convertToPythonList(sd.pop0); - } - return python::extract(pypop0); -} - - -void set_pop0(python::object obj, python::object value) -{ - StructureDifference& sd = python::extract(obj); - sd.pop0 = extractintvector(value); - get_pop0(obj)[slice()] = convertToPythonList(sd.pop0); -} - - -python::list get_add1(python::object obj) -{ - python::object pyadd1 = obj.attr("_add1"); - if (pyadd1.is_none()) - { - const StructureDifference& sd = - python::extract(obj); - pyadd1 = obj.attr("_add1") = convertToPythonList(sd.add1); - } - return python::extract(pyadd1); -} - - -void set_add1(python::object obj, python::object value) -{ - StructureDifference& sd = python::extract(obj); - sd.add1 = extractintvector(value); - get_add1(obj)[slice()] = convertToPythonList(sd.add1); -} - - -std::string get_diffmethod(const StructureDifference& sd) -{ - switch (sd.diffmethod) - { - case StructureDifference::Method::NONE: - return "NONE"; - case StructureDifference::Method::SIDEBYSIDE: - return "SIDEBYSIDE"; - case StructureDifference::Method::SORTED: - return "SORTED"; - } - const char* emsg = "Unknown internal value of StructureDifference::Method."; - PyErr_SetString(PyExc_NotImplementedError, emsg); - boost::python::throw_error_already_set(); - abort(); -} - - -bool sd_allowsfastupdate(python::object obj) -{ - sync_StructureDifference(obj); - StructureDifference& sd = python::extract(obj); - return sd.allowsfastupdate(); -} - -} // namespace nswrap_StructureDifference - -// this is a helper function to be called for Python-overridden -// StructureAdapter::diff method - -void sync_StructureDifference(boost::python::object obj) -{ - using namespace boost::python; - using diffpy::srreal::StructureDifference; - StructureDifference& sd = extract(obj); - object pypop0 = obj.attr("_pop0"); - if (!pypop0.is_none()) sd.pop0 = extractintvector(pypop0); - object pyadd1 = obj.attr("_add1"); - if (!pyadd1.is_none()) sd.add1 = extractintvector(pyadd1); -} - -// Wrapper definitions ------------------------------------------------------- - -void wrap_StructureDifference() -{ - using namespace nswrap_StructureDifference; - using namespace boost::python; - namespace bp = boost::python; - - class_("StructureDifference", doc_StructureDifference) - .def(init(bp::arg("sd"), - doc_StructureDifference_init_copy)) - .def(init( - (bp::arg("stru0"), bp::arg("stru1")), - doc_StructureDifference_init_structures)) - .def_readwrite("stru0", &StructureDifference::stru0) - .def_readwrite("stru1", &StructureDifference::stru1) - .add_property("pop0", get_pop0, set_pop0) - .setattr("_pop0", bp::object()) - .add_property("add1", get_add1, set_add1) - .setattr("_add1", bp::object()) - .add_property("diffmethod", - get_diffmethod, - doc_StructureDifference_diffmethod) - .def("allowsfastupdate", - sd_allowsfastupdate, - doc_StructureDifference_allowsfastupdate) - ; - -} - -} // namespace srrealmodule - -// End of file diff --git a/src/extensions/wrap_libdiffpy_version.cpp b/src/extensions/wrap_libdiffpy_version.cpp deleted file mode 100644 index 80347f3d..00000000 --- a/src/extensions/wrap_libdiffpy_version.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/***************************************************************************** -* -* diffpy.srreal Complex Modeling Initiative -* (c) 2014 Brookhaven Science Associates, -* Brookhaven National Laboratory. -* All rights reserved. -* -* File coded by: Pavol Juhas -* -* See AUTHORS.txt for a list of people who contributed. -* See LICENSE.txt for license information. -* -****************************************************************************** -* -* Access to the libdiffpy version data. -* -*****************************************************************************/ - -#include -#include -#include - -namespace srrealmodule { -namespace nswrap_libdiffpy_version { - -using namespace boost; - -// docstrings ---------------------------------------------------------------- - -const char* doc__get_libdiffpy_version_info_dict = "\ -Return dictionary with version data for the loaded libdiffpy library.\n\ -"; - -// wrappers ------------------------------------------------------------------ - -python::dict get_libdiffpy_version_info_dict() -{ - python::dict rv; - // Obtain version data from runtime values. - rv["version"] = libdiffpy_version_info::version; - rv["version_str"] = libdiffpy_version_info::version_str; - rv["major"] = libdiffpy_version_info::major; - rv["minor"] = libdiffpy_version_info::minor; - rv["micro"] = libdiffpy_version_info::micro; - rv["date"] = libdiffpy_version_info::date; - rv["git_commit"] = libdiffpy_version_info::git_sha; - rv["patch"] = libdiffpy_version_info::patch; - return rv; -} - -} // namespace nswrap_libdiffpy_version - -// Wrapper definition -------------------------------------------------------- - -void wrap_libdiffpy_version() -{ - using namespace nswrap_libdiffpy_version; - using boost::python::def; - - def("_get_libdiffpy_version_info_dict", - get_libdiffpy_version_info_dict, - doc__get_libdiffpy_version_info_dict); - -} - -} // namespace srrealmodule - -// End of file diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index 3e0ed938..00000000 --- a/tests/conftest.py +++ /dev/null @@ -1,77 +0,0 @@ -import json -import logging -from pathlib import Path - -import pytest - -from diffpy.srreal.structureconverters import convertObjCrystCrystal - - -@pytest.fixture -def user_filesystem(tmp_path): - base_dir = Path(tmp_path) - home_dir = base_dir / "home_dir" - home_dir.mkdir(parents=True, exist_ok=True) - cwd_dir = base_dir / "cwd_dir" - cwd_dir.mkdir(parents=True, exist_ok=True) - - home_config_data = {"username": "home_username", "email": "home@email.com"} - with open(home_dir / "diffpyconfig.json", "w") as f: - json.dump(home_config_data, f) - - yield tmp_path - - -# Resolve availability of optional packages. - -# pyobjcryst - - -@pytest.fixture(scope="session") -def _msg_nopyobjcryst(): - return "No module named 'pyobjcryst'" - - -@pytest.fixture(scope="session") -def has_pyobjcryst(): - try: - import pyobjcryst.crystal - - convertObjCrystCrystal(pyobjcryst.crystal.Crystal()) - has_pyobjcryst = True - except ImportError: - has_pyobjcryst = False - logging.warning("Cannot import pyobjcryst, pyobjcryst tests skipped.") - print("Cannot import pyobjcryst, pyobjcryst tests skipped.") - except TypeError: - has_pyobjcryst = False - logging.warning("Compiled without ObjCryst, pyobjcryst tests skipped.") - print("Compiled without ObjCryst, pyobjcryst tests skipped.") - - return has_pyobjcryst - - -# periodictable - - -@pytest.fixture(scope="session") -def _msg_noperiodictable(): - return "No module named 'periodictable'" - - -@pytest.fixture(scope="session") -def has_periodictable(): - try: - import periodictable - - has_periodictable = True - - # silence the pyflakes syntax checker - del periodictable - except ImportError: - has_periodictable = False - logging.warning( - "Cannot import periodictable, periodictable tests skipped." - ) - - return has_periodictable diff --git a/tests/test_atomradiitable.py b/tests/test_atomradiitable.py deleted file mode 100644 index c69b6ed3..00000000 --- a/tests/test_atomradiitable.py +++ /dev/null @@ -1,207 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for the AtomRadiiTable class.""" - - -import pickle -import unittest - -import pytest - -from diffpy.srreal.atomradiitable import ( - AtomRadiiTable, - ConstantRadiiTable, - CovalentRadiiTable, -) - -# ---------------------------------------------------------------------------- - - -class TestAtomRadiiTable(unittest.TestCase): - def setUp(self): - self.rtb = AtomRadiiTable() - self.ctb = ConstantRadiiTable() - return - - def tearDown(self): - return - - def test_pickling(self): - """Check pickling and unpickling of AtomRadiiTable.""" - ctb1 = pickle.loads(pickle.dumps(self.ctb)) - self.assertTrue(type(ctb1) is ConstantRadiiTable) - self.assertEqual({}, ctb1.getAllCustom()) - self.ctb.setCustom("Na", 1.3) - self.ctb.foobar = "foo" - self.ctb.setDefault(3.7) - ctb2 = pickle.loads(pickle.dumps(self.ctb)) - self.assertEqual({"Na": 1.3}, ctb2.getAllCustom()) - self.assertFalse(hasattr(ctb2, "foobar")) - self.assertEqual(3.7, ctb2.getDefault()) - return - - def test__standardLookup(self): - """Check AtomRadiiTable._standardLookup()""" - self.assertRaises(RuntimeError, self.rtb._standardLookup, "anything") - self.assertEqual(0.0, self.ctb._standardLookup("anything")) - self.ctb.setDefault(7.3) - self.assertEqual(7.3, self.ctb._standardLookup("anything")) - return - - def test_fromString(self): - """Check AtomRadiiTable.fromString()""" - self.rtb.fromString("H:0.33, B:0.42") - self.assertEqual({"H": 0.33, "B": 0.42}, self.rtb.getAllCustom()) - self.assertRaises(ValueError, self.rtb.fromString, "C:2.3, U:asdf") - self.assertEqual({"H": 0.33, "B": 0.42}, self.rtb.getAllCustom()) - self.rtb.fromString("C:2.3,,,") - self.assertEqual(3, len(self.rtb.getAllCustom())) - self.assertEqual(2.3, self.rtb.lookup("C")) - self.rtb.fromString("H:3.3") - self.assertEqual(3, len(self.rtb.getAllCustom())) - self.assertEqual(3.3, self.rtb.lookup("H")) - return - - def test_getAllCustom(self): - """Check AtomRadiiTable.getAllCustom()""" - self.assertEqual({}, self.rtb.getAllCustom()) - return - - def test_lookup(self): - """Check AtomRadiiTable.lookup()""" - self.assertRaises(RuntimeError, self.rtb.lookup, "C") - self.assertEqual(0.0, self.ctb.lookup("C")) - self.rtb.setCustom("C", 1.23) - self.assertEqual(1.23, self.rtb.lookup("C")) - return - - def test_resetCustom(self): - """Check AtomRadiiTable.resetCustom()""" - self.rtb.setCustom("C", 1.23) - self.assertTrue(self.rtb.getAllCustom()) - self.rtb.resetAll() - self.assertFalse(self.rtb.getAllCustom()) - return - - def test_setCustom(self): - """Check AtomRadiiTable.setCustom()""" - self.rtb.setCustom("C", 1.23) - self.assertEqual(1.23, self.rtb.lookup("C")) - self.rtb.setCustom("C", 3.3) - self.assertEqual(3.3, self.rtb.lookup("C")) - return - - def test_toString(self): - """Check AtomRadiiTable.toString()""" - rtb = self.rtb - self.assertEqual("", rtb.toString()) - self.assertEqual("", rtb.toString("; ")) - rtb.fromString("C : 1.5, B:2.0") - self.assertEqual("B:2,C:1.5", rtb.toString()) - self.assertEqual("B:2; C:1.5", rtb.toString("; ")) - return - - -# End of class TestAtomRadiiTable - -# ---------------------------------------------------------------------------- - - -class TestCovalentRadiiTable(unittest.TestCase): - - @pytest.fixture(autouse=True) - def _check_periodictable(self, has_periodictable, _msg_noperiodictable): - if not has_periodictable: - pytest.skip(_msg_noperiodictable) - - def setUp(self): - self.rtb = CovalentRadiiTable() - return - - def tearDown(self): - return - - def test_pickling(self): - """Check pickling and unpickling of CovalentRadiiTable.""" - rtb1 = pickle.loads(pickle.dumps(self.rtb)) - self.assertTrue(type(rtb1) is CovalentRadiiTable) - self.assertEqual({}, rtb1.getAllCustom()) - self.rtb.setCustom("Na", 1.3) - self.rtb.foobar = "foo" - rtb2 = pickle.loads(pickle.dumps(self.rtb)) - self.assertEqual({"Na": 1.3}, rtb2.getAllCustom()) - self.assertEqual("foo", rtb2.foobar) - return - - def test__standardLookup(self): - """Check CovalentRadiiTable._standardLookup()""" - self.assertEqual(1.22, self.rtb._standardLookup("Ga")) - return - - def test_create(self): - """Check CovalentRadiiTable.create()""" - self.rtb.setCustom("Na", 1.3) - rtb2 = self.rtb.create() - self.assertTrue(isinstance(rtb2, CovalentRadiiTable)) - self.assertEqual(1, len(self.rtb.getAllCustom())) - self.assertEqual(0, len(rtb2.getAllCustom())) - return - - def test_clone(self): - """Check CovalentRadiiTable.clone()""" - self.rtb.setCustom("Na", 1.3) - rtb2 = self.rtb.clone() - self.assertTrue(isinstance(rtb2, CovalentRadiiTable)) - self.assertEqual(1, len(rtb2.getAllCustom())) - self.assertEqual(1.3, rtb2.lookup("Na")) - return - - def test_fromString(self): - """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()""" - self.assertEqual({}, self.rtb.getAllCustom()) - return - - def test_lookup(self): - """Check CovalentRadiiTable.lookup()""" - self.assertEqual(1.22, self.rtb.lookup("Ga")) - self.rtb.fromString("Ga:2.22") - self.assertEqual(2.22, self.rtb.lookup("Ga")) - return - - def test_resetCustom(self): - """Check CovalentRadiiTable.resetCustom()""" - self.rtb.fromString("B:2.33, Ga:2.22") - self.rtb.resetCustom("B") - self.rtb.resetCustom("nada") - self.assertEqual(1, len(self.rtb.getAllCustom())) - self.assertEqual(0.84, self.rtb.lookup("B")) - self.assertEqual(2.22, self.rtb.lookup("Ga")) - return - - def test_setCustom(self): - """Check CovalentRadiiTable.setCustom()""" - self.assertEqual(0.84, self.rtb.lookup("B")) - self.rtb.setCustom("B", 0.9) - self.assertEqual(0.9, self.rtb.lookup("B")) - return - - def test_toString(self): - """Check CovalentRadiiTable.toString()""" - self.assertEqual("", self.rtb.toString(";---")) - return - - -# End of class TestCovalentRadiiTable - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_attributes.py b/tests/test_attributes.py deleted file mode 100644 index 573ccf8d..00000000 --- a/tests/test_attributes.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for the wrapped diffpy::Attributes -""" - - -import gc -import unittest -import weakref - -from diffpy.srreal.attributes import Attributes -from diffpy.srreal.pairquantity import PairQuantity -from diffpy.srreal.pdfcalculator import PDFCalculator - - -############################################################################## -class TestAttributes(unittest.TestCase): - - def setUp(self): - return - - def tearDown(self): - return - - def test___setattr__(self): - """Check Attributes.__setattr__()""" - # normal attribute - a = Attributes() - a.x = 45 - self.assertTrue("x" in a.__dict__) - self.assertFalse("x" in a._namesOfDoubleAttributes()) - self.assertRaises(AttributeError, a._getDoubleAttr, "x") - self.assertRaises(AttributeError, a._setDoubleAttr, "x", 13) - del a.x - a._registerDoubleAttribute("x") - self.assertTrue("x" in a._namesOfDoubleAttributes()) - a.x = 27 - self.assertEqual(27, a._getDoubleAttr("x")) - return - - def test___getattr__(self): - """Check Attributes.__getattr__()""" - a = Attributes() - self.assertRaises(AttributeError, getattr, a, "invalid") - a.x = 11 - self.assertEqual(11, a.x) - pdfc = PDFCalculator() - pdfc._setDoubleAttr("rmax", 12.34) - self.assertEqual(12.34, pdfc.rmax) - return - - def test_garbage_collection(self): - """Check garbage collection for Python defined Attributes.""" - # check if attributes are garbage collected - pq = PairQuantity() - wpq = weakref.ref(pq) - self.assertFalse(wpq() is None) - pq._registerDoubleAttribute("foo") - pq.foo = 45 - self.assertEqual(45, pq._getDoubleAttr("foo")) - del pq - self.assertTrue(wpq() is None) - return - - def test__getDoubleAttr(self): - """Check Attributes._getDoubleAttr()""" - pdfc = PDFCalculator() - pdfc.foo = 11 - self.assertRaises(AttributeError, pdfc._getDoubleAttr, "foo") - pdfc._registerDoubleAttribute("foo") - self.assertEqual(11, pdfc._getDoubleAttr("foo")) - pdfc.rmax = 22 - self.assertEqual(22, pdfc._getDoubleAttr("rmax")) - setattr(pdfc, "rmax", 23) - self.assertEqual(23, pdfc._getDoubleAttr("rmax")) - self.assertRaises(Exception, setattr, pdfc, "rmax", "xxx") - return - - def test__hasDoubleAttr(self): - """Check Attributes._hasDoubleAttr()""" - a = Attributes() - a.foo = 45 - self.assertFalse(a._hasDoubleAttr("foo")) - a._registerDoubleAttribute("foo") - self.assertTrue(a._hasDoubleAttr("foo")) - return - - def test__namesOfDoubleAttributes(self): - """Check Attributes._namesOfDoubleAttributes()""" - a = Attributes() - self.assertEqual(0, len(a._namesOfDoubleAttributes())) - pq = PairQuantity() - self.assertNotEqual(0, len(pq._namesOfDoubleAttributes())) - self.assertFalse("bar" in pq._namesOfDoubleAttributes()) - pq._registerDoubleAttribute("bar") - self.assertTrue("bar" in pq._namesOfDoubleAttributes()) - return - - def test__namesOfWritableDoubleAttributes(self): - """Check Attributes._namesOfDoubleAttributes()""" - a = Attributes() - self.assertEqual(0, len(a._namesOfDoubleAttributes())) - a._registerDoubleAttribute("bar", lambda obj: 13) - self.assertEqual(13, a._getDoubleAttr("bar")) - self.assertEqual(13, a.bar) - self.assertEqual(1, len(a._namesOfDoubleAttributes())) - self.assertEqual(0, len(a._namesOfWritableDoubleAttributes())) - pdfc = PDFCalculator() - self.assertTrue("extendedrmin" in pdfc._namesOfDoubleAttributes()) - self.assertTrue("extendedrmax" in pdfc._namesOfDoubleAttributes()) - nwda = pdfc._namesOfWritableDoubleAttributes() - self.assertFalse("extendedrmin" in nwda) - self.assertFalse("extendedrmax" in nwda) - return - - def test__registerDoubleAttribute(self): - """Check Attributes._registerDoubleAttribute()""" - d = {"g_called": False, "s_called": False, "value": 0} - - def g(obj): - d["g_called"] = True - return d["value"] - - def s(obj, value): - d["s_called"] = True - d["value"] = value - return - - a = Attributes() - wa = weakref.ref(a) - a._registerDoubleAttribute("a1", g, s) - self.assertFalse("a1" in a.__dict__) - self.assertFalse(d["g_called"]) - self.assertFalse(d["s_called"]) - self.assertEqual(0, a.a1) - self.assertTrue(d["g_called"]) - self.assertFalse(d["s_called"]) - a.a1 = 47 - self.assertTrue(d["s_called"]) - self.assertEqual(47, d["value"]) - self.assertTrue(hasattr(a, "a1")) - a._registerDoubleAttribute("a1readonly", g) - self.assertEqual(47, a.a1readonly) - self.assertTrue(hasattr(a, "a1readonly")) - self.assertRaises(AttributeError, a._setDoubleAttr, "a1readonly", 7) - self.assertRaises(AttributeError, setattr, a, "a1readonly", 5) - self.assertEqual(47, a.a1readonly) - a.a1 = 9 - self.assertEqual(9, a.a1readonly) - self.assertFalse(wa() is None) - del a - gc.collect() - self.assertTrue(wa() is None) - return - - def test__setDoubleAttr(self): - """Check Attributes._setDoubleAttr()""" - pdfc = PDFCalculator() - pdfc._setDoubleAttr("scale", 1.23) - self.assertFalse("scale" in pdfc.__dict__) - self.assertEqual(1.23, pdfc.scale) - return - - -# End of class TestAttributes - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_bondcalculator.py b/tests/test_bondcalculator.py deleted file mode 100644 index 8dd39ad0..00000000 --- a/tests/test_bondcalculator.py +++ /dev/null @@ -1,362 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.bondcalculator.""" - - -import pickle -import unittest - -import numpy -import pytest -from testutils import ( - loadDiffPyStructure, - loadObjCrystCrystal, - pickle_with_attr, -) - -from diffpy.srreal.bondcalculator import BondCalculator - -# ---------------------------------------------------------------------------- - - -class TestBondCalculator(unittest.TestCase): - - def setUp(self): - self.bdc = BondCalculator() - if not hasattr(self, "rutile"): - type(self).rutile = loadDiffPyStructure("rutile.cif") - if not hasattr(self, "nickel"): - type(self).nickel = loadDiffPyStructure("Ni.stru") - if not hasattr(self, "niprim"): - type(self).niprim = loadDiffPyStructure("Ni_primitive.stru") - return - - def tearDown(self): - return - - def test___init__(self): - """Check BondCalculator.__init__()""" - self.assertEqual(0, self.bdc.rmin) - self.assertEqual(5, self.bdc.rmax) - self.assertEqual(0, len(self.bdc.distances)) - bdc1 = BondCalculator(rmin=2, rmax=7) - self.assertEqual(2, bdc1.rmin) - self.assertEqual(7, bdc1.rmax) - self.assertRaises(TypeError, BondCalculator, invalid=55) - return - - def test___call__(self): - """Check BondCalculator.__call__()""" - bdc = self.bdc - bdc.rmax = 0 - self.assertEqual(0, len(bdc(self.rutile))) - bdc.rmax = 2.0 - self.assertEqual(24, len(bdc(self.rutile))) - self.assertEqual(0, len(bdc(self.niprim))) - bdc.rmax = 2.5 - self.assertEqual(12, len(bdc(self.niprim))) - self.assertEqual(0, len(bdc(self.niprim, rmax=2))) - self.assertRaises(TypeError, bdc, self.niprim, rmax=5, invalid=7) - self.assertEqual(2, bdc.rmax) - return - - def test_pickling(self): - """Check pickling and unpickling of BondCalculator.""" - bdc = self.bdc - bdc.rmin = 0.1 - bdc.rmax = 12.3 - bdc.setPairMask(1, 2, False) - bdc(self.nickel) - spkl = pickle.dumps(bdc) - bdc1 = pickle.loads(spkl) - self.assertFalse(bdc is bdc1) - for a in bdc._namesOfDoubleAttributes(): - self.assertEqual(getattr(bdc, a), getattr(bdc1, a)) - self.assertFalse(bdc1.getPairMask(1, 2)) - self.assertTrue(bdc1.getPairMask(0, 0)) - self.assertTrue(numpy.array_equal(bdc.distances, bdc1.distances)) - self.assertRaises(RuntimeError, pickle_with_attr, bdc, foo="bar") - return - - def test_pickling_derived_structure(self): - """Check pickling of BondCalculator with - DerivedStructureAdapter.""" - from testutils import DerivedStructureAdapter - - bdc = self.bdc - stru0 = DerivedStructureAdapter() - bdc.setStructure(stru0) - self.assertEqual(1, stru0.cpqcount) - spkl = pickle.dumps(bdc) - bdc1 = pickle.loads(spkl) - self.assertTrue(stru0 is bdc.getStructure()) - stru1 = bdc1.getStructure() - self.assertTrue(type(stru1) is DerivedStructureAdapter) - self.assertFalse(stru1 is stru0) - self.assertEqual(1, stru1.cpqcount) - return - - def test_distances(self): - """Check BondCalculator.distances.""" - self.bdc.eval(self.nickel) - dst = self.bdc.distances - self.assertTrue(numpy.array_equal(dst, BondCalculator()(self.nickel))) - self.assertTrue(numpy.array_equal(dst, numpy.sort(dst))) - self.bdc.maskAllPairs(False) - for i in range(4): - self.bdc.setPairMask(0, i, True) - dst0a = self.bdc(self.nickel) - idx0a = self.bdc.sites0 == 0 - self.bdc.maskAllPairs(False) - for i in range(4): - self.bdc.setPairMask(3, i, True) - dst3a = self.bdc(self.nickel) - self.bdc.maskAllPairs(True) - dstp = self.bdc(self.niprim) - self.assertTrue(numpy.allclose(dst0a, dst3a)) - self.assertTrue(numpy.allclose(dst0a[idx0a], dstp)) - return - - def test_directions(self): - """Check BondCalculator.directions.""" - dst = self.bdc(self.rutile) - drs = self.bdc.directions - nms = numpy.sqrt(numpy.sum(numpy.power(drs, 2), axis=1)) - self.assertTrue(numpy.allclose(dst, nms)) - return - - def test_sites(self): - """Check BondCalculator.sites.""" - bdc = self.bdc - dst = bdc(self.rutile) - self.assertEqual(len(dst), len(bdc.sites0)) - self.assertEqual(len(dst), len(bdc.sites1)) - self.assertEqual(0, numpy.min(bdc.sites0)) - self.assertEqual(5, numpy.max(bdc.sites0)) - self.assertEqual(0, numpy.min(bdc.sites1)) - self.assertEqual(5, numpy.max(bdc.sites1)) - dij = [ - (tuple(d) + (i0, i1)) - for d, i0, i1 in zip(bdc.directions, bdc.sites0, bdc.sites1) - ] - self.assertEqual(len(dij), len(set(dij))) - bdc.maskAllPairs(False) - bdc(self.rutile) - self.assertEqual(0, len(bdc.sites0)) - bdc.setPairMask(3, 3, True) - bdc(self.rutile) - self.assertTrue(len(bdc.sites0)) - self.assertEqual(set([3]), set(bdc.sites0).union(bdc.sites1)) - return - - def test_types(self): - """Check BondCalculator.types.""" - bdc = self.bdc - dst = bdc(self.rutile) - self.assertEqual(len(dst), len(bdc.types0)) - self.assertEqual(len(dst), len(bdc.types1)) - self.assertEqual(set(("Ti", "O")), set(bdc.types0)) - self.assertEqual(set(("Ti", "O")), set(bdc.types1)) - self.assertFalse((bdc.types0 == bdc.types1).all()) - bdc.maskAllPairs(False) - bdc(self.rutile) - self.assertEqual(0, bdc.types0.size) - self.assertEqual(0, bdc.types1.size) - bdc.setPairMask(3, 3, True) - bdc(self.rutile) - self.assertTrue(len(bdc.types0)) - self.assertEqual(set(["O"]), set(bdc.types0).union(set(bdc.types1))) - return - - def test_filterCone(self): - """Check BondCalculator.filterCone()""" - bdc = self.bdc - bdc.rmax = 2.5 - self.assertEqual(12, len(bdc(self.niprim))) - bdc.filterCone([0, 0, +1], 1) - self.assertEqual(1, len(bdc(self.niprim))) - bdc.filterCone([0, 0, -1], 1) - self.assertEqual(2, len(bdc(self.niprim))) - bdc.filterOff() - self.assertEqual(12, len(bdc(self.niprim))) - bdc.filterCone([0, 0.1, +1], 6) - bdc(self.niprim) - self.assertEqual(1, len(bdc(self.niprim))) - bdc.filterCone([0, 0, +1], 180) - self.assertEqual(12, len(bdc(self.niprim))) - return - - def test_filterOff(self): - """Check BondCalculator.filterOff()""" - bdc = self.bdc - bdc.rmax = 2.5 - bdc.filterCone([1, 2, 3], -1) - self.assertEqual(0, len(bdc(self.niprim).tolist())) - bdc.filterOff() - self.assertEqual(12, len(bdc(self.niprim))) - return - - def test_setPairMask(self): - """Check different setPairMask arguments.""" - bdc = self.bdc - dall = bdc(self.nickel) - bdc.maskAllPairs(False) - self.assertEqual(0, len(bdc(self.nickel))) - for i in range(4): - bdc.setPairMask(0, i, True) - dst0a = bdc(self.nickel) - bdc.setPairMask(range(4), 0, True, others=False) - dst0b = bdc(self.nickel) - self.assertTrue(numpy.array_equal(dst0a, dst0b)) - bdc.maskAllPairs(False) - bdc.setPairMask(0, -7, True) - dst0c = bdc(self.nickel) - self.assertTrue(numpy.array_equal(dst0a, dst0c)) - bdc.maskAllPairs(False) - bdc.setPairMask(0, "all", True) - dst0d = bdc(self.nickel) - self.assertTrue(numpy.array_equal(dst0a, dst0d)) - bdc.setPairMask("all", "all", False) - self.assertEqual(0, len(bdc(self.nickel))) - bdc.setPairMask("all", range(4), True) - dall2 = bdc(self.nickel) - self.assertTrue(numpy.array_equal(dall, dall2)) - self.assertRaises(ValueError, bdc.setPairMask, "fooo", 2, True) - self.assertRaises(ValueError, bdc.setPairMask, "aLL", 2, True) - return - - def test_setTypeMask(self): - """Check different setTypeMask arguments.""" - bdc = self.bdc - dall = bdc(self.rutile) - bdc.setTypeMask("all", "All", False) - self.assertTrue(numpy.array_equal(dall, bdc(self.rutile))) - bdc.setTypeMask("all", "ALL", False) - self.assertEqual(0, len(bdc(self.rutile))) - bdc.maskAllPairs(True) - bdc.setTypeMask("Ti", ["O"], True, others=False) - bdc() - tps = set(zip(bdc.types0, bdc.types1)) - self.assertEqual(2, len(tps)) - self.assertTrue(("Ti", "O") in tps) - self.assertTrue(("O", "Ti") in tps) - bdc.setTypeMask(["Ti"], self.rutile.element, 0, others=1) - bdc() - tps = set(zip(bdc.types0, bdc.types1)) - self.assertEqual(set([("O", "O")]), tps) - return - - -# End of class TestBondCalculator - -# ---------------------------------------------------------------------------- - - -class TestBondCalculatorObjCryst(unittest.TestCase): - - @pytest.fixture(autouse=True) - def _check_pyobjcryst(self, has_pyobjcryst, _msg_nopyobjcryst): - if not has_pyobjcryst: - pytest.skip(_msg_nopyobjcryst) - - def setUp(self): - self.bdc = BondCalculator() - if not hasattr(self, "rutile"): - type(self).rutile = loadObjCrystCrystal("rutile.cif") - if not hasattr(self, "nickel"): - type(self).nickel = loadObjCrystCrystal("Ni.cif") - return - - def tearDown(self): - return - - def test___call__(self): - """Check BondCalculator.__call__()""" - bdc = self.bdc - bdc.rmax = 0 - self.assertEqual(0, len(bdc(self.rutile).tolist())) - bdc.rmax = 2.0 - self.assertEqual(6 + 3, len(bdc(self.rutile))) - bdc.rmax = 2.5 - self.assertEqual(12, len(bdc(self.nickel))) - return - - def test_sites(self): - """Check BondCalculator.sites.""" - bdc = self.bdc - dst = bdc(self.rutile) - self.assertEqual(len(dst), len(bdc.sites0)) - self.assertEqual(len(dst), len(bdc.sites1)) - self.assertEqual(0, numpy.min(bdc.sites0)) - self.assertEqual(1, numpy.max(bdc.sites0)) - self.assertEqual(0, numpy.min(bdc.sites1)) - self.assertEqual(1, numpy.max(bdc.sites1)) - dij = [ - (tuple(d) + (i0, i1)) - for d, i0, i1 in zip(bdc.directions, bdc.sites0, bdc.sites1) - ] - self.assertEqual(len(dij), len(set(dij))) - bdc.maskAllPairs(False) - bdc(self.rutile) - self.assertEqual(0, len(bdc.sites0)) - bdc.setPairMask(1, 1, True) - bdc(self.rutile) - self.assertTrue(len(bdc.sites0)) - self.assertEqual(set([1]), set(bdc.sites0).union(bdc.sites1)) - return - - def test_types(self): - """Check BondCalculator.types.""" - bdc = self.bdc - dst = bdc(self.rutile) - self.assertEqual(len(dst), len(bdc.types0)) - self.assertEqual(len(dst), len(bdc.types1)) - self.assertEqual(set(("Ti", "O")), set(bdc.types0)) - self.assertEqual(set(("Ti", "O")), set(bdc.types1)) - self.assertNotEqual(bdc.types0.tolist(), bdc.types1.tolist()) - bdc.maskAllPairs(False) - bdc(self.rutile) - self.assertEqual(0, bdc.types0.size) - self.assertEqual(0, bdc.types1.size) - bdc.setPairMask(1, 1, True) - bdc(self.rutile) - self.assertTrue(len(bdc.types0)) - self.assertEqual(set(["O"]), set(bdc.types0).union(set(bdc.types1))) - return - - def test_filterCone(self): - """Check BondCalculator.filterCone()""" - bdc = self.bdc - bdc.rmax = 2.5 - bdc.filterCone([+0.5, +0.5, 0], 1) - self.assertEqual(1, len(bdc(self.nickel))) - bdc.filterCone([-0.5, -0.5, 0], 1) - self.assertEqual(2, len(bdc(self.nickel))) - bdc.filterOff() - self.assertEqual(12, len(bdc(self.nickel))) - bdc.filterCone([+0.5, +0.5, 0.05], 6) - bdc(self.nickel) - self.assertEqual(1, len(bdc(self.nickel))) - bdc.filterCone([+0.5, +0.5, 0], 180) - self.assertEqual(12, len(bdc(self.nickel))) - return - - def test_filterOff(self): - """Check BondCalculator.filterOff()""" - bdc = self.bdc - bdc.rmax = 2.5 - bdc.filterCone([1, 2, 3], -1) - self.assertEqual(0, len(bdc(self.nickel))) - bdc.filterOff() - self.assertEqual(12, len(bdc(self.nickel))) - return - - -# End of class TestBondCalculatorObjCryst - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_bvscalculator.py b/tests/test_bvscalculator.py deleted file mode 100644 index f15172f9..00000000 --- a/tests/test_bvscalculator.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.bvscalculator.""" - - -import pickle -import unittest - -from testutils import loadDiffPyStructure, pickle_with_attr - -from diffpy.srreal.bvscalculator import BVSCalculator - - -############################################################################## -class TestBVSCalculator(unittest.TestCase): - - def setUp(self): - self.bvc = BVSCalculator() - if not hasattr(self, "rutile"): - type(self).rutile = loadDiffPyStructure("rutile.cif") - # rutile.cif does not have charge data, we need to add them here - iondict = {"Ti": "Ti4+", "O": "O2-"} - for a in self.rutile: - a.element = iondict[a.element] - return - - def tearDown(self): - return - - def test___init__(self): - """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__()""" - vcalc = self.bvc(self.rutile) - self.assertEqual(len(self.rutile), len(vcalc)) - self.assertEqual(tuple(self.bvc.value), tuple(vcalc)) - self.assertTrue(vcalc[0] > 0) - self.assertTrue(vcalc[-1] < 0) - self.assertAlmostEqual(0.0, sum(vcalc), 12) - self.assertAlmostEqual(0.0, sum(self.bvc.valences), 12) - for vo, vc in zip(self.bvc.valences, vcalc): - self.assertTrue(abs((vo - vc) / vo) < 0.1) - return - - def test_bvdiff(self): - """Check BVSCalculator.bvdiff.""" - self.bvc(self.rutile) - self.assertEqual(6, len(self.bvc.bvdiff)) - # rutile is overbonded - for bvd in self.bvc.bvdiff: - self.assertTrue(bvd < 0) - return - - def test_bvmsdiff(self): - """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.""" - from math import sqrt - - self.assertEqual(0, self.bvc.bvrmsdiff) - self.bvc(self.rutile) - self.assertTrue(self.bvc.bvrmsdiff > 0) - self.assertAlmostEqual(sqrt(self.bvc.bvmsdiff), self.bvc.bvrmsdiff, 12) - bvrmsd0 = self.bvc.bvrmsdiff - # check mixed occupancy - rutilemix = self.rutile.copy() - for a in self.rutile: - rutilemix.addNewAtom(a) - for a in rutilemix: - a.occupancy = 0.5 - self.bvc(rutilemix) - self.assertEqual(12, len(self.bvc.value)) - self.assertAlmostEqual(bvrmsd0, self.bvc.bvrmsdiff, 12) - return - - def test_eval(self): - """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.""" - self.bvc(self.rutile) - self.assertEqual((4, 4, -2, -2, -2, -2), tuple(self.bvc.valences)) - return - - def test_value(self): - """Check BVSCalculator.value.""" - self.assertEqual(0, len(self.bvc.value)) - return - - def test_pickling(self): - """Check pickling and unpickling of BVSCalculator.""" - bvsc = BVSCalculator() - bvsc.rmin = 0.1 - bvsc.rmax = 12.3 - bvsc.valenceprecision = 0.3e-4 - spkl = pickle.dumps(bvsc) - bvsc1 = pickle.loads(spkl) - self.assertFalse(bvsc is bvsc1) - for a in bvsc._namesOfDoubleAttributes(): - self.assertEqual(getattr(bvsc, a), getattr(bvsc1, a)) - self.assertRaises(RuntimeError, pickle_with_attr, bvsc, foo="bar") - return - - def test_mask_pickling(self): - """Check if mask gets properly pickled and restored.""" - self.bvc.maskAllPairs(False) - self.bvc.setPairMask(0, 1, True) - self.assertTrue(False is self.bvc.getPairMask(0, 0)) - self.assertTrue(True is self.bvc.getPairMask(0, 1)) - bvc1 = pickle.loads(pickle.dumps(self.bvc)) - self.assertTrue(False is bvc1.getPairMask(0, 0)) - self.assertTrue(True is bvc1.getPairMask(0, 1)) - return - - def test_table_pickling(self): - """Check if bvparamtable gets correctly pickled and restored.""" - self.bvc.bvparamtable.setCustom("A", 1, "B", -2, 7, 8) - bvc1 = pickle.loads(pickle.dumps(self.bvc)) - bpab = bvc1.bvparamtable.lookup("A+", "B2-") - self.assertEqual("A", bpab.atom0) - self.assertEqual(1, bpab.valence0) - self.assertEqual("B", bpab.atom1) - self.assertEqual(-2, bpab.valence1) - self.assertEqual(7, bpab.Ro) - self.assertEqual(8, bpab.B) - return - - def test_pickling_derived_structure(self): - """Check pickling of BVSCalculator with - DerivedStructureAdapter.""" - from testutils import DerivedStructureAdapter - - bvc = self.bvc - stru0 = DerivedStructureAdapter() - bvc.setStructure(stru0) - self.assertEqual(1, stru0.cpqcount) - spkl = pickle.dumps(bvc) - bvc1 = pickle.loads(spkl) - self.assertTrue(stru0 is bvc.getStructure()) - stru1 = bvc1.getStructure() - self.assertTrue(type(stru1) is DerivedStructureAdapter) - self.assertFalse(stru1 is stru0) - self.assertEqual(1, stru1.cpqcount) - return - - def test_table_atom_valence(self): - """Check calculation with defined valences in bvparamtable.""" - bvc = self.bvc - barerutile = self.rutile.copy() - for a in barerutile: - a.element = a.element.rstrip("+-012345678") - self.assertEqual({"Ti": 2, "O": 4}, barerutile.composition) - self.assertFalse(any(bvc(barerutile))) - bptb = bvc.bvparamtable - bptb.setAtomValence("Ti", +4) - bptb.setAtomValence("O", -2) - vcalc = bvc(barerutile) - self.assertEqual(4, bptb.getAtomValence("Ti")) - self.assertEqual(-2, bptb.getAtomValence("O")) - self.assertEqual(set((+4, -2)), set(round(x) for x in vcalc)) - self.assertEqual(set((+4, -2)), set(bvc.valences)) - bptb.resetAtomValences() - self.assertFalse(any(bvc(barerutile))) - return - - -# End of class TestBVSCalculator - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_debyepdfcalculator.py b/tests/test_debyepdfcalculator.py deleted file mode 100644 index 7a41f66d..00000000 --- a/tests/test_debyepdfcalculator.py +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for pdfcalculator.py.""" - - -import pickle -import unittest -import warnings - -import numpy -from testutils import _maxNormDiff, loadDiffPyStructure, pickle_with_attr - -from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator -from diffpy.srreal.scatteringfactortable import SFTNeutron - - -############################################################################## -class TestDebyePDFCalculator(unittest.TestCase): - - bucky = None - tio2rutile = None - - def setUp(self): - self.dpdfc = DebyePDFCalculator() - if not TestDebyePDFCalculator.bucky: - TestDebyePDFCalculator.bucky = loadDiffPyStructure("C60bucky.stru") - if not TestDebyePDFCalculator.tio2rutile: - TestDebyePDFCalculator.tio2rutile = loadDiffPyStructure( - "TiO2_rutile-fit.stru" - ) - return - - # def tearDown(self): - # return - # - # def test___call__(self): - # """check DebyePDFCalculator.__call__() - # """ - # return - # - # def test___init__(self): - # """check DebyePDFCalculator.__init__() - # """ - # return - - def test___getattr__(self): - """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__()""" - 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()""" - gdba = self.dpdfc._getDoubleAttr - self.assertEqual(1.0, gdba("scale")) - self.assertEqual(0.0, gdba("qdamp")) - self.assertRaises(Exception, gdba, "notanattribute") - return - - def test__hasDoubleAttr(self): - """Check DebyePDFCalculator._hasDoubleAttr()""" - self.assertTrue(self.dpdfc._hasDoubleAttr("scale")) - self.assertFalse(self.dpdfc._hasDoubleAttr("notanattribute")) - return - - def test__namesOfDoubleAttributes(self): - """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()""" - gdba = self.dpdfc._getDoubleAttr - sdba = self.dpdfc._setDoubleAttr - self.assertEqual(0.0, gdba("rmin")) - sdba("rmin", 3.0) - self.assertEqual(3.0, gdba("rmin")) - return - - def test_PDF_C60bucky(self): - """Check DebyePDFCalculator.pdf for C60 Bucky ball.""" - qmax = self.dpdfc.qmax - r0, g0 = PDFCalculator(qmax=qmax)(self.bucky) - r1, g1 = self.dpdfc(self.bucky) - mxnd = _maxNormDiff(g0, g1) - self.assertTrue(mxnd < 0.0006) - return - - def test_partial_pdfs(self): - """Check calculation of partial PDFs.""" - dpdfc = self.dpdfc - dpdfc.qmin = 1.0 - rutile = self.tio2rutile - r0, g0 = dpdfc(rutile) - # Ti-Ti - dpdfc.maskAllPairs(False) - dpdfc.setTypeMask("Ti", "Ti", True) - r1, g1 = dpdfc(rutile) - self.assertTrue(numpy.array_equal(r0, r1)) - dpdfc.invertMask() - r1i, g1i = dpdfc(rutile) - self.assertTrue(numpy.array_equal(r0, r1i)) - self.assertTrue(numpy.allclose(g0, g1 + g1i)) - # Ti-O - dpdfc.maskAllPairs(False) - dpdfc.setTypeMask("all", "ALL", True) - dpdfc.setTypeMask("Ti", "Ti", False) - dpdfc.setTypeMask("O", "O", False) - r2, g2 = dpdfc(rutile) - self.assertTrue(numpy.array_equal(r0, r2)) - dpdfc.invertMask() - r2i, g2i = dpdfc(rutile) - self.assertTrue(numpy.allclose(g0, g2 + g2i)) - # Ti-O from type mask - dpdfc.maskAllPairs(True) - dpdfc.setTypeMask("Ti", "Ti", False) - dpdfc.setTypeMask("O", "O", False) - r2t, g2t = dpdfc(rutile) - self.assertTrue(numpy.array_equal(r0, r2t)) - self.assertTrue(numpy.array_equal(g2, g2t)) - dpdfc.invertMask() - r2ti, g2ti = dpdfc(rutile) - self.assertTrue(numpy.array_equal(g2i, g2ti)) - # O-O - dpdfc.maskAllPairs(False) - dpdfc.setTypeMask("O", "O", True) - r3, g3 = dpdfc(rutile) - dpdfc.invertMask() - r3i, g3i = dpdfc(rutile) - self.assertTrue(numpy.allclose(g0, g3 + g3i)) - # check the sum of all partials - self.assertTrue(numpy.allclose(g0, g1 + g2 + g3)) - return - - def test_pickling(self): - """Check pickling and unpickling of PDFCalculator.""" - # New syntax: assign an SFT instance to the property (should not warn) - dpdfc = self.dpdfc - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - dpdfc.scatteringfactortable = SFTNeutron() - self.assertFalse( - any(isinstance(x.message, DeprecationWarning) for x in w) - ) - - dpdfc.scatteringfactortable.setCustomAs("Na", "Na", 7) - spkl = pickle.dumps(dpdfc) - dpdfc1_new = pickle.loads(spkl) - self.assertEqual( - dpdfc.scatteringfactortable.type(), - dpdfc1_new.scatteringfactortable.type(), - ) - self.assertEqual(7.0, dpdfc1_new.scatteringfactortable.lookup("Na")) - - # Old syntax: call the deprecated method (should warn) - dpdfc = self.dpdfc - with self.assertWarns(DeprecationWarning): - dpdfc.setScatteringFactorTableByType("N") - dpdfc.scatteringfactortable.setCustomAs("Na", "Na", 7) - dpdfc.addEnvelope("sphericalshape") - dpdfc.debyeprecision = 0.001 - dpdfc.delta1 = 0.2 - dpdfc.delta2 = 0.3 - dpdfc.maxextension = 10.1 - dpdfc.qbroad = 0.01 - dpdfc.qdamp = 0.05 - dpdfc.qmax = 10 - dpdfc.qmin = 0.5 - dpdfc.rmax = 10.0 - dpdfc.rmin = 0.02 - dpdfc.rstep = 0.02 - dpdfc.scale = 1.1 - dpdfc.spdiameter = 13.3 - spkl = pickle.dumps(dpdfc) - dpdfc1 = pickle.loads(spkl) - self.assertFalse(dpdfc is dpdfc1) - sft = dpdfc.scatteringfactortable - sft1 = dpdfc1.scatteringfactortable - self.assertEqual(sft.type(), sft1.type()) - self.assertEqual(7.0, sft1.lookup("Na")) - for a in dpdfc._namesOfDoubleAttributes(): - self.assertEqual(getattr(dpdfc, a), getattr(dpdfc1, a)) - self.assertEqual(13.3, dpdfc1.getEnvelope("sphericalshape").spdiameter) - self.assertEqual( - dpdfc._namesOfDoubleAttributes(), dpdfc1._namesOfDoubleAttributes() - ) - self.assertEqual(dpdfc.usedenvelopetypes, dpdfc1.usedenvelopetypes) - self.assertRaises(RuntimeError, pickle_with_attr, dpdfc, foo="bar") - return - - def test_mask_pickling(self): - """Check if mask gets properly pickled and restored.""" - self.dpdfc.maskAllPairs(False) - self.dpdfc.setPairMask(0, 1, True) - self.dpdfc.setTypeMask("Na", "Cl", True) - self.assertTrue(False is self.dpdfc.getPairMask(0, 0)) - self.assertTrue(True is self.dpdfc.getPairMask(0, 1)) - self.assertTrue(True is self.dpdfc.getTypeMask("Cl", "Na")) - dpdfc1 = pickle.loads(pickle.dumps(self.dpdfc)) - self.assertTrue(False is dpdfc1.getPairMask(0, 0)) - self.assertTrue(True is dpdfc1.getPairMask(0, 1)) - self.assertTrue(True is self.dpdfc.getTypeMask("Cl", "Na")) - return - - def test_pickling_derived_structure(self): - """Check pickling of DebyePDFCalculator with - DerivedStructureAdapter.""" - from testutils import DerivedStructureAdapter - - dpdfc = self.dpdfc - stru0 = DerivedStructureAdapter() - dpdfc.setStructure(stru0) - self.assertEqual(1, stru0.cpqcount) - spkl = pickle.dumps(dpdfc) - dpdfc1 = pickle.loads(spkl) - self.assertTrue(stru0 is dpdfc.getStructure()) - stru1 = dpdfc1.getStructure() - self.assertTrue(type(stru1) is DerivedStructureAdapter) - self.assertFalse(stru1 is stru0) - self.assertEqual(1, stru1.cpqcount) - return - - -# def test_getPeakWidthModel(self): -# """check DebyePDFCalculator.getPeakWidthModel() -# """ -# return -# -# def test_qgrid(self): -# """check DebyePDFCalculator.qgrid -# """ -# return -# -# def test_getRadiationType(self): -# """check DebyePDFCalculator.getRadiationType() -# """ -# return -# -# def test_rgrid(self): -# """check DebyePDFCalculator.rgrid -# """ -# return -# -# def test_scatteringfactortable(self): -# """check DebyePDFCalculator.scatteringfactortable property -# """ -# return -# -# def test_isOptimumQstep(self): -# """check DebyePDFCalculator.isOptimumQstep() -# """ -# return -# -# def test_setOptimumQstep(self): -# """check DebyePDFCalculator.setOptimumQstep() -# """ -# return -# -# def test_peakwidthmodel(self): -# """check DebyePDFCalculator.setPeakWidthModel() -# """ -# return -# -# def test_value(self): -# """check DebyePDFCalculator.value -# """ -# return - -# End of class TestDebyePDFCalculator - - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_overlapcalculator.py b/tests/test_overlapcalculator.py deleted file mode 100644 index 2010130a..00000000 --- a/tests/test_overlapcalculator.py +++ /dev/null @@ -1,482 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.overlapcalculator.""" - - -import copy -import pickle -import unittest - -import numpy -import pytest -from testutils import ( - loadDiffPyStructure, - loadObjCrystCrystal, - pickle_with_attr, -) - -from diffpy.srreal.atomradiitable import CovalentRadiiTable -from diffpy.srreal.overlapcalculator import OverlapCalculator - -# ---------------------------------------------------------------------------- - - -class TestOverlapCalculator(unittest.TestCase): - - pool = None - - def setUp(self): - self.olc = OverlapCalculator() - if not hasattr(self, "rutile"): - type(self).rutile = loadDiffPyStructure("rutile.cif") - if not hasattr(self, "nickel"): - type(self).nickel = loadDiffPyStructure("Ni.stru") - if not hasattr(self, "niprim"): - type(self).niprim = loadDiffPyStructure("Ni_primitive.stru") - return - - def tearDown(self): - if self.pool: - self.pool.terminate() - self.pool.join() - self.pool = None - return - - def test___init__(self): - """Check OverlapCalculator.__init__()""" - self.assertEqual(0, self.olc.rmin) - self.assertTrue(100 <= self.olc.rmax) - self.assertEqual(0, self.olc.rmaxused) - self.assertEqual(0.0, self.olc.totalsquareoverlap) - return - - def test___call__(self): - """Check OverlapCalculator.__call__()""" - olc = self.olc - sso1 = olc(self.rutile) - self.assertEqual(6, len(sso1)) - self.assertFalse(numpy.any(sso1)) - self.assertEqual(0.0, olc.rmaxused) - rtb = olc.atomradiitable - rtb.fromString("Ti:1.6, O:0.66") - sso2 = olc(self.rutile) - self.assertEqual(6, len(sso2[sso2 > 0])) - self.assertEqual(3.2, olc.rmaxused) - sso3 = olc(self.rutile, rmax=1.93) - self.assertEqual(0.0, sum(sso3)) - self.assertEqual(1.93, olc.rmaxused) - return - - def test___getstate__(self): - """Check OverlapCalculator.__getstate__()""" - olc = self.olc - self.assertIs(None, olc.__getstate__()[-1]) - tb = CovalentRadiiTable() - olc.atomradiitable = tb - self.assertIs(tb, olc.__getstate__()[-1]) - olc.atomradiitable = "constant" - self.assertIs(None, olc.__getstate__()[-1]) - return - - def test_pickling(self): - """Check pickling and unpickling of OverlapCalculator.""" - olc = self.olc - olc.rmin = 0.1 - olc.rmax = 12.3 - olc.setPairMask(1, 2, False) - spkl = pickle.dumps(olc) - olc1 = pickle.loads(spkl) - self.assertFalse(olc is olc1) - for a in olc._namesOfDoubleAttributes(): - self.assertEqual(getattr(olc, a), getattr(olc1, a)) - self.assertFalse(olc1.getPairMask(1, 2)) - self.assertTrue(olc1.getPairMask(0, 0)) - self.assertTrue( - numpy.array_equal(olc.sitesquareoverlaps, olc1.sitesquareoverlaps) - ) - self.assertRaises(RuntimeError, pickle_with_attr, olc, foo="bar") - return - - def test_pickling_artb(self): - """Check pickling and unpickling of - OverlapCalculator.atomradiitable.""" - olc = self.olc - olc.atomradiitable.setDefault(1.3) - spkl = pickle.dumps(olc) - olc1 = pickle.loads(spkl) - self.assertFalse(olc is olc1) - self.assertEqual(1.3, olc1.atomradiitable.getDefault()) - olc.atomradiitable = CovalentRadiiTable() - olc.atomradiitable.setCustom("Na", 2) - olc.atomradiitable.foo = 123 - spkl2 = pickle.dumps(olc) - olc2 = pickle.loads(spkl2) - self.assertEqual(2, olc2.atomradiitable.lookup("Na")) - self.assertEqual(1, len(olc2.atomradiitable.getAllCustom())) - self.assertEqual(123, olc2.atomradiitable.foo) - return - - def test_pickling_derived_structure(self): - """Check pickling of OverlapCalculator with - DerivedStructureAdapter.""" - from testutils import DerivedStructureAdapter - - olc = self.olc - stru0 = DerivedStructureAdapter() - olc.setStructure(stru0) - self.assertEqual(1, stru0.cpqcount) - spkl = pickle.dumps(olc) - olc1 = pickle.loads(spkl) - self.assertTrue(stru0 is olc.getStructure()) - stru1 = olc1.getStructure() - self.assertTrue(type(stru1) is DerivedStructureAdapter) - self.assertFalse(stru1 is stru0) - self.assertEqual(1, stru1.cpqcount) - return - - def test_parallel(self): - """Check parallel run of OverlapCalculator.""" - import multiprocessing - - from diffpy.srreal.parallel import createParallelCalculator - - ncpu = 4 - self.pool = multiprocessing.Pool(processes=ncpu) - olc = self.olc - polc = createParallelCalculator( - OverlapCalculator(), ncpu, self.pool.imap_unordered - ) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - polc.atomradiitable = olc.atomradiitable - self.assertTrue(numpy.array_equal(olc(self.rutile), polc(self.rutile))) - self.assertTrue(olc.totalsquareoverlap > 0.0) - self.assertEqual(olc.totalsquareoverlap, polc.totalsquareoverlap) - self.assertEqual( - sorted(zip(olc.sites0, olc.sites1)), - sorted(zip(polc.sites0, polc.sites1)), - ) - olc.atomradiitable.resetAll() - self.assertEqual(0.0, sum(olc(self.rutile))) - self.assertEqual(0.0, sum(polc(self.rutile))) - return - - def test_distances(self): - """Check OverlapCalculator.distances.""" - olc = self.olc - olc(self.nickel) - self.assertEqual(0, len(olc.distances)) - olc.atomradiitable.setCustom("Ni", 1.25) - olc(self.nickel) - self.assertEqual(4 * 12, len(olc.distances)) - dmin = numpy.sqrt(0.5) * self.nickel.lattice.a - self.assertAlmostEqual(dmin, numpy.min(olc.distances)) - self.assertAlmostEqual(dmin, numpy.max(olc.distances)) - olc.maskAllPairs(False) - olc.setPairMask(0, "all", True) - olc(self.nickel) - self.assertEqual(12 + 12, len(olc.distances)) - return - - def test_directions(self): - """Check OverlapCalculator.directions.""" - olc = self.olc - olc(self.nickel) - self.assertEqual([], olc.directions.tolist()) - olc.atomradiitable.setCustom("Ni", 1.25) - olc.eval(self.nickel) - drs = self.olc.directions - nms = numpy.sqrt(numpy.sum(numpy.power(drs, 2), axis=1)) - self.assertTrue(0 < len(olc.directions)) - self.assertTrue(numpy.allclose(olc.distances, nms)) - return - - def test_gradients(self): - """Check OverlapCalculator.gradients.""" - olc = self.olc - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertEqual((6, 3), olc.gradients.shape) - self.assertTrue(numpy.allclose([0, 0, 0], numpy.sum(olc.gradients))) - g2 = olc.gradients[2] - self.assertTrue(abs(g2[0]) > 0.1) - tso0 = olc.totalsquareoverlap - dx = 1e-8 - rutile2 = loadDiffPyStructure("rutile.cif") - rutile2[2].xyz_cartn[0] += dx - olc.eval(rutile2) - g2nx = (olc.totalsquareoverlap - tso0) / dx - self.assertAlmostEqual(g2[0], g2nx, 6) - return - - def test_sitesquareoverlaps(self): - """Check OverlapCalculator.sitesquareoverlaps.""" - olc = self.olc - self.assertTrue(numpy.array_equal([], olc.sitesquareoverlaps)) - olc(self.rutile) - self.assertTrue(numpy.array_equal(6 * [0.0], olc.sitesquareoverlaps)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - sso = olc(self.rutile) - self.assertTrue(numpy.array_equal(sso, olc.sitesquareoverlaps)) - self.assertTrue(numpy.all(sso)) - return - - def test_totalsquareoverlap(self): - """Check OverlapCalculator.totalsquareoverlap.""" - olc = self.olc - self.assertEqual(0.0, olc.totalsquareoverlap) - olc(self.rutile) - self.assertEqual(0.0, olc.totalsquareoverlap) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertTrue(1.20854162728, olc.totalsquareoverlap) - return - - def test_meansquareoverlap(self): - """Check OverlapCalculator.meansquareoverlap.""" - olc = self.olc - self.assertEqual(0.0, olc.meansquareoverlap) - olc(self.nickel) - self.assertEqual(0.0, olc.meansquareoverlap) - olc.atomradiitable.setCustom("Ni", 1.25) - olc(self.nickel) - mso0 = olc.meansquareoverlap - self.assertTrue(mso0 > 0.0) - sso1 = olc(self.niprim) - self.assertEqual(1, len(sso1)) - self.assertAlmostEqual(mso0, olc.meansquareoverlap) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertAlmostEqual(0.201423604547, olc.meansquareoverlap) - return - - def test_flipDiffTotal(self): - """Check OverlapCalculator.flipDiffTotal.""" - olc = self.olc - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertEqual(0.0, olc.flipDiffTotal(0, 0)) - self.assertEqual(0.0, olc.flipDiffTotal(0, 1)) - self.assertEqual(0.0, olc.flipDiffTotal(2, 5)) - tso0 = olc.totalsquareoverlap - olc2 = copy.copy(olc) - rutile2 = loadDiffPyStructure("rutile.cif") - rutile2[0].element = "O" - rutile2[2].element = "Ti" - olc2(rutile2) - fdt02 = olc2.totalsquareoverlap - tso0 - self.assertTrue(fdt02 > 0.01) - self.assertAlmostEqual(fdt02, olc.flipDiffTotal(0, 2)) - n02 = numpy.array([0, 2], dtype=int) - self.assertAlmostEqual(fdt02, olc.flipDiffTotal(*n02)) - return - - def test_getNeighborSites(self): - """Check OverlapCalculator.getNeighborSites.""" - olc = self.olc - olc(self.rutile) - self.assertEqual(set(), olc.getNeighborSites(0)) - self.assertEqual(set(), olc.getNeighborSites(3)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - oxygens = list(range(2, 6)) - self.assertEqual(set([0] + oxygens), olc.getNeighborSites(0)) - self.assertEqual(set([1] + oxygens), olc.getNeighborSites(1)) - self.assertEqual(set(range(2)), olc.getNeighborSites(2)) - self.assertEqual(set(range(2)), olc.getNeighborSites(5)) - (n5,) = numpy.array([5], dtype=int) - self.assertEqual(set(range(2)), olc.getNeighborSites(n5)) - return - - def test_coordinations(self): - """Check OverlapCalculator.coordinations.""" - olc = self.olc - self.assertEqual(0, len(olc.coordinations)) - olc(self.rutile) - self.assertEqual(6, len(olc.coordinations)) - self.assertFalse(numpy.any(olc.coordinations)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertTrue( - numpy.array_equal([8, 8, 3, 3, 3, 3], olc.coordinations) - ) - return - - def test_coordinationByTypes(self): - """Check OverlapCalculator.coordinationByTypes.""" - olc = self.olc - olc(self.rutile) - self.assertEqual({}, olc.coordinationByTypes(0)) - self.assertEqual({}, olc.coordinationByTypes(5)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - cTi = {"Ti": 2.0, "O": 6.0} - cO = {"Ti": 3.0} - self.assertEqual(cTi, olc.coordinationByTypes(0)) - self.assertEqual(cTi, olc.coordinationByTypes(1)) - self.assertEqual(cO, olc.coordinationByTypes(2)) - self.assertEqual(cO, olc.coordinationByTypes(3)) - self.assertEqual(cO, olc.coordinationByTypes(4)) - self.assertEqual(cO, olc.coordinationByTypes(5)) - return - - def test_neighborhoods(self): - """Check OverlapCalculator.neighborhoods.""" - olc = self.olc - self.assertEqual([], olc.neighborhoods) - olc(self.rutile) - self.assertEqual([set((i,)) for i in range(6)], olc.neighborhoods) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertEqual([set(range(6))], olc.neighborhoods) - olc.atomradiitable.setCustom("Ti", 1.8) - olc.atomradiitable.setCustom("O", 0.1) - olc(self.rutile) - nghbs = [set((0, 1))] + [set((i,)) for i in range(2, 6)] - self.assertEqual(nghbs, olc.neighborhoods) - return - - -# End of class TestOverlapCalculator - -# ---------------------------------------------------------------------------- - - -class TestOverlapCalculatorObjCryst(unittest.TestCase): - - @pytest.fixture(autouse=True) - def _check_pyobjcryst(self, has_pyobjcryst, _msg_nopyobjcryst): - if not has_pyobjcryst: - pytest.skip(_msg_nopyobjcryst) - - def setUp(self): - self.olc = OverlapCalculator() - if not hasattr(self, "rutile"): - type(self).rutile = loadObjCrystCrystal("rutile.cif") - if not hasattr(self, "nickel"): - type(self).nickel = loadObjCrystCrystal("Ni.cif") - return - - def tearDown(self): - return - - def test_totalsquareoverlap(self): - """Check OverlapCalculator.totalsquareoverlap for ObjCryst - crystal.""" - olc = self.olc - self.assertEqual(0.0, olc.totalsquareoverlap) - olc(self.rutile) - self.assertEqual(0.0, olc.totalsquareoverlap) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertTrue(1.20854162728, olc.totalsquareoverlap) - return - - def test_meansquareoverlap(self): - """Check OverlapCalculator.meansquareoverlap for ObjCryst - crystal.""" - olc = self.olc - self.assertEqual(0.0, olc.meansquareoverlap) - olc(self.rutile) - self.assertEqual(0.0, olc.meansquareoverlap) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertAlmostEqual(0.201423604547, olc.meansquareoverlap) - return - - def test_flipDiffTotal(self): - """Check OverlapCalculator.flipDiffTotal for an ObjCryst - crystal.""" - olc = self.olc - olc(self.rutile) - self.assertEqual(0.0, olc.flipDiffTotal(0, 1)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - tso0 = olc.totalsquareoverlap - olc2 = copy.copy(olc) - olc2.atomradiitable.fromString("Ti:0.66, O:1.6") - olc2(self.rutile) - fdt01 = olc2.totalsquareoverlap - tso0 - self.assertAlmostEqual(fdt01, olc.flipDiffTotal(0, 1)) - return - - def test_flipDiffMean(self): - """Check OverlapCalculator.flipDiffMean for an ObjCryst - crystal.""" - olc = self.olc - olc(self.rutile) - self.assertEqual(0.0, olc.flipDiffMean(0, 1)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - mso0 = olc.meansquareoverlap - olc2 = copy.copy(olc) - olc2.atomradiitable.fromString("Ti:0.66, O:1.6") - olc2(self.rutile) - fdm01 = olc2.meansquareoverlap - mso0 - self.assertAlmostEqual(fdm01, olc.flipDiffMean(0, 1)) - self.assertAlmostEqual(fdm01, olc.flipDiffTotal(0, 1) / 6) - n01 = numpy.array([0, 1], dtype=int) - self.assertAlmostEqual(fdm01, olc.flipDiffMean(*n01)) - return - - def test_getNeighborSites(self): - """Check OverlapCalculator.getNeighborSites for an ObjCryst - crystal.""" - olc = self.olc - olc(self.rutile) - self.assertEqual(set(), olc.getNeighborSites(0)) - self.assertEqual(set(), olc.getNeighborSites(1)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertEqual(set([0, 1]), olc.getNeighborSites(0)) - self.assertEqual(set([0]), olc.getNeighborSites(1)) - return - - def test_coordinations(self): - """Check OverlapCalculator.coordinations for an ObjCryst - crystal.""" - olc = self.olc - self.assertEqual(0, len(olc.coordinations)) - olc(self.rutile) - self.assertEqual(2, len(olc.coordinations)) - self.assertFalse(numpy.any(olc.coordinations)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertTrue(numpy.array_equal([8, 3], olc.coordinations)) - return - - def test_coordinationByTypes(self): - """Check OverlapCalculator.coordinationByTypes for an ObjCryst - crystal.""" - olc = self.olc - olc(self.rutile) - self.assertEqual({}, olc.coordinationByTypes(0)) - self.assertEqual({}, olc.coordinationByTypes(1)) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - cTi = {"Ti": 2.0, "O": 6.0} - cO = {"Ti": 3.0} - self.assertEqual(cTi, olc.coordinationByTypes(0)) - self.assertEqual(cO, olc.coordinationByTypes(1)) - return - - def test_neighborhoods(self): - """Check OverlapCalculator.neighborhoods for an ObjCryst - crystal.""" - olc = self.olc - self.assertEqual([], olc.neighborhoods) - olc(self.rutile) - self.assertEqual([set((i,)) for i in range(2)], olc.neighborhoods) - olc.atomradiitable.fromString("Ti:1.6, O:0.66") - olc(self.rutile) - self.assertEqual([set((0, 1))], olc.neighborhoods) - return - - -# End of class TestOverlapCalculatorObjCryst - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_pairquantity.py b/tests/test_pairquantity.py deleted file mode 100644 index 14335a9f..00000000 --- a/tests/test_pairquantity.py +++ /dev/null @@ -1,256 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.pairquantity.""" - -import pickle -import unittest - -import numpy -from testutils import mod_structure - -from diffpy.srreal.pairquantity import PairQuantity -from diffpy.srreal.pdfcalculator import PDFCalculator -from diffpy.srreal.srreal_ext import BasePairQuantity - -# ---------------------------------------------------------------------------- - - -class TestBasePairQuantity(unittest.TestCase): - - def setUp(self): - self.bpq = BasePairQuantity() - return - - def test_pickling(self): - "verify pickling is disabled for the C++ base class." - self.assertRaises(RuntimeError, pickle.dumps, self.bpq) - return - - -# End of class TestBasePairQuantity - -# ---------------------------------------------------------------------------- - - -class TestPairQuantity(unittest.TestCase): - - def setUp(self): - self.pq = PairQuantity() - return - - def test_evaluatortype(self): - """Check PairQuantity.evaluatortype property.""" - pq = self.pq - self.assertTrue(pq.evaluatortype in ("BASIC", "OPTIMIZED")) - pq.evaluatortype = "BASIC" - self.assertEqual("BASIC", pq.evaluatortype) - self.assertRaises(ValueError, setattr, pq, "evaluatortype", "invalid") - self.assertRaises(ValueError, setattr, pq, "evaluatortype", "basic") - self.assertRaises(ValueError, setattr, pq, "evaluatortype", "BASic") - # check all supported evaluators in PDFCalculator - pdfc = PDFCalculator() - self.assertEqual("OPTIMIZED", pdfc.evaluatortype) - pdfc.evaluatortype = "BASIC" - self.assertEqual("BASIC", pdfc.evaluatortype) - pdfc.evaluatortype = "CHECK" - self.assertEqual("CHECK", pdfc.evaluatortype) - pdfc.evaluatortype = "OPTIMIZED" - self.assertEqual("OPTIMIZED", pdfc.evaluatortype) - return - - def test_setStructure(self): - """Check PairQuantity.setStructure()""" - Structure = mod_structure.Structure - Atom = mod_structure.Atom - from diffpy.srreal.structureadapter import EMPTY - - stru = Structure([Atom("Ar", [0.1, 0.2, 0.3])]) - self.pq.setStructure(stru) - adpt = self.pq.getStructure() - self.assertEqual(1, adpt.countSites()) - self.assertEqual("Ar", adpt.siteAtomType(0)) - self.pq.setStructure(EMPTY) - adpt = self.pq.getStructure() - self.assertEqual(0, adpt.countSites()) - return - - def test_setPairMask_args(self): - """Check argument type handling in setPairMask.""" - spm = self.pq.setPairMask - gpm = self.pq.getPairMask - self.assertRaises(TypeError, spm, 0.0, 0, False) - self.assertRaises(TypeError, spm, complex(0.5), 0, False) - self.assertTrue(gpm(0, 0)) - spm(numpy.int32(1), 0, True, others=False) - self.assertTrue(gpm(0, 1)) - self.assertTrue(gpm(1, 0)) - self.assertFalse(gpm(0, 0)) - self.assertFalse(gpm(2, 7)) - return - - def test_getStructure(self): - """Check PairQuantity.getStructure()""" - adpt = self.pq.getStructure() - self.assertEqual(0, adpt.countSites()) - return - - def test_ticker(self): - """Check PairQuantity.ticker()""" - from diffpy.srreal.eventticker import EventTicker - - et0 = EventTicker(self.pq.ticker()) - self.pq.rmax = 3.77 - et1 = self.pq.ticker() - self.assertNotEqual(et0, et1) - self.assertTrue(et0 < et1) - return - - def test_ticker_override(self): - """Check Python override of PairQuantity.ticker.""" - pqcnt = PQCounter() - self.assertEqual(0, pqcnt.tcnt) - et0 = pqcnt.ticker() - self.assertEqual(1, pqcnt.tcnt) - et1 = PairQuantity.ticker(pqcnt) - self.assertEqual(1, pqcnt.tcnt) - self.assertEqual(et0, et1) - et0.click() - self.assertEqual(et0, et1) - # BASIC evaluator does not call the ticker method. - pqcnt.eval() - self.assertEqual(1, pqcnt.tcnt) - # Check if ticker call from OPTIMIZED evaluator is handled - # with our Python override. - pqcnt.evaluatortype = "OPTIMIZED" - self.assertEqual(1, pqcnt.tcnt) - pqcnt.eval() - self.assertEqual(2, pqcnt.tcnt) - return - - def test__addPairContribution(self): - """Check Python override of - PairQuantity._addPairContribution.""" - pqcnt = PQCounter() - self.assertEqual(0, pqcnt(carbonzchain(0))) - self.assertEqual(0, pqcnt(carbonzchain(1))) - self.assertEqual(1, pqcnt(carbonzchain(2))) - self.assertEqual(10, pqcnt(carbonzchain(5))) - return - - def test_optimized_evaluation(self): - """Check OPTIMIZED evaluation in Python-defined calculator - class.""" - c8 = carbonzchain(8) - c9 = carbonzchain(9) - pqd = PQDerived() - - # wrapper for evaluation using specified evaluatortype. - # Use pq.eval twice to trigger optimized evaluation. - 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 - # raise ValueError or RuntimeError for older libdiffpy. - # Here we check for StandardError that covers them both. - self.assertRaises(Exception, eval_as, "OPTIMIZED", pqd, c8) - # PQCounter supports OPTIMIZED evaluation mode. - ocnt = PQCounter() - ocnt.evaluatortype = "OPTIMIZED" - self.assertEqual(28, ocnt(c8)) - self.assertEqual(28, ocnt(c8)) - self.assertEqual("OPTIMIZED", ocnt.evaluatortypeused) - self.assertEqual(36, ocnt(c9)) - self.assertEqual("OPTIMIZED", ocnt.evaluatortypeused) - self.assertEqual(28, ocnt(c8)) - self.assertEqual("OPTIMIZED", ocnt.evaluatortypeused) - return - - def test_pickling(self): - """Check pickling and unpickling of PairQuantity.""" - from testutils import DerivedStructureAdapter - - stru0 = DerivedStructureAdapter() - self.pq.setStructure(stru0) - self.assertEqual(1, stru0.cpqcount) - spkl = pickle.dumps(self.pq) - pq1 = pickle.loads(spkl) - self.assertTrue(stru0 is self.pq.getStructure()) - stru1 = pq1.getStructure() - self.assertTrue(type(stru1) is DerivedStructureAdapter) - self.assertFalse(stru1 is stru0) - self.assertEqual(1, stru1.cpqcount) - # check pickling of attributes - pcnt = PQCounter() - pcnt.foo = "asdf" - pcnt2 = pickle.loads(pickle.dumps(pcnt)) - self.assertTrue(isinstance(pcnt2, PQCounter)) - self.assertEqual("asdf", pcnt2.foo) - return - - -# End of class TestPairQuantity - -# ---------------------------------------------------------------------------- - -# helper for testing PairQuantity overrides - - -class PQDerived(PairQuantity): - - tcnt = 0 - - def ticker(self): - self.tcnt += 1 - return PairQuantity.ticker(self) - - -# End of class PQDerived - -# helper for testing support for optimized evaluation - - -class PQCounter(PQDerived): - - def __init__(self): - super(PQCounter, self).__init__() - self._resizeValue(1) - self.rmax = 10 - return - - def __call__(self, structure=None): - (rv,) = self.eval(structure) - return rv - - def _addPairContribution(self, bnds, sumscale): - self._value[0] += 0.5 * sumscale - return - - def _stashPartialValue(self): - self.__stashed_value = self._value[0] - return - - def _restorePartialValue(self): - self._value[0] = self.__stashed_value - del self.__stashed_value - return - - -# End of class PQCounter - - -def carbonzchain(n): - "Helper function that returns a z-chain of Carbon atoms." - Structure = mod_structure.Structure - Atom = mod_structure.Atom - rv = Structure([Atom("C", [0, 0, z]) for z in range(n)]) - return rv - - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_parallel.py b/tests/test_parallel.py deleted file mode 100644 index b4b53b17..00000000 --- a/tests/test_parallel.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.parallel.""" - - -import multiprocessing -import unittest - -import numpy -from testutils import loadDiffPyStructure - -from diffpy.srreal.parallel import createParallelCalculator - - -############################################################################## -class TestRoutines(unittest.TestCase): - - _pool = None - ncpu = 4 - cdse = None - nickel = None - - def setUp(self): - if self.cdse is None: - type(self).cdse = loadDiffPyStructure("CdSe_cadmoselite.cif") - for a in self.cdse: - a.Uisoequiv = 0.003 - if self.nickel is None: - type(self).nickel = loadDiffPyStructure("Ni.cif") - for a in self.nickel: - a.Uisoequiv = 0.003 - return - - def tearDown(self): - if self._pool: - self._pool.terminate() - self._pool.join() - self._pool = None - return - - @property - def pool(self): - if not self._pool: - self._pool = multiprocessing.Pool(processes=self.ncpu) - return self._pool - - def test_parallel_evaluatortype(self): - """Check handling of the evaluatortype property.""" - from diffpy.srreal.pdfcalculator import PDFCalculator - - pdfc = PDFCalculator() - self.assertEqual("OPTIMIZED", pdfc.evaluatortype) - ppdfc = createParallelCalculator(pdfc, 2, map) - self.assertEqual("BASIC", ppdfc.evaluatortype) - self.assertEqual("BASIC", pdfc.evaluatortype) - ppdfc.evaluatortype = "BASIC" - self.assertRaises( - ValueError, setattr, ppdfc, "evaluatortype", "OPTIMIZED" - ) - return - - def test_parallel_pdf(self): - """Check parallel PDFCalculator.""" - from diffpy.srreal.pdfcalculator import PDFCalculator - - pdfc = PDFCalculator() - r0, g0 = pdfc(self.cdse) - ppdfc1 = createParallelCalculator(PDFCalculator(), 3, map) - r1, g1 = ppdfc1(self.cdse) - self.assertTrue(numpy.array_equal(r0, r1)) - self.assertTrue(numpy.allclose(g0, g1)) - ppdfc2 = createParallelCalculator( - PDFCalculator(), self.ncpu, self.pool.imap_unordered - ) - r2, g2 = ppdfc2(self.cdse) - self.assertTrue(numpy.array_equal(r0, r2)) - self.assertTrue(numpy.allclose(g0, g2)) - pdfc.rmax = ppdfc1.rmax = ppdfc2.rmax = 5 - pdfc.qmax = ppdfc1.qmax = ppdfc2.qmax = 15 - r0a, g0a = pdfc() - self.assertTrue(numpy.all(r0a <= 5)) - self.assertFalse(numpy.allclose(g0a, numpy.interp(r0a, r0, g0))) - r1a, g1a = ppdfc1() - self.assertTrue(numpy.array_equal(r0a, r1a)) - self.assertTrue(numpy.allclose(g0a, g1a)) - r2a, g2a = ppdfc2() - self.assertTrue(numpy.array_equal(r0a, r2a)) - self.assertTrue(numpy.allclose(g0a, g2a)) - return - - def test_parallel_bonds(self): - """Check parallel BondCalculator.""" - from diffpy.srreal.bondcalculator import BondCalculator - - nickel = self.nickel - bc = BondCalculator() - d0 = bc(nickel) - pbc1 = createParallelCalculator(BondCalculator(), 3, map) - d1 = pbc1(nickel) - self.assertTrue(numpy.array_equal(d0, d1)) - pbc2 = createParallelCalculator( - BondCalculator(), self.ncpu, self.pool.imap_unordered - ) - d2 = pbc2(nickel) - self.assertTrue(numpy.array_equal(d0, d2)) - bc.rmax = pbc1.rmax = pbc2.rmax = 2.5 - for bci in (bc, pbc1, pbc2): - bci.maskAllPairs(False) - bci.setPairMask(0, "all", True) - bci.filterCone([1, 0, 0], 48) - d0a = bc(nickel) - self.assertEqual(8, len(d0a)) - d1a = pbc1(nickel) - self.assertTrue(numpy.array_equal(d0a, d1a)) - d2a = pbc2(nickel) - self.assertTrue(numpy.array_equal(d0a, d2a)) - return - - -# End of class TestRoutines - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_pdfbaseline.py b/tests/test_pdfbaseline.py deleted file mode 100644 index e9aff06a..00000000 --- a/tests/test_pdfbaseline.py +++ /dev/null @@ -1,260 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for the PDFBaseline class from -diffpy.srreal.pdfcalculator.""" - - -import pickle -import unittest - -import numpy -from testutils import pickle_with_attr - -from diffpy.srreal.pdfbaseline import ( - LinearBaseline, - PDFBaseline, - ZeroBaseline, - makePDFBaseline, -) -from diffpy.srreal.pdfcalculator import PDFCalculator - -# ---------------------------------------------------------------------------- - - -class TestPDFBaseline(unittest.TestCase): - - def setUp(self): - self.linear = PDFBaseline.createByType("linear") - self.zero = PDFBaseline.createByType("zero") - return - - def tearDown(self): - for tp in PDFBaseline.getRegisteredTypes(): - PDFBaseline._deregisterType(tp) - self.linear._registerThisType() - self.zero._registerThisType() - return - - def test___init__(self): - """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__()""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFBaseline().__call__, 37) - self.assertEqual(0.0, self.zero(10)) - self.assertEqual(0.0, self.zero(3.45)) - self.assertEqual(0.0, self.linear(3.45)) - self.assertEqual(0.0, self.linear(345)) - self.linear.slope = -2 - self.assertEqual(-7.0, self.linear(3.5)) - self.assertEqual(-2.0, self.linear._getDoubleAttr("slope")) - x = numpy.arange(0, 10.001, 0.1) - xb = numpy.array([(0.0, xi) for xi in x])[:, 1] - self.assertTrue(xb.strides > x.strides) - self.assertTrue(numpy.array_equal(-2 * x, self.linear(x))) - self.assertTrue(numpy.array_equal(-2 * x, self.linear(xb))) - return - - def test_clone(self): - """Check PDFBaseline.clone.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFBaseline().clone) - self.linear.slope = 17 - bl2 = self.linear.clone() - self.assertEqual("linear", bl2.type()) - self.assertEqual(17.0, bl2.slope) - self.assertEqual(17.0, bl2._getDoubleAttr("slope")) - return - - def test_create(self): - """Check PDFBaseline.create.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFBaseline().create) - self.assertEqual("zero", self.zero.create().type()) - self.assertEqual("linear", self.linear.create().type()) - self.linear.slope = 17 - self.assertEqual(0.0, self.linear.create().slope) - return - - def test_type(self): - """Check PDFBaseline.type.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFBaseline().type) - self.assertEqual("linear", self.linear.type()) - self.assertEqual("zero", self.zero.type()) - self.assertTrue(type(self.linear) is LinearBaseline) - self.assertTrue(type(self.zero) is ZeroBaseline) - return - - def test__aliasType(self): - """Check PDFBaseline._aliasType.""" - self.assertRaises(ValueError, PDFBaseline.createByType, "alias") - self.assertRaises( - RuntimeError, PDFBaseline._aliasType, "invalid", "alias" - ) - self.assertRaises( - RuntimeError, PDFBaseline._aliasType, "linear", "zero" - ) - PDFBaseline._aliasType("linear", "alias") - bl = PDFBaseline.createByType("alias") - self.assertEqual("linear", bl.type()) - self.assertTrue(isinstance(bl, LinearBaseline)) - # second registration is a no-op - PDFBaseline._aliasType("linear", "alias") - bl1 = PDFBaseline.createByType("alias") - self.assertTrue(isinstance(bl1, LinearBaseline)) - # no other type can be aliased to the existing name. - self.assertRaises( - RuntimeError, PDFBaseline._aliasType, "zero", "alias" - ) - return - - def test__deregisterType(self): - """Check PDFBaseline._deregisterType.""" - self.assertEqual(0, PDFBaseline._deregisterType("nonexistent")) - PDFBaseline._aliasType("linear", "alias") - self.assertEqual(2, PDFBaseline._deregisterType("alias")) - self.assertFalse("linear" in PDFBaseline.getRegisteredTypes()) - self.assertEqual(0, PDFBaseline._deregisterType("alias")) - return - - def test_createByType(self): - """Check PDFBaseline.createByType()""" - self.assertRaises( - ValueError, PDFBaseline.createByType, "notregistered" - ) - return - - def test_isRegisteredType(self): - """Check PDFBaseline.isRegisteredType()""" - self.assertTrue(PDFBaseline.isRegisteredType("linear")) - self.assertFalse(PDFBaseline.isRegisteredType("nonexistent")) - PDFBaseline._deregisterType("linear") - self.assertFalse(PDFBaseline.isRegisteredType("linear")) - return - - def test_getAliasedTypes(self): - """Check PDFBaseline.getAliasedTypes()""" - self.assertEqual({}, PDFBaseline.getAliasedTypes()) - PDFBaseline._aliasType("linear", "foo") - PDFBaseline._aliasType("linear", "bar") - PDFBaseline._aliasType("linear", "linear") - PDFBaseline._aliasType("bar", "foo") - self.assertEqual( - {"bar": "linear", "foo": "linear"}, PDFBaseline.getAliasedTypes() - ) - return - - def test_getRegisteredTypes(self): - """Check PDFBaseline.getRegisteredTypes.""" - regtypes = PDFBaseline.getRegisteredTypes() - self.assertTrue(2 <= len(regtypes)) - self.assertTrue("linear" in regtypes) - self.assertTrue("zero" in regtypes) - return - - def test_pickling(self): - """Check pickling and unpickling of PDFBaseline.""" - linear = self.linear - linear.slope = 11 - linear2 = pickle.loads(pickle.dumps(linear)) - self.assertEqual("linear", linear2.type()) - self.assertEqual(11, linear2.slope) - self.assertEqual(11, linear2._getDoubleAttr("slope")) - self.assertRaises(RuntimeError, pickle_with_attr, linear, foo="bar") - self.assertRaises(RuntimeError, pickle_with_attr, self.zero, foo="bar") - return - - def test_makePDFBaseline(self): - """Check the makePDFBaseline wrapper.""" - pbl = makePDFBaseline( - "parabolabaseline", parabola_baseline, a=1, b=2, c=3 - ) - self.assertEqual(3, pbl(0)) - self.assertEqual(6, pbl(1)) - self.assertEqual(11, pbl(2)) - pbl.b = 0 - self.assertEqual([7, 3, 28], [pbl(x) for x in [-2, 0, 5]]) - pbl2 = pbl.clone() - self.assertEqual(1, pbl2.a) - self.assertEqual(0, pbl2.b) - self.assertEqual(3, pbl2.c) - self.assertEqual([7, 3, 28], [pbl2(x) for x in [-2, 0, 5]]) - pbl3 = PDFBaseline.createByType("parabolabaseline") - self.assertEqual(1, pbl3.a) - self.assertEqual(2, pbl3.b) - self.assertEqual(3, pbl3.c) - pbl.foo = "bar" - pbl4 = pickle.loads(pickle.dumps(pbl)) - self.assertEqual([7, 3, 28], [pbl4(x) for x in [-2, 0, 5]]) - self.assertEqual("bar", pbl4.foo) - # fail if this baseline type already exists. - self.assertRaises( - RuntimeError, - makePDFBaseline, - "linear", - parabola_baseline, - a=1, - b=2, - c=3, - ) - self.assertRaises( - RuntimeError, - makePDFBaseline, - "parabolabaseline", - parabola_baseline, - a=1, - b=2, - c=3, - ) - # check replacement of an existing type. - makePDFBaseline( - "linear", parabola_baseline, replace=True, a=1, b=2, c=4 - ) - pbl4 = PDFBaseline.createByType("linear") - self.assertEqual(set(("a", "b", "c")), pbl4._namesOfDoubleAttributes()) - self.assertEqual(4, pbl4.c) - # check baseline with no attributes - pbl5 = makePDFBaseline("myzero", lambda x: 0.0) - self.assertEqual(0, pbl5(33)) - self.assertEqual(set(), pbl5._namesOfDoubleAttributes()) - return - - def test_picking_owned(self): - """Verify pickling of PDFBaseline owned by PDF calculators.""" - pbl = makePDFBaseline( - "parabolabaseline", parabola_baseline, a=1, b=2, c=3 - ) - pbl.a = 7 - pbl.foobar = "asdf" - pc = PDFCalculator() - pc.baseline = pbl - self.assertIs(pbl, pc.baseline) - pc2 = pickle.loads(pickle.dumps(pc)) - pbl2 = pc2.baseline - self.assertEqual(7, pbl2.a) - self.assertEqual("asdf", pbl2.foobar) - self.assertEqual("parabolabaseline", pbl2.type()) - return - - -# End of class TestPDFBaseline - -# ---------------------------------------------------------------------------- - -# function for wrapping by makePDFBaseline - - -def parabola_baseline(x, a, b, c): - return a * x**2 + b * x + c - - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_pdfcalcobjcryst.py b/tests/test_pdfcalcobjcryst.py deleted file mode 100644 index d0ef6da5..00000000 --- a/tests/test_pdfcalcobjcryst.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for pdfcalculator.py on ObjCryst crystal structures.""" - - -import re -import unittest - -import numpy -import pytest -from testutils import _maxNormDiff, datafile, loadObjCrystCrystal - -from diffpy.srreal.pdfcalculator import PDFCalculator - -# helper functions - - -def _loadExpectedPDF(basefilename): - """Read expected result and return a tuple of (r, g, cfgdict).""" - rxf = re.compile(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?") - fullpath = datafile(basefilename) - cfgdict = {} - fp = open(fullpath) - for line in fp: - if line[:1] != "#": - break - w = line.split() - has_cfgdata = len(w) == 4 and w[2] == "=" - if not has_cfgdata: - continue - cfgdict[w[1]] = w[3] - if rxf.match(w[3]): - cfgdict[w[1]] = float(w[3]) - fp.close() - r, g = numpy.loadtxt(fullpath, usecols=(0, 1), unpack=True) - rv = (r, g, cfgdict) - return rv - - -def _makePDFCalculator(crst, cfgdict): - """Return a PDFCalculator object evaluated for a pyobjcryst.Crystal - crst.""" - pdfcargs = {k: v for k, v in cfgdict.items() if k not in ("biso", "type")} - pdfc = PDFCalculator(**pdfcargs) - if "biso" in cfgdict: - reg = crst.GetScatteringPowerRegistry() - for i in range(reg.GetNb()): - sp = reg.GetObj(i) - sp.SetBiso(cfgdict["biso"]) - if "type" in cfgdict: - pdfc.scatteringfactortable = cfgdict["type"] - pdfc.eval(crst) - # avoid metadata override by PDFFitStructure - for k, v in pdfcargs.items(): - setattr(pdfc, k, v) - return pdfc - - -# ---------------------------------------------------------------------------- - - -class TestPDFCalcObjcryst(unittest.TestCase): - - @pytest.fixture(autouse=True) - def _check_pyobjcryst(self, has_pyobjcryst, _msg_nopyobjcryst): - if not has_pyobjcryst: - pytest.skip(_msg_nopyobjcryst) - - def _comparePDFs(self, nickname, pdfbasename, cifbasename): - def setself(**kwtoset): - for n, v in kwtoset.items(): - setattr(self, nickname + "_" + n, v) - return - - r, gobs, cfg = _loadExpectedPDF(pdfbasename) - setself(r=r, gobs=gobs, cfg=cfg) - crst = loadObjCrystCrystal(cifbasename) - setself(crst=crst) - pdfc = _makePDFCalculator(crst, cfg) - gcalc = pdfc.pdf - mxnd = _maxNormDiff(gobs, gcalc) - setself(gcalc=gcalc, mxnd=mxnd) - return - - def test_CdSeN(self): - """Check PDFCalculator on ObjCryst loaded CIF, neutrons.""" - self._comparePDFs( - "cdsen", "CdSe_cadmoselite_N.fgr", "CdSe_cadmoselite.cif" - ) - self.assertTrue(self.cdsen_mxnd < 0.01) - return - - def test_CdSeX(self): - """Check PDFCalculator on ObjCryst loaded CIF, xrays.""" - self._comparePDFs( - "cdsex", "CdSe_cadmoselite_X.fgr", "CdSe_cadmoselite.cif" - ) - self.assertTrue(self.cdsex_mxnd < 0.01) - return - - def test_rutileaniso(self): - """Check PDFCalculator on ObjCryst loaded anisotropic rutile.""" - self._comparePDFs( - "rutileaniso", "TiO2_rutile-fit.fgr", "TiO2_rutile-fit.cif" - ) - self.assertTrue(self.rutileaniso_mxnd < 0.057) - return - - -# End of class TestPDFCalcObjcryst - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_pdfcalculator.py b/tests/test_pdfcalculator.py deleted file mode 100644 index 28b31980..00000000 --- a/tests/test_pdfcalculator.py +++ /dev/null @@ -1,376 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.pdfcalculator.""" - - -import pickle -import unittest - -import numpy -from testutils import ( - _maxNormDiff, - datafile, - loadDiffPyStructure, - pickle_with_attr, -) - -from diffpy.srreal.pdfcalculator import PDFCalculator, fftftog, fftgtof - -# helper functions - - -# ---------------------------------------------------------------------------- - - -class TestPDFCalculator(unittest.TestCase): - - nickel = None - tio2rutile = None - - def setUp(self): - self.pdfcalc = PDFCalculator() - if not self.nickel: - type(self).nickel = loadDiffPyStructure("Ni.stru") - if not self.tio2rutile: - type(self).tio2rutile = loadDiffPyStructure("TiO2_rutile-fit.stru") - return - - def tearDown(self): - return - - def test___init__(self): - """Check PDFCalculator.__init__()""" - pdfc = PDFCalculator(qmin=13, rmin=4, rmax=99) - self.assertEqual(13, pdfc.qmin) - self.assertEqual(4, pdfc.rmin) - self.assertEqual(99, pdfc.rmax) - self.assertEqual(99, pdfc._getDoubleAttr("rmax")) - return - - def test___call__(self): - """Check PDFCalculator.__call__()""" - r0, g0 = self.pdfcalc(self.tio2rutile, rmin=2) - self.assertEqual(2.0, r0[0]) - r1, g1 = self.pdfcalc(self.tio2rutile, scale=7) - self.assertAlmostEqual(7.0, g1[0] / g0[0]) - # check application of spdiameter - rutile2 = self.tio2rutile.copy() - # work around Structure bug of shared pdffit dictionary - rutile2.pdffit = dict(self.tio2rutile.pdffit) - rutile2.pdffit["spdiameter"] = 5.0 - r3, g3 = self.pdfcalc(rutile2) - self.assertEqual(0.0, sum(g3[r3 >= 5] ** 2)) - r4, g4 = self.pdfcalc(rutile2, scale=1, spdiameter=0) - self.assertTrue(numpy.all(r4 == r0)) - self.assertTrue(numpy.all(g4 == g0)) - return - - def test__getDoubleAttr(self): - """Check PDFCalculator._getDoubleAttr()""" - gdba = self.pdfcalc._getDoubleAttr - self.assertEqual(1.0, gdba("scale")) - self.assertEqual(0.0, gdba("qdamp")) - self.assertRaises(Exception, gdba, "notanattribute") - return - - def test__hasDoubleAttr(self): - """Check PDFCalculator._hasDoubleAttr()""" - self.assertTrue(self.pdfcalc._hasDoubleAttr("scale")) - self.assertFalse(self.pdfcalc._hasDoubleAttr("notanattribute")) - return - - def test__namesOfDoubleAttributes(self): - """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()""" - gdba = self.pdfcalc._getDoubleAttr - sdba = self.pdfcalc._setDoubleAttr - self.assertEqual(0.0, gdba("rmin")) - sdba("rmin", 3.0) - self.assertEqual(3.0, gdba("rmin")) - return - - def test_eval_nickel(self): - """Check PDFCalculator.eval() on simple Nickel data.""" - fnipf2 = datafile("Ni-fit.fgr") - gpf2 = numpy.loadtxt(fnipf2, usecols=(1,)) - self.pdfcalc._setDoubleAttr("rmax", 10.0001) - self.pdfcalc.eval(self.nickel) - gcalc = self.pdfcalc.pdf - self.assertTrue(_maxNormDiff(gpf2, gcalc) < 0.0091) - return - - def test_eval_rutile(self): - """Check PDFCalculator.eval() on anisotropic rutile data.""" - frutile = datafile("TiO2_rutile-fit.fgr") - gpf2 = numpy.loadtxt(frutile, usecols=(1,)) - # configure calculator according to testdata/TiO2_ruitile-fit.fgr - self.pdfcalc.qmax = 26 - self.pdfcalc.qdamp = 0.0665649 - dscale = 0.655857 - self.pdfcalc.rmin = 1 - self.pdfcalc.rmax = 30.0001 - # apply data scale - self.pdfcalc(self.tio2rutile) - self.pdfcalc.scale *= dscale - gcalc = self.pdfcalc.pdf - # termination at rmin is poorly cut in PDFfit2 - mxnd = _maxNormDiff(gpf2, gcalc) - self.assertTrue(mxnd < 0.057) - # more accurate from 1.5 - mxnd1 = _maxNormDiff(gpf2[:500], gcalc[:500]) - mxnd2 = _maxNormDiff(gpf2[500:], gcalc[500:]) - self.assertTrue(mxnd1 < 0.056) - self.assertTrue(mxnd2 < 0.020) - return - - def test_partial_pdfs(self): - """Check calculation of partial PDFs.""" - pdfc = self.pdfcalc - pdfc.rstep = 0.1 - rutile = self.tio2rutile - atomtypes = [a.element for a in rutile] - r0, g0 = pdfc(rutile) - rdf0 = pdfc.rdf - # Ti-Ti - pdfc.maskAllPairs(False) - pdfc.setTypeMask("Ti", "Ti", True) - r1, g1 = pdfc(rutile) - rdf1 = pdfc.rdf - self.assertTrue(numpy.array_equal(r0, r1)) - pdfc.invertMask() - r1i, g1i = pdfc(rutile) - rdf1i = pdfc.rdf - self.assertTrue(numpy.array_equal(r0, r1i)) - self.assertTrue(numpy.allclose(g0, g1 + g1i)) - self.assertTrue(numpy.allclose(rdf0, rdf1 + rdf1i)) - # Ti-O - pdfc.maskAllPairs(True) - pdfc.setPairMask(range(2), range(2), False) - pdfc.setPairMask(range(2, 6), range(2, 6), False) - r2, g2 = pdfc(rutile) - rdf2 = pdfc.rdf - self.assertTrue(numpy.array_equal(r0, r2)) - pdfc.invertMask() - r2i, g2i = pdfc(rutile) - rdf2i = pdfc.rdf - self.assertTrue(numpy.allclose(g0, g2 + g2i)) - self.assertTrue(numpy.allclose(rdf0, rdf2 + rdf2i)) - # Ti-O using type mask - pdfc.maskAllPairs(True) - pdfc.setTypeMask("Ti", "Ti", False) - pdfc.setTypeMask("O", "O", False) - r2t, g2t = pdfc(rutile) - rdf2t = pdfc.rdf - self.assertTrue(numpy.array_equal(r0, r2t)) - self.assertTrue(numpy.array_equal(g2, g2t)) - self.assertTrue(numpy.array_equal(rdf2, rdf2t)) - pdfc.invertMask() - r2ti, g2ti = pdfc(rutile) - rdf2ti = pdfc.rdf - self.assertTrue(numpy.array_equal(g2i, g2ti)) - self.assertTrue(numpy.array_equal(rdf2i, rdf2ti)) - # O-O - pdfc.maskAllPairs(False) - for i, smbli in enumerate(atomtypes): - for j, smblj in enumerate(atomtypes): - if smbli == smblj == "O": - pdfc.setPairMask(i, j, True) - r3, g3 = pdfc(rutile) - rdf3 = pdfc.rdf - pdfc.invertMask() - r3i, g3i = pdfc(rutile) - rdf3i = pdfc.rdf - self.assertTrue(numpy.allclose(g0, g3 + g3i)) - self.assertTrue(numpy.allclose(rdf0, rdf3 + rdf3i)) - # check the sum of all partials - self.assertTrue(numpy.allclose(g0, g1 + g2 + g3)) - self.assertTrue(numpy.allclose(rdf0, rdf1 + rdf2 + rdf3)) - return - - def test_full_mask(self): - """Test PDFCalculator for a fully masked structure.""" - pdfc = self.pdfcalc - pdfc.rstep = 0.1 - rutile = self.tio2rutile - pdfc.maskAllPairs(True) - r0, g0 = pdfc(rutile) - pdfc.maskAllPairs(False) - r1, g1 = pdfc(rutile) - self.assertEqual(0.0, numpy.dot(g1, g1)) - indices = list(range(len(rutile))) - pdfc.setPairMask(indices, indices, True) - r2, g2 = pdfc(rutile) - self.assertTrue(numpy.array_equal(g0, g2)) - return - - def test_zero_mask(self): - """Test PDFCalculator with a totally masked out structure.""" - pdfc = self.pdfcalc - pdfc.rstep = 0.1 - rutile = self.tio2rutile - indices = list(range(len(rutile))) - for i in indices: - for j in indices: - pdfc.setPairMask(i, j, False) - r, g = pdfc(rutile) - self.assertEqual(0.0, numpy.dot(g, g)) - rdf = pdfc.rdf - self.assertEqual(0.0, numpy.dot(rdf, rdf)) - return - - def test_pickling(self): - """Check pickling and unpickling of PDFCalculator.""" - pdfc = self.pdfcalc - pdfc.scatteringfactortable = "N" - pdfc.scatteringfactortable.setCustomAs("Na", "Na", 7) - pdfc.addEnvelope("sphericalshape") - pdfc.delta1 = 0.2 - pdfc.delta2 = 0.3 - pdfc.maxextension = 10.1 - pdfc.peakprecision = 5e-06 - pdfc.qbroad = 0.01 - pdfc.qdamp = 0.05 - pdfc.qmax = 10 - pdfc.qmin = 0.5 - pdfc.rmax = 10.0 - pdfc.rmin = 0.02 - pdfc.rstep = 0.02 - pdfc.scale = 1.1 - pdfc.slope = 0.1 - pdfc.spdiameter = 13.3 - spkl = pickle.dumps(pdfc) - pdfc1 = pickle.loads(spkl) - sft = pdfc.scatteringfactortable - sft1 = pdfc1.scatteringfactortable - self.assertEqual(sft.type(), sft1.type()) - self.assertEqual(7.0, sft1.lookup("Na")) - for a in pdfc._namesOfDoubleAttributes(): - self.assertEqual(getattr(pdfc, a), getattr(pdfc1, a)) - self.assertEqual(13.3, pdfc1.getEnvelope("sphericalshape").spdiameter) - self.assertEqual( - pdfc._namesOfDoubleAttributes(), pdfc1._namesOfDoubleAttributes() - ) - self.assertEqual(pdfc.usedenvelopetypes, pdfc1.usedenvelopetypes) - self.assertRaises(RuntimeError, pickle_with_attr, pdfc, foo="bar") - return - - def test_mask_pickling(self): - """Check if mask gets properly pickled and restored.""" - self.pdfcalc.maskAllPairs(False) - self.pdfcalc.setPairMask(0, 1, True) - self.assertTrue(False is self.pdfcalc.getPairMask(0, 0)) - self.assertTrue(True is self.pdfcalc.getPairMask(0, 1)) - pdfcalc1 = pickle.loads(pickle.dumps(self.pdfcalc)) - self.assertTrue(False is pdfcalc1.getPairMask(0, 0)) - self.assertTrue(True is pdfcalc1.getPairMask(0, 1)) - return - - def test_pickling_derived_structure(self): - """Check pickling of PDFCalculator with - DerivedStructureAdapter.""" - from testutils import DerivedStructureAdapter - - pdfc = self.pdfcalc - stru0 = DerivedStructureAdapter() - pdfc.setStructure(stru0) - self.assertEqual(1, stru0.cpqcount) - spkl = pickle.dumps(pdfc) - pdfc1 = pickle.loads(spkl) - self.assertTrue(stru0 is pdfc.getStructure()) - stru1 = pdfc1.getStructure() - self.assertTrue(type(stru1) is DerivedStructureAdapter) - self.assertFalse(stru1 is stru0) - self.assertEqual(1, stru1.cpqcount) - return - - def test_envelopes(self): - """Check the envelopes property.""" - from diffpy.srreal.pdfenvelope import PDFEnvelope - - pc = self.pdfcalc - self.assertTrue(len(pc.envelopes) > 0) - pc.clearEnvelopes() - self.assertEqual(0, len(pc.envelopes)) - pc.addEnvelope(PDFEnvelope.createByType("scale")) - self.assertEqual(1, len(pc.envelopes)) - self.assertEqual("scale", pc.envelopes[0].type()) - pc.envelopes += ("qresolution",) - self.assertEqual(("qresolution", "scale"), pc.usedenvelopetypes) - self.assertTrue( - all([isinstance(e, PDFEnvelope) for e in pc.envelopes]) - ) - return - - -# def test_pdf(self): -# """check PDFCalculator.pdf -# """ -# return - -# def test_getRDF(self): -# """check PDFCalculator.rdf -# """ -# return - -# def test_getRadiationType(self): -# """check PDFCalculator.getRadiationType() -# """ -# return - -# def test_rgrid(self): -# """check PDFCalculator.rgrid -# """ -# return - -# def test_setScatteringFactorTable(self): -# """check PDFCalculator.setScatteringFactorTable() -# """ -# return - -# End of class TestPDFCalculator - -# ---------------------------------------------------------------------------- - - -class TestFFTRoutines(unittest.TestCase): - - def test_fft_conversions(self): - """Verify conversions of arguments in fftgtof function.""" - fnipf2 = datafile("Ni-fit.fgr") - data = numpy.loadtxt(fnipf2) - dr = 0.01 - fq0, dq0 = fftgtof(data[:, 1], dr) - fq1, dq1 = fftgtof(data[:, 1].copy(), dr) - fq2, dq2 = fftgtof(list(data[:, 1]), dr) - self.assertTrue(numpy.array_equal(fq0, fq1)) - self.assertTrue(numpy.array_equal(fq0, fq2)) - self.assertEqual(dq0, dq1) - self.assertEqual(dq0, dq2) - return - - def test_fft_roundtrip(self): - """Check if forward and inverse transformation recover the - input.""" - fnipf2 = datafile("Ni-fit.fgr") - g0 = numpy.loadtxt(fnipf2, usecols=(1,)) - dr0 = 0.01 - fq, dq = fftgtof(g0, dr0) - g1, dr1 = fftftog(fq, dq) - self.assertAlmostEqual(dr0, dr1, 12) - self.assertTrue(numpy.allclose(g0, g1[: g0.size])) - return - - -# End of class TestFFTRoutines - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_pdfenvelope.py b/tests/test_pdfenvelope.py deleted file mode 100644 index ff8d95a6..00000000 --- a/tests/test_pdfenvelope.py +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for the PDFEnvelope class from -diffpy.srreal.pdfcalculator.""" - - -import pickle -import unittest - -import numpy -from testutils import pickle_with_attr - -from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator -from diffpy.srreal.pdfenvelope import ( - PDFEnvelope, - QResolutionEnvelope, - ScaleEnvelope, - SphericalShapeEnvelope, - StepCutEnvelope, - makePDFEnvelope, -) - -# ---------------------------------------------------------------------------- - - -class TestPDFEnvelope(unittest.TestCase): - - def setUp(self): - self.fstepcut = PDFEnvelope.createByType("stepcut") - self.fstepcut.stepcut = 5 - self.fscale = PDFEnvelope.createByType("scale") - return - - def tearDown(self): - PDFEnvelope._deregisterType("parabolaenvelope") - return - - def test___init__(self): - """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__()""" - 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) - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFEnvelope().__call__, 37) - self.assertEqual(0.0, self.fstepcut(10)) - self.assertEqual(1.0, self.fstepcut(3.45)) - ycheck = numpy.array(17 * [1] + 14 * [0]) - self.assertTrue(numpy.array_equal(ycheck, self.fstepcut(x))) - self.assertTrue(numpy.array_equal(ycheck, self.fstepcut(xb))) - self.assertEqual(1.0, self.fscale(3.45)) - self.assertEqual(1.0, self.fscale(345)) - self.assertTrue(numpy.array_equal(numpy.ones_like(x), self.fscale(x))) - self.fscale.scale = -2 - self.assertEqual(-2.0, self.fscale(3.5)) - return - - def test_clone(self): - """Check PDFEnvelope.clone.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFEnvelope().clone) - self.fstepcut.stepcut = 17 - e2 = self.fstepcut.clone() - self.assertEqual("stepcut", e2.type()) - self.assertEqual(17.0, e2.stepcut) - self.assertEqual(17.0, e2._getDoubleAttr("stepcut")) - return - - def test_create(self): - """Check PDFEnvelope.create.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFEnvelope().create) - self.assertEqual("stepcut", self.fstepcut.create().type()) - self.assertEqual("scale", self.fscale.create().type()) - self.fstepcut.stepcut = 17 - self.assertEqual(0.0, self.fstepcut.create().stepcut) - return - - def test_type(self): - """Check PDFEnvelope.type.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PDFEnvelope().type) - self.assertEqual("stepcut", self.fstepcut.type()) - self.assertEqual("scale", self.fscale.type()) - return - - def test_createByType(self): - """Check PDFEnvelope.createByType()""" - self.assertRaises( - ValueError, PDFEnvelope.createByType, "notregistered" - ) - return - - def test_getRegisteredTypes(self): - """Check PDFEnvelope.getRegisteredTypes.""" - regtypes = PDFEnvelope.getRegisteredTypes() - self.assertTrue(2 <= len(regtypes)) - self.assertTrue("stepcut" in regtypes) - self.assertTrue("scale" in regtypes) - return - - def test_pickling(self): - """Check pickling and unpickling of PDFEnvelope.""" - stp = self.fstepcut - stp.stepcut = 11 - stp2 = pickle.loads(pickle.dumps(stp)) - self.assertEqual("stepcut", stp2.type()) - self.assertEqual(11, stp2.stepcut) - self.assertEqual(11, stp2._getDoubleAttr("stepcut")) - return - - def test_makePDFEnvelope(self): - """Check the makePDFEnvelope wrapper.""" - pbl = makePDFEnvelope( - "parabolaenvelope", parabola_envelope, a=1, b=2, c=3 - ) - self.assertEqual(3, pbl(0)) - self.assertEqual(6, pbl(1)) - self.assertEqual(11, pbl(2)) - pbl.b = 0 - self.assertEqual([7, 3, 28], [pbl(x) for x in [-2, 0, 5]]) - pbl2 = pbl.clone() - self.assertEqual(1, pbl2.a) - self.assertEqual(0, pbl2.b) - self.assertEqual(3, pbl2.c) - self.assertEqual([7, 3, 28], [pbl2(x) for x in [-2, 0, 5]]) - pbl3 = PDFEnvelope.createByType("parabolaenvelope") - self.assertEqual(1, pbl3.a) - self.assertEqual(2, pbl3.b) - self.assertEqual(3, pbl3.c) - pbl3.a = 0 - pbl3.foo = "asdf" - pbl3cp = pickle.loads(pickle.dumps(pbl3)) - self.assertEqual(0, pbl3cp.a) - self.assertEqual("asdf", pbl3cp.foo) - return - - def test_picking_owned(self): - """Verify pickling of envelopes owned by PDF calculators.""" - pbl = makePDFEnvelope( - "parabolaenvelope", parabola_envelope, a=1, b=2, c=3 - ) - pbl.a = 7 - pbl.foobar = "asdf" - pc = PDFCalculator() - pc.envelopes = (pbl,) - dbpc = DebyePDFCalculator() - dbpc.envelopes = (pbl,) - self.assertIs(pbl, pc.envelopes[0]) - self.assertIs(pbl, dbpc.envelopes[0]) - pc.addEnvelope(self.fscale) - dbpc.addEnvelope(self.fscale) - self.fscale.scale = 3.5 - self.assertEqual(3.5, pc.scale) - self.assertEqual(3.5, dbpc.scale) - pc2 = pickle.loads(pickle.dumps(pc)) - dbpc2 = pickle.loads(pickle.dumps(dbpc)) - self.assertEqual(3.5, pc2.scale) - self.assertEqual(3.5, dbpc2.scale) - pblcopies = [ - pc2.getEnvelope("parabolaenvelope"), - dbpc2.getEnvelope("parabolaenvelope"), - ] - for pbl2 in pblcopies: - self.assertEqual(7, pbl2.a) - self.assertEqual("asdf", pbl2.foobar) - self.assertEqual("parabolaenvelope", pbl2.type()) - return - - -# ---------------------------------------------------------------------------- - - -class TestQResolutionEnvelope(unittest.TestCase): - - def setUp(self): - self.evlp = QResolutionEnvelope() - return - - def test_type(self): - self.assertEqual("qresolution", self.evlp.type()) - self.assertTrue(hasattr(self.evlp, "qdamp")) - return - - def test_pickling(self): - evlp = self.evlp - evlp.qdamp = 3 - evlp2 = pickle.loads(pickle.dumps(evlp)) - self.assertEqual(QResolutionEnvelope, type(evlp2)) - self.assertEqual(3, evlp2.qdamp) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") - return - - -# ---------------------------------------------------------------------------- - - -class TestScaleEnvelope(unittest.TestCase): - - def setUp(self): - self.evlp = ScaleEnvelope() - return - - def test_type(self): - self.assertEqual("scale", self.evlp.type()) - self.assertTrue(hasattr(self.evlp, "scale")) - return - - def test_pickling(self): - evlp = self.evlp - evlp.scale = 3 - evlp2 = pickle.loads(pickle.dumps(evlp)) - self.assertEqual(ScaleEnvelope, type(evlp2)) - self.assertEqual(3, evlp2.scale) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") - return - - -# ---------------------------------------------------------------------------- - - -class TestSphericalShapeEnvelope(unittest.TestCase): - - def setUp(self): - self.evlp = SphericalShapeEnvelope() - return - - def test_type(self): - self.assertEqual("sphericalshape", self.evlp.type()) - self.assertTrue(hasattr(self.evlp, "spdiameter")) - return - - def test_pickling(self): - evlp = self.evlp - evlp.spdiameter = 3 - evlp2 = pickle.loads(pickle.dumps(evlp)) - self.assertEqual(SphericalShapeEnvelope, type(evlp2)) - self.assertEqual(3, evlp2.spdiameter) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") - return - - -# ---------------------------------------------------------------------------- - - -class TestStepCutEnvelope(unittest.TestCase): - - def setUp(self): - self.evlp = StepCutEnvelope() - return - - def test_type(self): - self.assertEqual("stepcut", self.evlp.type()) - self.assertTrue(hasattr(self.evlp, "stepcut")) - return - - def test_pickling(self): - evlp = self.evlp - evlp.stepcut = 3 - evlp2 = pickle.loads(pickle.dumps(evlp)) - self.assertEqual(StepCutEnvelope, type(evlp2)) - self.assertEqual(3, evlp2.stepcut) - self.assertRaises(RuntimeError, pickle_with_attr, evlp, foo="bar") - return - - -# ---------------------------------------------------------------------------- - - -def parabola_envelope(x, a, b, c): - "parabola function for wrapping by makePDFEnvelope" - return a * x**2 + b * x + c - - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_peakprofile.py b/tests/test_peakprofile.py deleted file mode 100644 index dfc59ed2..00000000 --- a/tests/test_peakprofile.py +++ /dev/null @@ -1,225 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for the PeakProfile classes from -diffpy.srreal.peakprofile.""" - - -import pickle -import unittest - -import numpy -from testutils import mod_structure, pickle_with_attr - -from diffpy.srreal.pdfcalculator import PDFCalculator -from diffpy.srreal.peakprofile import PeakProfile - -# ---------------------------------------------------------------------------- - - -class TestPeakProfile(unittest.TestCase): - - def setUp(self): - self.pkgauss = PeakProfile.createByType("gaussian") - self.pkcropped = PeakProfile.createByType("croppedgaussian") - return - - def tearDown(self): - return - - def test___init__(self): - """Check PeakProfile.__init__()""" - self.assertNotEqual(0.0, self.pkgauss.peakprecision) - self.assertEqual( - self.pkgauss.peakprecision, self.pkcropped.peakprecision - ) - self.pkgauss._setDoubleAttr("peakprecision", 0.01) - self.assertEqual(0.01, self.pkgauss.peakprecision) - return - - def test_create(self): - """Check PeakProfile.create.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PeakProfile().create) - self.assertEqual("gaussian", self.pkgauss.create().type()) - self.pkgauss.peakprecision = 0.007 - self.assertNotEqual(0.007, self.pkgauss.create().peakprecision) - return - - def test_clone(self): - """Check PeakProfile.clone.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PeakProfile().clone) - self.pkgauss.peakprecision = 0.0003 - pkg2 = self.pkgauss.clone() - self.assertEqual("gaussian", pkg2.type()) - self.assertEqual(0.0003, pkg2.peakprecision) - self.assertEqual(0.0003, pkg2._getDoubleAttr("peakprecision")) - return - - def test_type(self): - """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__()""" - ymx = self.pkgauss(0.0, 1) - yhalflo = self.pkgauss(-0.5, 1) - yhalfhi = self.pkgauss(-0.5, 1) - self.assertAlmostEqual(ymx, 2 * yhalflo) - self.assertAlmostEqual(ymx, 2 * yhalfhi) - self.assertEqual(0, self.pkcropped(10, 1)) - self.assertNotEqual(0, self.pkgauss(10, 1)) - return - - def test_ticker(self): - """Check PeakProfile.ticker()""" - from diffpy.srreal.eventticker import EventTicker - - et0 = EventTicker(self.pkgauss.ticker()) - self.pkgauss.peakprecision = 0.003 - et1 = self.pkgauss.ticker() - self.assertNotEqual(et0, et1) - self.assertTrue(et0 < et1) - return - - def test_ticker_override(self): - """Check method override for PeakProfile.ticker in a derived - class.""" - pkf = MySawTooth() - self.assertEqual(0, pkf.tcnt) - et0 = pkf.ticker() - self.assertEqual(1, pkf.tcnt) - et1 = PeakProfile.ticker(pkf) - self.assertEqual(1, pkf.tcnt) - self.assertEqual(et0, et1) - et0.click() - self.assertEqual(et0, et1) - # check that implicit ticker call from PDFCalculator is - # handled by the Python ticker override. - pc = PDFCalculator() - pc.peakprofile = pkf - pc.ticker() - self.assertEqual(2, pkf.tcnt) - return - - def test_getRegisteredTypes(self): - """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.""" - pkg = self.pkgauss - pkg.peakprecision = 0.0011 - pkg2 = pickle.loads(pickle.dumps(pkg)) - self.assertEqual("gaussian", pkg2.type()) - self.assertEqual(0.0011, pkg2.peakprecision) - self.assertEqual(0.0011, pkg2._getDoubleAttr("peakprecision")) - self.assertRaises(RuntimeError, pickle_with_attr, pkg, foo="bar") - pkc = self.pkcropped - self.assertRaises(RuntimeError, pickle_with_attr, pkc, foo="bar") - return - - -# ---------------------------------------------------------------------------- - - -class MySawTooth(PeakProfile): - "Helper class for testing PeakProfile." - - def type(self): - return "mysawtooth" - - def create(self): - return MySawTooth() - - def clone(self): - import copy - - return copy.copy(self) - - tcnt = 0 - - def ticker(self): - self.tcnt += 1 - return PeakProfile.ticker(self) - - def __call__(self, x, fwhm): - w = 1.0 * fwhm - rv = (1 - abs(x) / w) / (1.0 * w) - if rv < 0: - rv = 0 - return rv - - def xboundlo(self, fwhm): - return -fwhm - - def xboundhi(self, fwhm): - return +fwhm - - -# End of class MySawTooth - - -class TestPeakProfileOwner(unittest.TestCase): - - def setUp(self): - MySawTooth()._registerThisType() - self.pc = PDFCalculator() - self.pc.peakprofile = "mysawtooth" - self.pkf = self.pc.peakprofile - self.pkf.peakprecision = 0.0017 - return - - def tearDown(self): - PeakProfile._deregisterType(self.pkf.type()) - return - - def test_pkftype(self): - """Check type of the owned PeakProfile instance.""" - self.assertEqual("mysawtooth", self.pc.peakprofile.type()) - return - - def test_custom_peakprofile(self): - "Check if our MySawTooth is indeed applied." - c2 = mod_structure.Structure(2 * [mod_structure.Atom("C")]) - c2.z = [0, 1] - c2.Uisoequiv = 0.01 - r, g = self.pc(c2) - k = g.argmax() - self.assertEqual(1, r[k]) - self.assertTrue(numpy.allclose(numpy.diff(g[k - 5 : k], 2), 0)) - self.assertTrue(numpy.allclose(numpy.diff(g[k : k + 5], 2), 0)) - pkf2 = self.pc.peakprofile.clone() - self.assertTrue(isinstance(pkf2, MySawTooth)) - self.assertEqual(0.0017, pkf2.peakprecision) - return - - def test_pickling(self): - """Check pickling of an owned PeakProfile instance.""" - pc1 = pickle.loads(pickle.dumps(self.pc)) - self.pkf.peakprecision = 0.0003 - self.pkf.foo = "bar" - pc2 = pickle.loads(pickle.dumps(self.pc)) - self.assertEqual("mysawtooth", pc1.peakprofile.type()) - self.assertEqual(0.0017, pc1.peakprofile.peakprecision) - self.assertEqual(0.0017, pc1.peakprecision) - self.assertFalse(hasattr(pc1.peakprofile, "foo")) - self.assertEqual("mysawtooth", pc2.peakprofile.type()) - self.assertEqual(0.0003, pc2.peakprofile.peakprecision) - self.assertEqual(0.0003, pc2.peakprecision) - self.assertEqual("bar", pc2.peakprofile.foo) - return - - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_peakwidthmodel.py b/tests/test_peakwidthmodel.py deleted file mode 100644 index 2b5bd853..00000000 --- a/tests/test_peakwidthmodel.py +++ /dev/null @@ -1,297 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for the PeakWidthModel classes from -diffpy.srreal.peakwidthmodel.""" - - -import pickle -import unittest - -from testutils import loadDiffPyStructure - -from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator -from diffpy.srreal.peakwidthmodel import ( - DebyeWallerPeakWidth, - JeongPeakWidth, - PeakWidthModel, -) -from diffpy.srreal.structureadapter import createStructureAdapter - -# ---------------------------------------------------------------------------- - - -class TestPeakWidthModel(unittest.TestCase): - - tio2stru = None - tio2adpt = None - - def setUp(self): - self.pwconst = PeakWidthModel.createByType("constant") - self.pwconst.width = 2 - if self.tio2stru is None: - self.tio2stru = loadDiffPyStructure("rutile.cif") - self.tio2adpt = createStructureAdapter(self.tio2stru) - return - - def tearDown(self): - return - - def _genbonds(self, rmin, rmax): - "Return ready-to-use BondGenerator for rutile." - bnds = self.tio2adpt.createBondGenerator() - bnds.setRmin(rmin) - bnds.setRmax(rmax) - bnds.rewind() - return bnds - - def test___init__(self): - """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.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PeakWidthModel().create) - self.assertEqual("constant", self.pwconst.create().type()) - self.pwconst.width = 17 - self.assertEqual(0.0, self.pwconst.create().width) - return - - def test_clone(self): - """Check PeakWidthModel.clone.""" - # this is a virtual method in the base class - self.assertRaises(RuntimeError, PeakWidthModel().clone) - self.pwconst.width = 17 - pwc2 = self.pwconst.clone() - self.assertEqual("constant", pwc2.type()) - self.assertEqual(17.0, pwc2.width) - self.assertEqual(17.0, pwc2._getDoubleAttr("width")) - return - - def test_type(self): - """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()""" - pwm = PeakWidthModel() - bnds = self._genbonds(1, 2) - self.assertRaises(RuntimeError, pwm.calculate, bnds) - self.assertEqual(2.0, self.pwconst.calculate(bnds)) - return - - def test_isowidths(self): - """Check ConstantPeakWidth properties bisowidth, uisowidth.""" - from numpy import pi - - cnpw = self.pwconst - dwpw = DebyeWallerPeakWidth() - bnds = self._genbonds(1, 2) - w0 = dwpw.calculate(bnds) - cnpw.uisowidth = self.tio2stru[[0, -1]].Uisoequiv.mean() - self.assertAlmostEqual(w0, cnpw.calculate(bnds), 12) - self.assertAlmostEqual(cnpw.bisowidth, 8 * pi**2 * cnpw.uisowidth, 12) - return - - def test_maxWidth(self): - """Check PeakWidthModel.maxWidth()""" - self.assertRaises( - RuntimeError, PeakWidthModel().maxWidth, self.tio2adpt, 0, 10 - ) - 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()""" - from diffpy.srreal.eventticker import EventTicker - - et0 = EventTicker(self.pwconst.ticker()) - self.pwconst.width = 3 - et1 = self.pwconst.ticker() - self.assertNotEqual(et0, et1) - self.assertTrue(et0 < et1) - return - - def test_ticker_override(self): - """Check PeakWidthModel.ticker override in a Python-derived - class.""" - pwm = MyPWM() - self.assertEqual(0, pwm.tcnt) - et0 = pwm.ticker() - self.assertEqual(1, pwm.tcnt) - et1 = PeakWidthModel.ticker(pwm) - self.assertEqual(1, pwm.tcnt) - self.assertEqual(et0, et1) - et0.click() - self.assertEqual(et0, et1) - # check that implicit ticker call from PDFCalculator is - # handled by the Python ticker override. - pc = PDFCalculator() - pc.peakwidthmodel = pwm - pc.ticker() - self.assertEqual(2, pwm.tcnt) - return - - def test_getRegisteredTypes(self): - """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.""" - pwc = self.pwconst - pwc.width = 11 - pwc2 = pickle.loads(pickle.dumps(pwc)) - self.assertEqual("constant", pwc2.type()) - self.assertEqual(11, pwc2.width) - self.assertEqual(11, pwc2._getDoubleAttr("width")) - return - - -# ---------------------------------------------------------------------------- - - -class TestDebyeWallerPeakWidth(unittest.TestCase): - - def setUp(self): - self.pwm = DebyeWallerPeakWidth() - return - - def test_type(self): - """Check DebyeWallerPeakWidth.type.""" - self.assertEqual("debye-waller", self.pwm.type()) - self.assertEqual(0, len(self.pwm._namesOfDoubleAttributes())) - return - - def test_pickling(self): - """Check pickling of DebyeWallerPeakWidth class.""" - self.assertEqual("debye-waller", self.pwm.type()) - pwm = self.pwm - pwm2 = pickle.loads(pickle.dumps(pwm)) - self.assertEqual(DebyeWallerPeakWidth, type(pwm2)) - return - - -# ---------------------------------------------------------------------------- - - -class TestJeongPeakWidth(unittest.TestCase): - - def setUp(self): - self.pwm = JeongPeakWidth() - return - - def test_type(self): - """Check JeongPeakWidth.type.""" - self.assertEqual("jeong", self.pwm.type()) - self.assertTrue(hasattr(self.pwm, "delta1")) - self.assertTrue(hasattr(self.pwm, "delta2")) - self.assertTrue(hasattr(self.pwm, "qbroad")) - return - - def test_pickling(self): - """Check pickling of the DebyeWallerPeakWidth class.""" - pwm = self.pwm - pwm.delta1 = 1 - pwm.delta2 = 2 - pwm.qbroad = 3 - pwm2 = pickle.loads(pickle.dumps(pwm)) - self.assertEqual(JeongPeakWidth, type(pwm2)) - self.assertEqual(1, pwm2.delta1) - self.assertEqual(2, pwm2.delta2) - self.assertEqual(3, pwm2.qbroad) - return - - -# ---------------------------------------------------------------------------- - - -class MyPWM(PeakWidthModel): - "Helper class for testing PeakWidthModelOwner." - - pwmscale = 1.5 - - def __init__(self): - PeakWidthModel.__init__(self) - self._registerDoubleAttribute("pwmscale") - return - - def type(self): - return "mypwm" - - def create(self): - return MyPWM() - - def clone(self): - import copy - - return copy.copy(self) - - def calculate(self, bnds): - return self.pwmscale * bnds.msd() - - tcnt = 0 - - def ticker(self): - self.tcnt += 1 - return PeakWidthModel.ticker(self) - - -# End of class MyPWM - - -class TestPeakWidthOwner(unittest.TestCase): - - @classmethod - def tearDownClass(cls): - assert "mypwm" not in PeakWidthModel.getRegisteredTypes() - return - - def setUp(self): - self.pc = PDFCalculator() - self.dbpc = DebyePDFCalculator() - self.pwm = MyPWM() - self.pc.peakwidthmodel = self.pwm - self.dbpc.peakwidthmodel = self.pwm - return - - def test_pwmtype(self): - """Check type of the owned PeakWidthModel instance.""" - self.assertEqual("mypwm", self.pc.peakwidthmodel.type()) - self.assertEqual("mypwm", self.dbpc.peakwidthmodel.type()) - return - - def test_pickling(self): - """Check pickling of an owned PeakWidthModel instance.""" - pc1 = pickle.loads(pickle.dumps(self.pc)) - self.pwm.pwmscale = 3 - pc2 = pickle.loads(pickle.dumps(self.pc)) - self.assertEqual("mypwm", pc1.peakwidthmodel.type()) - self.assertEqual(1.5, pc1.peakwidthmodel.pwmscale) - self.assertEqual(1.5, pc1.pwmscale) - self.assertEqual("mypwm", pc2.peakwidthmodel.type()) - self.assertEqual(3, pc2.peakwidthmodel.pwmscale) - self.assertEqual(3, pc2.pwmscale) - dbpc2 = pickle.loads(pickle.dumps(self.dbpc)) - self.assertEqual(3, dbpc2.peakwidthmodel.pwmscale) - self.assertEqual(3, dbpc2.pwmscale) - return - - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_scatteringfactortable.py b/tests/test_scatteringfactortable.py deleted file mode 100644 index 097d4129..00000000 --- a/tests/test_scatteringfactortable.py +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.scatteringfactortable.""" - - -import pickle -import unittest - -import numpy -from testutils import pickle_with_attr - -from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator -from diffpy.srreal.scatteringfactortable import ( - ScatteringFactorTable, - SFTElectron, - SFTElectronNumber, - SFTNeutron, - SFTXray, -) - -# ---------------------------------------------------------------------------- - - -class LocalTable(ScatteringFactorTable): - def clone(self): - import copy - - return copy.copy(self) - - def create(self): - return LocalTable() - - def _standardLookup(self, smbl, q): - return q + 1 - - def radiationType(self): - return "LTB" - - def type(self): - return "localtable" - - def ticker(self): - self.tcnt += 1 - return ScatteringFactorTable.ticker(self) - - tcnt = 0 - - -# ---------------------------------------------------------------------------- - - -class TestScatteringFactorTable(unittest.TestCase): - - def setUp(self): - self.sftx = ScatteringFactorTable.createByType("X") - self.sftn = ScatteringFactorTable.createByType("N") - LocalTable()._registerThisType() - return - - def tearDown(self): - ScatteringFactorTable._deregisterType("localtable") - return - - def test_class_registry(self): - """Check if instances are aliased by radiationType().""" - ltb = ScatteringFactorTable.createByType("LTB") - self.assertTrue(type(ltb) is LocalTable) - ltb2 = ScatteringFactorTable.createByType("localtable") - self.assertTrue(type(ltb2) is LocalTable) - return - - def test_ticker(self): - """Check ScatteringFactorTable.ticker()""" - from diffpy.srreal.eventticker import EventTicker - - et0 = EventTicker(self.sftx.ticker()) - self.sftx.setCustomAs("D", "H") - et1 = self.sftx.ticker() - self.assertNotEqual(et0, et1) - self.assertTrue(et0 < et1) - return - - def test_ticker_override(self): - """Check Python override of ScatteringFactorTable.ticker.""" - from diffpy.srreal.pdfcalculator import PDFCalculator - - lsft = LocalTable() - self.assertEqual(0, lsft.tcnt) - et0 = lsft.ticker() - self.assertEqual(1, lsft.tcnt) - et1 = ScatteringFactorTable.ticker(lsft) - self.assertEqual(1, lsft.tcnt) - self.assertEqual(et0, et1) - et0.click() - self.assertEqual(et0, et1) - # check that implicit ticker call from PDFCalculator is - # handled by Python override of the ticker method. - pc = PDFCalculator() - pc.scatteringfactortable = lsft - pc.ticker() - self.assertEqual(2, lsft.tcnt) - return - - def test_pickling(self): - """Check pickling of ScatteringFactorTable instances.""" - self.assertEqual(0, len(self.sftx.getCustomSymbols())) - self.sftx.setCustomAs("Na", "Na", 123) - self.sftx.setCustomAs("Calias", "C") - self.assertEqual(2, len(self.sftx.getCustomSymbols())) - sftx1 = pickle.loads(pickle.dumps(self.sftx)) - self.assertEqual(2, len(sftx1.getCustomSymbols())) - self.assertAlmostEqual(123, sftx1.lookup("Na"), 12) - self.assertEqual(self.sftx.lookup("C"), sftx1.lookup("Calias")) - self.assertEqual(self.sftx.type(), sftx1.type()) - pwa = pickle_with_attr - self.assertRaises(RuntimeError, pwa, SFTXray(), foo="bar") - self.assertRaises(RuntimeError, pwa, SFTElectron(), foo="bar") - self.assertRaises(RuntimeError, pwa, SFTNeutron(), foo="bar") - self.assertRaises(RuntimeError, pwa, SFTElectronNumber(), foo="bar") - return - - def test_picking_owned(self): - """Verify pickling of envelopes owned by PDF calculators.""" - pc = PDFCalculator() - dbpc = DebyePDFCalculator() - ltb = LocalTable() - ltb.setCustomAs("Na", "Na", 37) - ltb.foo = "bar" - pc.scatteringfactortable = ltb - dbpc.scatteringfactortable = ltb - self.assertIs(ltb, pc.scatteringfactortable) - self.assertIs(ltb, dbpc.scatteringfactortable) - pc2 = pickle.loads(pickle.dumps(pc)) - dbpc2 = pickle.loads(pickle.dumps(dbpc)) - self.assertEqual("localtable", pc2.scatteringfactortable.type()) - self.assertEqual("localtable", dbpc2.scatteringfactortable.type()) - self.assertEqual(37, pc2.scatteringfactortable.lookup("Na")) - self.assertEqual(37, dbpc2.scatteringfactortable.lookup("Na")) - self.assertEqual("bar", pc2.scatteringfactortable.foo) - self.assertEqual("bar", dbpc2.scatteringfactortable.foo) - return - - def test_pickling_derived(self): - """Check pickling of a derived classes.""" - lsft = LocalTable() - self.assertEqual(3, lsft._standardLookup("Na", 2)) - self.assertEqual(set(), lsft.getCustomSymbols()) - lsft.foobar = "asdf" - lsft.setCustomAs("Na", "Na", 123) - self.assertEqual(1, len(lsft.getCustomSymbols())) - lsft1 = pickle.loads(pickle.dumps(lsft)) - self.assertEqual(1, len(lsft1.getCustomSymbols())) - self.assertAlmostEqual(123, lsft1.lookup("Na"), 12) - self.assertEqual("asdf", lsft1.foobar) - self.assertEqual(lsft.type(), lsft1.type()) - self.assertEqual(3, lsft1._standardLookup("Cl", 2)) - self.assertEqual(1, lsft1.lookup("H")) - return - - def test_derived_create(self): - """Check override of ScatteringFactorTable.create in Python - class.""" - lsft = LocalTable() - lsft.setCustomAs("Xy", "Na") - lsft2 = lsft.create() - self.assertTrue(isinstance(lsft2, LocalTable)) - self.assertEqual(set(), lsft2.getCustomSymbols()) - return - - def test_derived_clone(self): - """Check override of ScatteringFactorTable.clone in Python - class.""" - lsft = LocalTable() - lsft.setCustomAs("Xy", "Na") - lsft2 = lsft.clone() - self.assertTrue(isinstance(lsft2, LocalTable)) - self.assertEqual(set(["Xy"]), lsft2.getCustomSymbols()) - return - - def test_lookup(self): - """Check ScatteringFactorTable.lookup handling of array - arguments.""" - qa = numpy.linspace(0, 50) - qb = numpy.array([(x, 0.0) for x in qa])[:, 0] - self.assertTrue(qb.strides > qa.strides) - sftx = self.sftx - fmn0 = numpy.array([sftx.lookup("Mn", x) for x in qa]) - self.assertTrue(numpy.array_equal(fmn0, sftx.lookup("Mn", qa))) - self.assertTrue(numpy.array_equal(fmn0, sftx.lookup("Mn", qb))) - self.assertTrue( - numpy.array_equal( - fmn0.reshape(5, 10), sftx.lookup("Mn", qa.reshape(5, 10)) - ) - ) - self.assertTrue( - numpy.array_equal( - fmn0.reshape(5, 2, 5), sftx.lookup("Mn", qa.reshape(5, 2, 5)) - ) - ) - self.assertTrue(numpy.array_equal(fmn0, sftx.lookup("Mn", list(qa)))) - self.assertRaises(TypeError, sftx.lookup, "Na", "asdf") - self.assertRaises(TypeError, sftx.lookup, "Na", {}) - return - - -# End of class TestScatteringFactorTable - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_sfaverage.py b/tests/test_sfaverage.py deleted file mode 100644 index bff8c800..00000000 --- a/tests/test_sfaverage.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.sfaverage.""" - - -import unittest - -import numpy -import pytest -from testutils import loadDiffPyStructure, loadObjCrystCrystal - -from diffpy.srreal.scatteringfactortable import ScatteringFactorTable -from diffpy.srreal.sfaverage import SFAverage - -# ---------------------------------------------------------------------------- - - -class TestSFAverage(unittest.TestCase): - - def setUp(self): - self.sftx = ScatteringFactorTable.createByType("X") - self.sftn = ScatteringFactorTable.createByType("N") - return - - def tearDown(self): - return - - def test_fromStructure_CdSe(self): - """Check SFAverage.fromStructure() for CdSe.""" - cdse = loadDiffPyStructure("CdSe_cadmoselite.cif") - sfavg = SFAverage.fromStructure(cdse, self.sftx) - fcd = self.sftx.lookup("Cd") - fse = self.sftx.lookup("Se") - self.assertTrue(isinstance(sfavg.f1sum, float)) - self.assertAlmostEqual(0.5 * (fcd + fse), sfavg.f1avg) - self.assertAlmostEqual(0.5 * (fcd**2 + fse**2), sfavg.f2avg) - self.assertEqual(4, sfavg.count) - self.assertEqual(cdse.composition, sfavg.composition) - qa = numpy.arange(0, 25, 0.1) - sfavg2 = SFAverage.fromStructure(cdse, self.sftx, qa) - self.assertTrue(isinstance(sfavg2.f1sum, numpy.ndarray)) - self.assertNotEqual(sfavg2.f1sum[0], sfavg2.f1sum[-1]) - self.assertEqual(sfavg.f1sum, sfavg2.f1sum[0]) - self.assertEqual(sfavg.f2sum, sfavg2.f2sum[0]) - sfavg3 = SFAverage.fromStructure(cdse, self.sftn, qa) - self.assertEqual(sfavg3.f1sum[0], sfavg3.f1sum[-1]) - sfavg4 = SFAverage.fromStructure(cdse, "N", qa) - self.assertTrue(numpy.array_equal(sfavg3.f1sum, sfavg4.f1sum)) - self.assertTrue(numpy.array_equal(sfavg3.f2sum, sfavg4.f2sum)) - sfavg5 = SFAverage.fromStructure(cdse, "EN", qa) - self.assertFalse(numpy.array_equal(sfavg3.f1sum, sfavg5.f1sum)) - self.assertRaises( - TypeError, SFAverage.fromStructure, "notastructure", self.sftx - ) - self.assertRaises(ValueError, SFAverage.fromStructure, cdse, "invalid") - return - - def test_fromComposition(self): - """Check SFAverage.fromComposition()""" - sfavg1 = SFAverage.fromComposition({"Na": 1, "Cl": 1}, self.sftx) - fm = ["Na", 0.25, "Cl", 0.75, "Cl", 0.25, "Na", 0.5, "Na", 0.25] - smblcnts = zip(fm[0::2], fm[1::2]) - sfavg2 = SFAverage.fromComposition(smblcnts, self.sftx) - self.assertEqual(sfavg1.f1sum, sfavg2.f1sum) - self.assertEqual(sfavg1.f2sum, sfavg2.f2sum) - self.assertEqual(sfavg1.count, sfavg2.count) - sfempty = SFAverage.fromComposition([], self.sftx) - self.assertEqual(0, sfempty.f1avg) - self.assertEqual(0, sfempty.f2avg) - self.assertEqual(0, sfempty.count) - return - - -# End of class TestSFAverage - -# ---------------------------------------------------------------------------- - - -class TestSFAverageObjCryst(unittest.TestCase): - - @pytest.fixture(autouse=True) - def _check_pyobjcryst(self, has_pyobjcryst, _msg_nopyobjcryst): - if not has_pyobjcryst: - pytest.skip(_msg_nopyobjcryst) - - def setUp(self): - self.sftx = ScatteringFactorTable.createByType("X") - return - - def tearDown(self): - return - - def test_from_rutile(self): - """Check SFAverage.fromStructure for pyobjcryst Crystal of - rutile.""" - rutile = loadObjCrystCrystal("rutile.cif") - qa = numpy.arange(0, 25, 0.1) - sfavg = SFAverage.fromStructure(rutile, self.sftx, qa) - fti = self.sftx.lookup("Ti", qa) - fo = self.sftx.lookup("O", qa) - self.assertTrue(numpy.allclose((fti + 2 * fo) / 3.0, sfavg.f1avg)) - fti2, fo2 = fti**2, fo**2 - self.assertTrue(numpy.allclose((fti2 + 2 * fo2) / 3.0, sfavg.f2avg)) - self.assertEqual(6, sfavg.count) - - -# End of class TestSFAverageObjCryst - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_structureadapter.py b/tests/test_structureadapter.py deleted file mode 100644 index 910faae8..00000000 --- a/tests/test_structureadapter.py +++ /dev/null @@ -1,675 +0,0 @@ -#!/usr/bin/env python - -"""Unit tests for diffpy.srreal.structureadapter.""" - - -import pickle -import unittest - -import numpy -import pytest -from testutils import ( - DerivedAtomicStructureAdapter, - DerivedCrystalStructureAdapter, - DerivedPeriodicStructureAdapter, - DerivedStructureAdapter, - loadCrystalStructureAdapter, - loadDiffPyStructure, - loadObjCrystCrystal, -) - -from diffpy.srreal.pdfcalculator import PDFCalculator -from diffpy.srreal.structureadapter import ( - Atom, - AtomicStructureAdapter, - CrystalStructureAdapter, - PeriodicStructureAdapter, - StructureAdapter, - createStructureAdapter, - nometa, - nosymmetry, -) - -# ---------------------------------------------------------------------------- - - -class TestRoutines(unittest.TestCase): - - def setUp(self): - self.nickel = loadDiffPyStructure("Ni.stru") - return - - def test_createStructureAdapter(self): - """Check createStructureAdapter() routine.""" - adpt = createStructureAdapter(self.nickel) - self.assertEqual(4, adpt.countSites()) - self.assertTrue(False is adpt.siteAnisotropy(0)) - self.assertTrue(isinstance(adpt, StructureAdapter)) - adpt1 = createStructureAdapter(adpt) - self.assertTrue(adpt is adpt1) - self.assertRaises(TypeError, createStructureAdapter, 77) - self.assertRaises(TypeError, createStructureAdapter, list(range(8))) - self.assertRaises(TypeError, createStructureAdapter, None) - self.assertRaises(TypeError, createStructureAdapter, {}) - return - - def test_createStructureAdapterTypes(self): - """Check types returned by conversion from diffpy.structure.""" - from diffpy.srreal.structureconverters import ( - DiffPyStructureAtomicAdapter, - DiffPyStructurePeriodicAdapter, - ) - - adpt = createStructureAdapter(self.nickel) - self.assertTrue(type(adpt) is DiffPyStructurePeriodicAdapter) - self.nickel.pdffit = None - adpt1 = createStructureAdapter(self.nickel) - self.assertTrue(type(adpt1) is PeriodicStructureAdapter) - self.nickel.lattice.setLatPar(1, 1, 1, 90, 90, 90) - adpt2 = createStructureAdapter(self.nickel) - self.assertTrue(type(adpt2) is AtomicStructureAdapter) - self.nickel.pdffit = dict(scale=1) - adpt3 = createStructureAdapter(self.nickel) - self.assertTrue(type(adpt3) is DiffPyStructureAtomicAdapter) - return - - def test_createStructureAdapter_int64_occupancy(self): - """Check Structure conversion when occupany is of numpy.int64 - type.""" - self.nickel[0].occupancy = numpy.int64(0) - self.nickel[1].occupancy = numpy.int64(1) - adpt = createStructureAdapter(self.nickel) - self.assertEqual(0.0, adpt.siteOccupancy(0)) - self.assertEqual(1.0, adpt.siteOccupancy(1)) - return - - def test_pickling(self): - """Check pickling of StructureAdapter instances.""" - adpt = createStructureAdapter(self.nickel) - adpt1 = pickle.loads(pickle.dumps(adpt)) - self.assertFalse(adpt is adpt1) - self.assertEqual(adpt.countSites(), adpt1.countSites()) - self.assertEqual(adpt.totalOccupancy(), adpt1.totalOccupancy()) - self.assertEqual(adpt.siteAtomType(1), adpt1.siteAtomType(1)) - self.assertTrue( - numpy.array_equal( - adpt.siteCartesianPosition(1), adpt1.siteCartesianPosition(1) - ) - ) - self.assertEqual(adpt.siteMultiplicity(1), adpt1.siteMultiplicity(1)) - self.assertEqual(adpt.siteOccupancy(1), adpt1.siteOccupancy(1)) - self.assertTrue(adpt.siteAnisotropy(1) is adpt1.siteAnisotropy(1)) - self.assertTrue( - numpy.array_equal( - adpt.siteCartesianUij(1), adpt1.siteCartesianUij(1) - ) - ) - return - - def test_pickle_nonwrapped(self): - """Check if pickling works for non-wrapped C++ object.""" - from diffpy.srreal.structureadapter import EMPTY as e0 - - spkl = pickle.dumps(e0) - e1 = pickle.loads(spkl) - self.assertEqual(0, e1.countSites()) - return - - -# End of class TestStructureAdapter - -# ---------------------------------------------------------------------------- - - -class TestDerivedAdapter(unittest.TestCase): - "Check functionality in a Python-derived StructureAdapter class." - - DerivedCls = DerivedStructureAdapter - - def setUp(self): - self.adpt = self.DerivedCls() - return - - def test__customPQConfig(self): - """Check if DerivedCls._customPQConfig gets called.""" - self.assertEqual(0, self.adpt.cpqcount) - pc = PDFCalculator() - pc.setStructure(self.adpt) - self.assertEqual(1, self.adpt.cpqcount) - pc(self.adpt) - self.assertEqual(2, self.adpt.cpqcount) - return - - def test_pickling(self): - """Check pickling of DerivedCls instances.""" - self.adpt.cpqcount = 1 - adpt1 = pickle.loads(pickle.dumps(self.adpt)) - self.assertTrue(self.DerivedCls is type(adpt1)) - self.assertFalse(self.adpt is adpt1) - self.assertEqual(1, adpt1.cpqcount) - pc = PDFCalculator() - pc.setStructure(adpt1) - self.assertEqual(2, adpt1.cpqcount) - pc(adpt1) - self.assertEqual(3, adpt1.cpqcount) - return - - -# End of class TestDerivedAdapter - - -class TestDerivedAtomicAdapter(TestDerivedAdapter): - DerivedCls = DerivedAtomicStructureAdapter - - -class TestDerivedPeriodicAdapter(TestDerivedAdapter): - DerivedCls = DerivedPeriodicStructureAdapter - - -class TestDerivedCrystalAdapter(TestDerivedAdapter): - DerivedCls = DerivedCrystalStructureAdapter - - -# ---------------------------------------------------------------------------- - - -class TestNoMeta(unittest.TestCase): - - def setUp(self): - self.nickel = loadDiffPyStructure("Ni.stru") - return - - def test_nometa(self): - """Check NoMetaStructureAdapter.""" - r0, g0 = PDFCalculator()(self.nickel) - ni1 = self.nickel.copy() - ni1.pdffit["scale"] = 2.0 - r1, g1 = PDFCalculator()(ni1) - self.assertTrue(numpy.array_equal(r0, r1)) - self.assertTrue(numpy.allclose(2 * g0, g1)) - ni1nm = nometa(ni1) - self.assertTrue(ni1nm is nometa(ni1nm)) - r1nm, g1nm = PDFCalculator()(ni1nm) - self.assertTrue(numpy.array_equal(r0, r1nm)) - self.assertTrue(numpy.allclose(g0, g1nm)) - ni2 = self.nickel.copy() - ni2.pdffit["delta2"] = 4 - r2, g2 = PDFCalculator()(ni2) - r2, g2nm = PDFCalculator()(nometa(ni2)) - self.assertFalse(numpy.allclose(g0, g2)) - self.assertTrue(numpy.allclose(g0, g2nm)) - adpt2 = createStructureAdapter(ni2) - ra2, ga2 = PDFCalculator()(adpt2) - ra2, ga2nm = PDFCalculator()(nometa(adpt2)) - self.assertTrue(numpy.allclose(g2, ga2)) - self.assertTrue(numpy.allclose(g0, ga2nm)) - return - - def test_nometa_pickling(self): - """Check pickling of the NoMetaStructureAdapter wrapper.""" - r0, g0 = PDFCalculator()(self.nickel) - ni1 = self.nickel.copy() - ni1.pdffit["scale"] = 2.0 - ni1nm = pickle.loads(pickle.dumps(nometa(ni1))) - self.assertFalse(ni1nm is ni1) - r1nm, g1nm = PDFCalculator()(ni1nm) - self.assertTrue(numpy.array_equal(r0, r1nm)) - self.assertTrue(numpy.array_equal(g0, g1nm)) - return - - def test_nometa_twice(self): - """Check that second call of nometa returns the same object.""" - adpt1 = nometa(self.nickel) - adpt2 = nometa(adpt1) - self.assertTrue(adpt1 is adpt2) - - -# End of class TestNoMeta - -# ---------------------------------------------------------------------------- - - -class TestNoSymmetry(unittest.TestCase): - - def setUp(self): - self.nickel = loadDiffPyStructure("Ni.stru") - return - - def test_nosymmetry(self): - """Check NoSymmetryStructureAdapter.""" - pdfc0 = PDFCalculator() - r0, g0 = pdfc0(self.nickel) - rdf0 = pdfc0.rdf - niuc = nosymmetry(self.nickel) - self.assertTrue(niuc is nosymmetry(niuc)) - pdfc1 = PDFCalculator() - r1, g1 = pdfc1(niuc) - self.assertTrue(numpy.array_equal(r0, r1)) - self.assertFalse(numpy.allclose(g0, g1)) - tail = r0 > 5.0 - self.assertTrue(numpy.allclose(0.0 * g1[tail], g1[tail])) - rdf0 = pdfc0.rdf - rdf1 = pdfc1.rdf - head = r0 < 3.0 - self.assertAlmostEqual(12.0, numpy.sum(rdf0[head] * pdfc0.rstep), 5) - self.assertAlmostEqual(3.0, numpy.sum(rdf1[head] * pdfc1.rstep), 5) - adpt0 = createStructureAdapter(self.nickel) - ra2, ga2 = PDFCalculator()(nosymmetry(adpt0)) - self.assertTrue(numpy.array_equal(r0, ra2)) - self.assertTrue(numpy.allclose(g1, ga2)) - return - - def test_nosymmetry_twice(self): - """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.""" - ni1ns = nosymmetry(self.nickel) - r1, g1 = PDFCalculator()(ni1ns) - ni2ns = pickle.loads(pickle.dumps(ni1ns)) - self.assertFalse(ni1ns is ni2ns) - r2, g2 = PDFCalculator()(ni2ns) - self.assertTrue(numpy.array_equal(r1, r2)) - self.assertTrue(numpy.array_equal(g1, g2)) - return - - -# End of class TestNoSymmetry - -# ---------------------------------------------------------------------------- - - -class TestPyObjCrystAdapter(unittest.TestCase): - - @pytest.fixture(autouse=True) - def _check_pyobjcryst(self, has_pyobjcryst, _msg_nopyobjcryst): - if not has_pyobjcryst: - pytest.skip(_msg_nopyobjcryst) - - def setUp(self): - rutile_crystal = loadObjCrystCrystal("TiO2_rutile-fit.cif") - self.rutile = createStructureAdapter(rutile_crystal) - return - - def test_objcryst_adapter(self): - """Check ObjCrystStructureAdapter for rutile.""" - self.assertEqual(2, self.rutile.countSites()) - self.assertEqual(6, self.rutile.totalOccupancy()) - self.assertEqual("Ti", self.rutile.siteAtomType(0)) - self.assertEqual("O", self.rutile.siteAtomType(1)) - self.assertTrue(True is self.rutile.siteAnisotropy(0)) - self.assertTrue(True is self.rutile.siteAnisotropy(1)) - self.assertTrue( - numpy.allclose( - numpy.diag([0.008698, 0.008698, 0.005492]), - self.rutile.siteCartesianUij(0), - ) - ) - self.assertTrue( - numpy.allclose( - numpy.diag([0.021733, 0.021733, 0.007707]), - self.rutile.siteCartesianUij(1), - ) - ) - return - - def test_objcryst_pickling(self): - """Check pickling of the NoSymmetryStructureAdapter wrapper.""" - r0, g0 = PDFCalculator()(self.rutile) - rutile1 = pickle.loads(pickle.dumps(self.rutile)) - self.assertFalse(self.rutile is rutile1) - r1, g1 = PDFCalculator()(rutile1) - self.assertTrue(numpy.array_equal(r0, r1)) - self.assertTrue(numpy.array_equal(g0, g1)) - return - - -# End of class TestPyObjCrystAdapter - -# ---------------------------------------------------------------------------- - - -class IndexRangeTests(object): - "Check error handling for site index arguments." - - AdptClass = None - - def setUp(self): - self.adpt = self.AdptClass() - return - - def test_siteAtomTypeIndex(self): - """Check out-of-range arguments in AdptClass.siteAtomType.""" - cnt = self.adpt.countSites() - self.assertRaises(IndexError, self.adpt.siteAtomType, cnt) - self.assertRaises(IndexError, self.adpt.siteAtomType, -1) - return - - def test_siteCartesianPositionIndex(self): - """Check out-of-range arguments in - AdptClass.siteCartesianPosition.""" - cnt = self.adpt.countSites() - self.assertRaises(IndexError, self.adpt.siteCartesianPosition, cnt) - self.assertRaises(IndexError, self.adpt.siteCartesianPosition, -1) - return - - def test_siteMultiplicityIndex(self): - """Check out-of-range arguments in - AdptClass.siteMultiplicity.""" - cnt = self.adpt.countSites() - self.assertRaises(IndexError, self.adpt.siteMultiplicity, cnt) - self.assertRaises(IndexError, self.adpt.siteMultiplicity, -1) - return - - def test_siteOccupancyIndex(self): - """Check out-of-range arguments in AdptClass.siteOccupancy.""" - cnt = self.adpt.countSites() - self.assertRaises(IndexError, self.adpt.siteOccupancy, cnt) - self.assertRaises(IndexError, self.adpt.siteOccupancy, -1) - return - - def test_siteAnisotropyIndex(self): - """Check out-of-range arguments in AdptClass.siteAnisotropy.""" - cnt = self.adpt.countSites() - self.assertRaises(IndexError, self.adpt.siteAnisotropy, cnt) - self.assertRaises(IndexError, self.adpt.siteAnisotropy, -1) - return - - def test_siteCartesianUijIndex(self): - """Check out-of-range arguments in - AdptClass.siteCartesianUij.""" - cnt = self.adpt.countSites() - self.assertRaises(IndexError, self.adpt.siteCartesianUij, cnt) - self.assertRaises(IndexError, self.adpt.siteCartesianUij, -1) - return - - -# End of class IndexRangeTests - -TestCase = unittest.TestCase - -# test index bounds for C++ classes - - -class TestAtomicAdapterIndexRange(IndexRangeTests, TestCase): - AdptClass = AtomicStructureAdapter - - -# No need to do index tests for PeriodicStructureAdapter as it does not -# override any of AtomicStructureAdapter site-access methods. -# CrystalStructureAdapter overrides siteMultiplicity so we'll -# test it here as well. - - -class TestCrystalAdapter(IndexRangeTests, TestCase): - AdptClass = CrystalStructureAdapter - - def test_expandLatticeAtom(self): - """Check CrystalStructureAdapter.expandLatticeAtom.""" - cdse = loadCrystalStructureAdapter("CdSe_cadmoselite.cif") - a = Atom() - a.xyz_cartn = (0.1, 0.13, 0.17) - asymsites = cdse.expandLatticeAtom(a) - self.assertTrue(type(asymsites) is list) - self.assertEqual(12, len(asymsites)) - self.assertEqual(12, cdse.countSymOps()) - return - - def test_getEquivalentAtoms(self): - """Check CrystalStructureAdapter.getEquivalentAtoms.""" - cdse = loadCrystalStructureAdapter("CdSe_cadmoselite.cif") - eqatoms0 = cdse.getEquivalentAtoms(0) - eqatoms1 = cdse.getEquivalentAtoms(1) - self.assertTrue(type(eqatoms1) is list) - self.assertEqual(2, len(eqatoms0)) - self.assertEqual(2, len(eqatoms1)) - self.assertTrue(all(a.atomtype == "Cd" for a in eqatoms0)) - self.assertTrue(all(a.atomtype == "Se" for a in eqatoms1)) - return - - -# ---------------------------------------------------------------------------- - - -class TestDerivedStructureAdapter(IndexRangeTests, TestCase): - AdptClass = DerivedStructureAdapter - - def setUp(self): - IndexRangeTests.setUp(self) - self.adpt1 = self.adpt.clone() - self.adpt1.positions.append(numpy.array([1.0, 2.0, 3.0])) - return - - def test_siteAtomType_valid(self): - """Check DerivedStructureAdapter.siteAtomType.""" - adpt1 = self.adpt1 - self.assertEqual("Cu", adpt1.siteAtomType(0)) - self.assertEqual("", StructureAdapter.siteAtomType(adpt1, 0)) - return - - def test_siteCartesianPosition_valid(self): - """Check DerivedStructureAdapter.siteCartesianPosition.""" - adpt1 = self.adpt1 - xyz0 = adpt1.siteCartesianPosition(0) - self.assertTrue(numpy.array_equal([1, 2, 3], xyz0)) - return - - def test_siteMultiplicity_valid(self): - """Check DerivedStructureAdapter.siteMultiplicity.""" - adpt1 = self.adpt1 - self.assertEqual(2, adpt1.siteMultiplicity(0)) - self.assertEqual(1, StructureAdapter.siteMultiplicity(adpt1, 0)) - return - - def test_siteOccupancy_valid(self): - """Check DerivedStructureAdapter.siteOccupancy.""" - adpt1 = self.adpt1 - self.assertEqual(0.5, adpt1.siteOccupancy(0)) - self.assertEqual(1.0, StructureAdapter.siteOccupancy(adpt1, 0)) - return - - def test_siteAnisotropy_valid(self): - """Check DerivedStructureAdapter.siteAnisotropy.""" - adpt1 = self.adpt1 - self.assertFalse(adpt1.siteAnisotropy(0)) - return - - def test_siteCartesianUij_valid(self): - """Check DerivedStructureAdapter.siteCartesianUij.""" - adpt1 = self.adpt1 - uiso = 0.005 * numpy.identity(3) - self.assertTrue(numpy.array_equal(uiso, adpt1.siteCartesianUij(0))) - self.assertRaises(IndexError, adpt1.siteCartesianUij, 1) - return - - -# End of class TestDerivedStructureAdapter - -# ---------------------------------------------------------------------------- - - -class TestStructureAdapter(unittest.TestCase): - - def setUp(self): - self.adpt = StructureAdapter() - return - - # def test__customPQConfig(self): - # """check StructureAdapter._customPQConfig() - # """ - # return - # - # def test_countSites(self): - # """check StructureAdapter.countSites() - # """ - # return - # - # def test_createBondGenerator(self): - # """check StructureAdapter.createBondGenerator() - # """ - # return - # - # def test_numberDensity(self): - # """check StructureAdapter.numberDensity() - # """ - # return - - def test_siteAtomType(self): - """Check StructureAdapter.siteAtomType()""" - self.assertEqual("", self.adpt.siteAtomType(0)) - return - - def test_siteCartesianPosition(self): - """Check StructureAdapter.siteCartesianPosition()""" - self.assertRaises(RuntimeError, self.adpt.siteAnisotropy, 0) - return - - def test_siteMultiplicity(self): - """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 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()""" - self.assertRaises(RuntimeError, self.adpt.siteAnisotropy, 0) - return - - def test_siteCartesianUij(self): - """Check StructureAdapter.siteCartesianUij()""" - self.assertRaises(RuntimeError, self.adpt.siteCartesianUij, 0) - return - - -# def test_totalOccupancy(self): -# """check StructureAdapter.totalOccupancy() -# """ -# return - -# End of class TestStructureAdapter - -# ---------------------------------------------------------------------------- - - -class TestAtom(unittest.TestCase): - - def setUp(self): - self.a = Atom() - return - - def test___init__copy(self): - """Check Atom copy constructor.""" - self.a.xyz_cartn = (1, 2, 3) - a1 = Atom(self.a) - self.assertEqual(self.a, a1) - self.assertNotEqual(self.a, Atom()) - return - - def test_equality(self): - """Check Atom equal and not equal operators.""" - self.assertEqual(self.a, Atom()) - self.assertFalse(self.a != Atom()) - a1 = Atom() - a1.atomtype = "Na" - self.assertNotEqual(self.a, a1) - return - - def test_pickling(self): - """Check pickling of Atom instances.""" - self.a.atomtype = "Na" - a1 = pickle.loads(pickle.dumps(self.a)) - self.assertEqual("Na", a1.atomtype) - self.assertEqual(self.a, a1) - self.assertFalse(self.a is a1) - return - - def test_xyz_cartn(self): - """Check Atom.xyz_cartn.""" - a = self.a - a.xyz_cartn = 4, 5, 6 - self.assertTrue(numpy.array_equal([4, 5, 6], a.xyz_cartn)) - self.assertEqual(4.0, a.xc) - self.assertEqual(5.0, a.yc) - self.assertEqual(6.0, a.zc) - return - - def test_uij_cartn(self): - """Check Atom.uij_cartn.""" - a = self.a - a.uij_cartn = numpy.identity(3) * 0.01 - a.uc12 = 0.012 - a.uc13 = 0.013 - a.uc23 = 0.023 - self.assertTrue( - numpy.array_equal( - a.uij_cartn, - [ - [0.01, 0.012, 0.013], - [0.012, 0.01, 0.023], - [0.013, 0.023, 0.01], - ], - ) - ) - self.assertEqual(0.01, a.uc11) - self.assertEqual(0.01, a.uc22) - self.assertEqual(0.01, a.uc33) - self.assertEqual(0.012, a.uc12) - self.assertEqual(0.013, a.uc13) - self.assertEqual(0.023, a.uc23) - return - - def test_xc_yc_zc(self): - "check Atom properties xc, yc, zc." - a = self.a - a.xc, a.yc, a.zc = numpy.arange(1, 4) - self.assertEqual(1.0, a.xc) - self.assertEqual(2.0, a.yc) - self.assertEqual(3.0, a.zc) - return - - def test_occupancy(self): - "check Atom.occupancy" - a = self.a - (a.occupancy,) = numpy.arange(1) - self.assertEqual(0.0, a.occupancy) - a.occupancy = numpy.float32(0.5) - self.assertEqual(0.5, a.occupancy) - return - - def test_anisotropy(self): - "check Atom.anisotropy" - a = self.a - nptrue, npfalse = numpy.arange(2) < 1 - a.anisotropy = nptrue - self.assertTrue(a.anisotropy) - a.anisotropy = npfalse - self.assertFalse(a.anisotropy) - return - - def test_ucij(self): - "check Atom attributes u11, u22, etc." - a = self.a - a.uc11, a.uc22, a.uc33, a.uc12, a.uc13, a.uc23 = numpy.arange(1, 7) - uijexp = [[1, 4, 5], [4, 2, 6], [5, 6, 3]] - self.assertTrue(numpy.array_equal(uijexp, a.uij_cartn)) - return - - -# End of class TestAtom - -# ---------------------------------------------------------------------------- - -if __name__ == "__main__": - unittest.main() - -# End of file diff --git a/tests/test_version.py b/tests/test_version.py deleted file mode 100644 index d50b30db..00000000 --- a/tests/test_version.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Unit tests for __version__.py.""" - -import diffpy.srreal - - -def test_package_version(): - """Ensure the package version is defined and not set to the initial - placeholder.""" - assert hasattr(diffpy.srreal, "__version__") - assert diffpy.srreal.__version__ != "0.0.0" diff --git a/tests/testdata/C60bucky.stru b/tests/testdata/C60bucky.stru deleted file mode 100644 index 7a9d9225..00000000 --- a/tests/testdata/C60bucky.stru +++ /dev/null @@ -1,65 +0,0 @@ -title Matlab generated C60 bucky ball -spcgr P1 -cell 1.000000, 1.000000, 1.000000, 90.000000, 90.000000, 90.000000 -ncell 1, 1, 1, 60 -atoms -C 1.22493716 0.00000000 3.35151135 0.25 -C 0.37852640 1.16498447 3.35151135 0.25 -C -0.99099498 0.72000000 3.35151135 0.25 -C -0.99099498 -0.72000000 3.35151135 0.25 -C 0.37852640 -1.16498447 3.35151135 0.25 -C 2.44987433 0.00000000 2.59445855 0.25 -C 2.82840073 -1.16498447 1.83740575 0.25 -C 3.44086931 -0.72000000 0.61246858 0.25 -C 3.44086931 0.72000000 0.61246858 0.25 -C 2.82840073 1.16498447 1.83740575 0.25 -C 0.75705280 2.32996894 2.59445855 0.25 -C 1.98198996 2.32996894 1.83740575 0.25 -C 1.74804778 3.04996894 0.61246858 0.25 -C 0.37852640 3.49495342 0.61246858 0.25 -C -0.23394218 3.04996894 1.83740575 0.25 -C -1.98198996 1.44000000 2.59445855 0.25 -C -1.60346356 2.60498447 1.83740575 0.25 -C -2.36051637 2.60498447 0.61246858 0.25 -C -3.20692713 1.44000000 0.61246858 0.25 -C -2.97298495 0.72000000 1.83740575 0.25 -C -1.98198996 -1.44000000 2.59445855 0.25 -C -2.97298495 -0.72000000 1.83740575 0.25 -C -3.20692713 -1.44000000 0.61246858 0.25 -C -2.36051637 -2.60498447 0.61246858 0.25 -C -1.60346356 -2.60498447 1.83740575 0.25 -C 0.75705280 -2.32996894 2.59445855 0.25 -C -0.23394218 -3.04996894 1.83740575 0.25 -C 0.37852640 -3.49495342 0.61246858 0.25 -C 1.74804778 -3.04996894 0.61246858 0.25 -C 1.98198996 -2.32996894 1.83740575 0.25 -C -1.98198996 2.32996894 -1.83740575 0.25 -C -1.74804778 3.04996894 -0.61246858 0.25 -C -0.37852640 3.49495342 -0.61246858 0.25 -C 0.23394218 3.04996894 -1.83740575 0.25 -C -0.75705280 2.32996894 -2.59445855 0.25 -C 1.60346356 2.60498447 -1.83740575 0.25 -C 2.36051637 2.60498447 -0.61246858 0.25 -C 3.20692713 1.44000000 -0.61246858 0.25 -C 2.97298495 0.72000000 -1.83740575 0.25 -C 1.98198996 1.44000000 -2.59445855 0.25 -C 2.97298495 -0.72000000 -1.83740575 0.25 -C 3.20692713 -1.44000000 -0.61246858 0.25 -C 2.36051637 -2.60498447 -0.61246858 0.25 -C 1.60346356 -2.60498447 -1.83740575 0.25 -C 1.98198996 -1.44000000 -2.59445855 0.25 -C 0.23394218 -3.04996894 -1.83740575 0.25 -C -0.37852640 -3.49495342 -0.61246858 0.25 -C -1.74804778 -3.04996894 -0.61246858 0.25 -C -1.98198996 -2.32996894 -1.83740575 0.25 -C -0.75705280 -2.32996894 -2.59445855 0.25 -C -2.82840073 -1.16498447 -1.83740575 0.25 -C -3.44086931 -0.72000000 -0.61246858 0.25 -C -3.44086931 0.72000000 -0.61246858 0.25 -C -2.82840073 1.16498447 -1.83740575 0.25 -C -2.44987433 0.00000000 -2.59445855 0.25 -C -0.37852640 1.16498447 -3.35151135 0.25 -C 0.99099498 0.72000000 -3.35151135 0.25 -C 0.99099498 -0.72000000 -3.35151135 0.25 -C -0.37852640 -1.16498447 -3.35151135 0.25 -C -1.22493716 0.00000000 -3.35151135 0.25 diff --git a/tests/testdata/CdSe_cadmoselite.cif b/tests/testdata/CdSe_cadmoselite.cif deleted file mode 100644 index 72337ac7..00000000 --- a/tests/testdata/CdSe_cadmoselite.cif +++ /dev/null @@ -1,57 +0,0 @@ -#------------------------------------------------------------------------------ -#$Date: 2008-03-10 08:25:41 +0000 (Mon, 10 Mar 2008) $ -#$Revision: 255 $ -#$URL: svn://cod.ibt.lt/cod/cif/9/9008863.cif $ -#------------------------------------------------------------------------------ -# -# This file is available in the Crystallography Open Database (COD), -# http://www.crystallography.net/ -# -# All data on this site have been placed in the public domain by the -# contributors. -# -data_9008863 -loop_ -_publ_author_name -'Wyckoff R W G' -_publ_section_title -; - Second edition. Interscience Publishers, New York, New York - Note: wurtzite structure -; -_journal_name_full 'Crystal Structures' -_journal_page_first 85 -_journal_page_last 237 -_journal_volume 1 -_journal_year 1963 -_chemical_formula_sum 'Cd Se' -_chemical_name_mineral Cadmoselite -_symmetry_space_group_name_H-M 'P 63 m c' -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 120 -_cell_length_a 4.30 -_cell_length_b 4.30 -_cell_length_c 7.02 -_cell_volume 112.410 -loop_ -_symmetry_equiv_pos_as_xyz -x,y,z --x,-x+y,1/2+z -x-y,x,1/2+z --y,-x,z --y,x-y,z -x-y,-y,1/2+z --x,-y,1/2+z -x,x-y,z --x+y,-x,z -y,x,1/2+z -y,-x+y,1/2+z --x+y,y,z -loop_ -_atom_site_label -_atom_site_fract_x -_atom_site_fract_y -_atom_site_fract_z -Cd 0.33333 0.66667 0.00000 -Se 0.33333 0.66667 0.38500 diff --git a/tests/testdata/CdSe_cadmoselite_N.fgr b/tests/testdata/CdSe_cadmoselite_N.fgr deleted file mode 100644 index 960d20fb..00000000 --- a/tests/testdata/CdSe_cadmoselite_N.fgr +++ /dev/null @@ -1,204 +0,0 @@ -# type = N -# rmin = 0.10 -# rmax = 10.00 -# rstep = 0.05 -# biso = 0.50 -# qmax = 40.00 -0.1 -3.594960e-02 -0.15 -6.357034e-02 -0.2 -1.010748e-01 -0.25 -1.057479e-01 -0.3 -1.274572e-01 -0.35 -1.680407e-01 -0.4 -1.761003e-01 -0.45 -1.919489e-01 -0.5 -2.339551e-01 -0.55 -2.467115e-01 -0.6 -2.572803e-01 -0.65 -2.989205e-01 -0.7 -3.172623e-01 -0.75 -3.236111e-01 -0.8 -3.631249e-01 -0.85 -3.874380e-01 -0.9 -3.910124e-01 -0.95 -4.268249e-01 -1 -4.569563e-01 -1.05 -4.594591e-01 -1.1 -4.903238e-01 -1.15 -5.255928e-01 -1.2 -5.288325e-01 -1.25 -5.539443e-01 -1.3 -5.932008e-01 -1.35 -5.989297e-01 -1.4 -6.180003e-01 -1.45 -6.597251e-01 -1.5 -6.694818e-01 -1.55 -6.827684e-01 -1.6 -7.252077e-01 -1.65 -7.401767e-01 -1.7 -7.484637e-01 -1.75 -7.897842e-01 -1.8 -8.106872e-01 -1.85 -8.152195e-01 -1.9 -8.536730e-01 -1.95 -8.806996e-01 -2 -8.830739e-01 -2.05 -9.171405e-01 -2.1 -9.498113e-01 -2.15 -9.510815e-01 -2.2 -9.755675e-01 -2.25 -9.952371e-01 -2.3 -9.347293e-01 -2.35 -7.727363e-01 -2.4 -3.872584e-01 -2.45 3.904418e-01 -2.5 1.497846e+00 -2.55 2.651927e+00 -2.6 3.461606e+00 -2.65 3.531844e+00 -2.7 2.807840e+00 -2.75 1.671788e+00 -2.8 5.372527e-01 -2.85 -3.589358e-01 -2.9 -8.989639e-01 -2.95 -1.155994e+00 -3 -1.296881e+00 -3.05 -1.361730e+00 -3.1 -1.372372e+00 -3.15 -1.406841e+00 -3.2 -1.443028e+00 -3.25 -1.444488e+00 -3.3 -1.470600e+00 -3.35 -1.510972e+00 -3.4 -1.514749e+00 -3.45 -1.534254e+00 -3.5 -1.577662e+00 -3.55 -1.585583e+00 -3.6 -1.598618e+00 -3.65 -1.643182e+00 -3.7 -1.656661e+00 -3.75 -1.663881e+00 -3.8 -1.707079e+00 -3.85 -1.723917e+00 -3.9 -1.710465e+00 -3.95 -1.683379e+00 -4 -1.480541e+00 -4.05 -8.559234e-01 -4.1 4.607020e-01 -4.15 2.722147e+00 -4.2 5.670255e+00 -4.25 8.265550e+00 -4.3 9.315003e+00 -4.35 8.291567e+00 -4.4 5.675179e+00 -4.45 2.676495e+00 -4.5 3.481429e-01 -4.55 -1.049853e+00 -4.6 -1.737722e+00 -4.65 -1.977691e+00 -4.7 -2.027100e+00 -4.75 -1.986800e+00 -4.8 -1.722909e+00 -4.85 -1.106470e+00 -4.9 -7.007781e-02 -4.95 1.361227e+00 -5 2.773916e+00 -5.05 3.503927e+00 -5.1 3.215670e+00 -5.15 2.062879e+00 -5.2 5.186860e-01 -5.25 -8.277165e-01 -5.3 -1.675669e+00 -5.35 -2.135617e+00 -5.4 -2.354050e+00 -5.45 -2.410842e+00 -5.5 -2.445721e+00 -5.55 -2.496305e+00 -5.6 -2.500667e+00 -5.65 -2.509371e+00 -5.7 -2.543010e+00 -5.75 -2.492502e+00 -5.8 -2.302439e+00 -5.85 -1.855373e+00 -5.9 -8.720268e-01 -5.95 7.050158e-01 -6 2.505752e+00 -6.05 3.903092e+00 -6.1 4.216927e+00 -6.15 3.205107e+00 -6.2 1.421721e+00 -6.25 -3.260708e-01 -6.3 -1.591565e+00 -6.35 -2.208417e+00 -6.4 -2.187176e+00 -6.45 -1.690001e+00 -6.5 -8.121258e-01 -6.55 2.844129e-01 -6.6 1.128737e+00 -6.65 1.314283e+00 -6.7 8.247404e-01 -6.75 -1.279997e-01 -6.8 -1.152896e+00 -6.85 -1.820718e+00 -6.9 -2.065998e+00 -6.95 -2.092130e+00 -7 -2.040506e+00 -7.05 -2.070806e+00 -7.1 -2.268691e+00 -7.15 -2.387548e+00 -7.2 -2.094591e+00 -7.25 -1.161360e+00 -7.3 6.114047e-01 -7.35 2.982785e+00 -7.4 5.010714e+00 -7.45 5.729229e+00 -7.5 4.806685e+00 -7.55 2.650814e+00 -7.6 2.577341e-01 -7.65 -1.450135e+00 -7.7 -2.236274e+00 -7.75 -2.218754e+00 -7.8 -1.532480e+00 -7.85 -5.779091e-01 -7.9 1.462045e-01 -7.95 4.602995e-01 -8 4.554095e-01 -8.05 5.029144e-01 -8.1 1.119635e+00 -8.15 2.224926e+00 -8.2 3.042399e+00 -8.25 2.957690e+00 -8.3 1.924281e+00 -8.35 4.055310e-01 -8.4 -7.218484e-01 -8.45 -8.516101e-01 -8.5 -1.933027e-01 -8.55 6.671100e-01 -8.6 1.139531e+00 -8.65 7.487619e-01 -8.7 -3.282219e-01 -8.75 -1.321250e+00 -8.8 -1.680134e+00 -8.85 -1.187672e+00 -8.9 1.424203e-01 -8.95 1.672731e+00 -9 2.507491e+00 -9.05 2.316868e+00 -9.1 1.255579e+00 -9.15 -2.388671e-01 -9.2 -1.484445e+00 -9.25 -2.216280e+00 -9.3 -2.694508e+00 -9.35 -2.890663e+00 -9.4 -2.545214e+00 -9.45 -1.642745e+00 -9.5 -1.778503e-01 -9.55 1.563203e+00 -9.6 2.633854e+00 -9.65 2.423924e+00 -9.7 1.232324e+00 -9.75 -4.376721e-01 -9.8 -1.989275e+00 -9.85 -2.810648e+00 -9.9 -3.034062e+00 -9.95 -3.065218e+00 diff --git a/tests/testdata/CdSe_cadmoselite_X.fgr b/tests/testdata/CdSe_cadmoselite_X.fgr deleted file mode 100644 index 45bb010a..00000000 --- a/tests/testdata/CdSe_cadmoselite_X.fgr +++ /dev/null @@ -1,404 +0,0 @@ -# type = X -# rmin = 0.10 -# rmax = 20.00 -# rstep = 0.05 -# biso = 0.50 -# qmax = 40.00 -0.1 -4.265025e-02 -0.15 -6.633296e-02 -0.2 -9.211916e-02 -0.25 -1.102843e-01 -0.3 -1.327214e-01 -0.35 -1.592080e-01 -0.4 -1.780326e-01 -0.45 -1.992168e-01 -0.5 -2.260928e-01 -0.55 -2.458450e-01 -0.6 -2.658627e-01 -0.65 -2.927873e-01 -0.7 -3.136663e-01 -0.75 -3.326916e-01 -0.8 -3.593196e-01 -0.85 -3.814404e-01 -0.9 -3.997225e-01 -0.95 -4.257297e-01 -1 -4.491147e-01 -1.05 -4.669594e-01 -1.1 -4.920671e-01 -1.15 -5.166436e-01 -1.2 -5.343911e-01 -1.25 -5.583868e-01 -1.3 -5.839922e-01 -1.35 -6.019918e-01 -1.4 -6.247454e-01 -1.45 -6.511388e-01 -1.5 -6.697228e-01 -1.55 -6.911973e-01 -1.6 -7.180766e-01 -1.65 -7.375355e-01 -1.7 -7.577900e-01 -1.75 -7.848142e-01 -1.8 -8.053748e-01 -1.85 -8.245611e-01 -1.9 -8.513755e-01 -1.95 -8.731832e-01 -2 -8.915336e-01 -2.05 -9.177811e-01 -2.1 -9.407699e-01 -2.15 -9.578021e-01 -2.2 -9.789747e-01 -2.25 -9.847601e-01 -2.3 -9.362153e-01 -2.35 -7.699910e-01 -2.4 -3.547285e-01 -2.45 4.378909e-01 -2.5 1.575572e+00 -2.55 2.785826e+00 -2.6 3.615854e+00 -2.65 3.677519e+00 -2.7 2.947056e+00 -2.75 1.772266e+00 -2.8 5.857835e-01 -2.85 -3.247901e-01 -2.9 -8.784110e-01 -2.95 -1.160645e+00 -3 -1.294662e+00 -3.05 -1.352147e+00 -3.1 -1.380471e+00 -3.15 -1.409366e+00 -3.2 -1.432674e+00 -3.25 -1.450414e+00 -3.3 -1.476188e+00 -3.35 -1.500400e+00 -3.4 -1.517781e+00 -3.45 -1.542444e+00 -3.5 -1.567875e+00 -3.55 -1.585343e+00 -3.6 -1.608705e+00 -3.65 -1.635141e+00 -3.7 -1.653069e+00 -3.75 -1.674964e+00 -3.8 -1.701624e+00 -3.85 -1.717307e+00 -3.9 -1.722048e+00 -3.95 -1.683426e+00 -4 -1.479641e+00 -4.05 -8.905963e-01 -4.1 3.997651e-01 -4.15 2.614808e+00 -4.2 5.469694e+00 -4.25 8.003565e+00 -4.3 9.045072e+00 -4.35 8.033302e+00 -4.4 5.480459e+00 -4.45 2.575061e+00 -4.5 2.905781e-01 -4.55 -1.083183e+00 -4.6 -1.735142e+00 -4.65 -1.977179e+00 -4.7 -2.038413e+00 -4.75 -1.974424e+00 -4.8 -1.702818e+00 -4.85 -1.084638e+00 -4.9 4.621561e-03 -4.95 1.488824e+00 -5 2.926685e+00 -5.05 3.694858e+00 -5.1 3.409378e+00 -5.15 2.196220e+00 -5.2 6.090482e-01 -5.25 -7.636615e-01 -5.3 -1.660600e+00 -5.35 -2.134757e+00 -5.4 -2.337789e+00 -5.45 -2.414002e+00 -5.5 -2.456439e+00 -5.55 -2.483483e+00 -5.6 -2.500206e+00 -5.65 -2.522797e+00 -5.7 -2.532536e+00 -5.75 -2.488036e+00 -5.8 -2.318476e+00 -5.85 -1.850968e+00 -5.9 -8.681527e-01 -5.95 6.828771e-01 -6 2.501587e+00 -6.05 3.911685e+00 -6.1 4.204563e+00 -6.15 3.209150e+00 -6.2 1.444344e+00 -6.25 -3.302626e-01 -6.3 -1.592252e+00 -6.35 -2.183711e+00 -6.4 -2.176334e+00 -6.45 -1.662939e+00 -6.5 -7.263784e-01 -6.55 3.880757e-01 -6.6 1.248171e+00 -6.65 1.470561e+00 -6.7 9.528141e-01 -6.75 -5.421964e-02 -6.8 -1.088786e+00 -6.85 -1.792370e+00 -6.9 -2.089180e+00 -6.95 -2.106631e+00 -7 -2.056650e+00 -7.05 -2.119055e+00 -7.1 -2.294103e+00 -7.15 -2.394337e+00 -7.2 -2.142503e+00 -7.25 -1.227116e+00 -7.3 5.173676e-01 -7.35 2.788187e+00 -7.4 4.756547e+00 -7.45 5.484323e+00 -7.5 4.562147e+00 -7.55 2.459275e+00 -7.6 1.730897e-01 -7.65 -1.497071e+00 -7.7 -2.263382e+00 -7.75 -2.175369e+00 -7.8 -1.465024e+00 -7.85 -5.072133e-01 -7.9 2.756426e-01 -7.95 5.925668e-01 -8 5.231163e-01 -8.05 5.522967e-01 -8.1 1.125966e+00 -8.15 2.134126e+00 -8.2 2.934111e+00 -8.25 2.864648e+00 -8.3 1.801591e+00 -8.35 3.203756e-01 -8.4 -7.388780e-01 -8.45 -8.877990e-01 -8.5 -2.233200e-01 -8.55 6.904713e-01 -8.6 1.134283e+00 -8.65 7.264115e-01 -8.7 -2.935377e-01 -8.75 -1.298054e+00 -8.8 -1.671691e+00 -8.85 -1.088072e+00 -8.9 2.891711e-01 -8.95 1.822982e+00 -9 2.736807e+00 -9.05 2.552710e+00 -9.1 1.395117e+00 -9.15 -1.084007e-01 -9.2 -1.362662e+00 -9.25 -2.187562e+00 -9.3 -2.661374e+00 -9.35 -2.823563e+00 -9.4 -2.563949e+00 -9.45 -1.680884e+00 -9.5 -1.696922e-01 -9.55 1.493003e+00 -9.6 2.535102e+00 -9.65 2.416502e+00 -9.7 1.196590e+00 -9.75 -5.016895e-01 -9.8 -1.941608e+00 -9.85 -2.773443e+00 -9.9 -3.066713e+00 -9.95 -2.999735e+00 -10 -2.651632e+00 -10.05 -1.942383e+00 -10.1 -7.692873e-01 -10.15 6.381646e-01 -10.2 1.653397e+00 -10.25 1.726643e+00 -10.3 8.485566e-01 -10.35 -4.296730e-01 -10.4 -1.374831e+00 -10.45 -1.607123e+00 -10.5 -1.304149e+00 -10.55 -8.749688e-01 -10.6 -5.818348e-01 -10.65 -4.150369e-01 -10.7 -1.393983e-01 -10.75 4.199030e-01 -10.8 1.066285e+00 -10.85 1.394603e+00 -10.9 1.229083e+00 -10.95 7.599296e-01 -11 3.331289e-01 -11.05 1.250751e-01 -11.1 1.598008e-02 -11.15 -7.384476e-02 -11.2 1.366440e-01 -11.25 9.611937e-01 -11.3 2.202373e+00 -11.35 3.152378e+00 -11.4 3.138231e+00 -11.45 2.157475e+00 -11.5 9.890944e-01 -11.55 4.785566e-01 -11.6 7.585303e-01 -11.65 1.274529e+00 -11.7 1.356525e+00 -11.75 7.214789e-01 -11.8 -3.667126e-01 -11.85 -1.416764e+00 -11.9 -2.128155e+00 -11.95 -2.358572e+00 -12 -1.971956e+00 -12.05 -1.008078e+00 -12.1 1.916285e-01 -12.15 1.152266e+00 -12.2 1.540905e+00 -12.25 1.437299e+00 -12.3 1.274214e+00 -12.35 1.303323e+00 -12.4 1.295053e+00 -12.45 8.680871e-01 -12.5 -1.168587e-01 -12.55 -1.450015e+00 -12.6 -2.693648e+00 -12.65 -3.497645e+00 -12.7 -3.755485e+00 -12.75 -3.442020e+00 -12.8 -2.622828e+00 -12.85 -1.631073e+00 -12.9 -9.081891e-01 -12.95 -6.921340e-01 -13 -9.107032e-01 -13.05 -1.209237e+00 -13.1 -1.185595e+00 -13.15 -6.909728e-01 -13.2 2.519282e-01 -13.25 1.592930e+00 -13.3 3.038194e+00 -13.35 4.046398e+00 -13.4 4.290119e+00 -13.45 3.906514e+00 -13.5 3.282914e+00 -13.55 2.683734e+00 -13.6 2.048768e+00 -13.65 1.278650e+00 -13.7 6.032627e-01 -13.75 2.783410e-01 -13.8 1.131957e-01 -13.85 -3.104574e-01 -13.9 -1.168185e+00 -13.95 -2.262378e+00 -14 -3.126456e+00 -14.05 -3.351632e+00 -14.1 -2.920764e+00 -14.15 -2.126595e+00 -14.2 -1.370613e+00 -14.25 -1.076517e+00 -14.3 -1.379735e+00 -14.35 -1.930576e+00 -14.4 -2.262866e+00 -14.45 -2.120329e+00 -14.5 -1.415559e+00 -14.55 -2.553189e-01 -14.6 1.034649e+00 -14.65 2.036621e+00 -14.7 2.338462e+00 -14.75 1.809921e+00 -14.8 9.002575e-01 -14.85 2.807050e-01 -14.9 2.724427e-01 -14.95 8.449404e-01 -15 1.745590e+00 -15.05 2.484573e+00 -15.1 2.585116e+00 -15.15 1.860284e+00 -15.2 4.607789e-01 -15.25 -1.067400e+00 -15.3 -1.995430e+00 -15.35 -1.946211e+00 -15.4 -1.063216e+00 -15.45 1.307836e-01 -15.5 8.759017e-01 -15.55 7.025253e-01 -15.6 -1.015496e-01 -15.65 -9.084627e-01 -15.7 -1.324798e+00 -15.75 -1.219578e+00 -15.8 -7.051230e-01 -15.85 -6.084065e-02 -15.9 5.737824e-01 -15.95 1.172435e+00 -16 1.619090e+00 -16.05 1.837822e+00 -16.1 1.821556e+00 -16.15 1.542573e+00 -16.2 1.147077e+00 -16.25 8.946362e-01 -16.3 8.143840e-01 -16.35 8.309345e-01 -16.4 9.068829e-01 -16.45 8.083692e-01 -16.5 2.973510e-01 -16.55 -5.060798e-01 -16.6 -1.371826e+00 -16.65 -2.149931e+00 -16.7 -2.643364e+00 -16.75 -2.771656e+00 -16.8 -2.585441e+00 -16.85 -1.982911e+00 -16.9 -9.302265e-01 -16.95 2.501140e-01 -17 1.150155e+00 -17.05 1.457763e+00 -17.1 1.074152e+00 -17.15 4.367826e-01 -17.2 1.979247e-01 -17.25 5.290946e-01 -17.3 1.155734e+00 -17.35 1.568611e+00 -17.4 1.118063e+00 -17.45 -3.138068e-01 -17.5 -1.978904e+00 -17.55 -3.002894e+00 -17.6 -2.929280e+00 -17.65 -1.835394e+00 -17.7 -5.290023e-01 -17.75 3.017936e-02 -17.8 -3.157324e-01 -17.85 -1.079822e+00 -17.9 -1.663376e+00 -17.95 -1.522603e+00 -18 -6.652933e-01 -18.05 2.905078e-01 -18.1 9.916111e-01 -18.15 1.530233e+00 -18.2 1.957664e+00 -18.25 2.336143e+00 -18.3 2.615469e+00 -18.35 2.401478e+00 -18.4 1.593642e+00 -18.45 6.171894e-01 -18.5 -2.146133e-01 -18.55 -6.425646e-01 -18.6 -3.528850e-01 -18.65 3.962940e-01 -18.7 1.019255e+00 -18.75 1.310521e+00 -18.8 1.166407e+00 -18.85 6.103673e-01 -18.9 1.544510e-01 -18.95 5.896378e-02 -19 5.203727e-02 -19.05 1.134137e-01 -19.1 2.283433e-01 -19.15 3.345473e-02 -19.2 -4.214438e-01 -19.25 -8.701009e-01 -19.3 -1.495063e+00 -19.35 -2.252871e+00 -19.4 -2.846983e+00 -19.45 -3.426720e+00 -19.5 -3.802040e+00 -19.55 -3.263601e+00 -19.6 -1.906231e+00 -19.65 -3.260781e-01 -19.7 1.164501e+00 -19.75 1.899503e+00 -19.8 1.515947e+00 -19.85 8.659977e-01 -19.9 4.754980e-01 -19.95 1.496017e-01 diff --git a/tests/testdata/Ni-fit.fgr b/tests/testdata/Ni-fit.fgr deleted file mode 100644 index 3e9b6fd0..00000000 --- a/tests/testdata/Ni-fit.fgr +++ /dev/null @@ -1,1001 +0,0 @@ -0 0 -0.01 -0.011525 -0.02 -0.02305 -0.03 -0.0345751 -0.04 -0.0461001 -0.05 -0.0576251 -0.06 -0.0691501 -0.07 -0.0806752 -0.08 -0.0922002 -0.09 -0.103725 -0.1 -0.11525 -0.11 -0.126775 -0.12 -0.1383 -0.13 -0.149825 -0.14 -0.16135 -0.15 -0.172875 -0.16 -0.1844 -0.17 -0.195925 -0.18 -0.20745 -0.19 -0.218975 -0.2 -0.2305 -0.21 -0.242026 -0.22 -0.253551 -0.23 -0.265076 -0.24 -0.276601 -0.25 -0.288126 -0.26 -0.299651 -0.27 -0.311176 -0.28 -0.322701 -0.29 -0.334226 -0.3 -0.345751 -0.31 -0.357276 -0.32 -0.368801 -0.33 -0.380326 -0.34 -0.391851 -0.35 -0.403376 -0.36 -0.414901 -0.37 -0.426426 -0.38 -0.437951 -0.39 -0.449476 -0.4 -0.461001 -0.41 -0.472526 -0.42 -0.484051 -0.43 -0.495576 -0.44 -0.507101 -0.45 -0.518626 -0.46 -0.530151 -0.47 -0.541676 -0.48 -0.553201 -0.49 -0.564726 -0.5 -0.576251 -0.51 -0.587776 -0.52 -0.599301 -0.53 -0.610826 -0.54 -0.622351 -0.55 -0.633876 -0.56 -0.645401 -0.57 -0.656926 -0.58 -0.668451 -0.59 -0.679976 -0.6 -0.691501 -0.61 -0.703027 -0.62 -0.714552 -0.63 -0.726077 -0.64 -0.737602 -0.65 -0.749127 -0.66 -0.760652 -0.67 -0.772177 -0.68 -0.783702 -0.69 -0.795227 -0.7 -0.806752 -0.71 -0.818277 -0.72 -0.829802 -0.73 -0.841327 -0.74 -0.852852 -0.75 -0.864377 -0.76 -0.875902 -0.77 -0.887427 -0.78 -0.898952 -0.79 -0.910477 -0.8 -0.922002 -0.81 -0.933527 -0.82 -0.945052 -0.83 -0.956577 -0.84 -0.968102 -0.85 -0.979627 -0.86 -0.991152 -0.87 -1.00268 -0.88 -1.0142 -0.89 -1.02573 -0.9 -1.03725 -0.91 -1.04878 -0.92 -1.0603 -0.93 -1.07183 -0.94 -1.08335 -0.95 -1.09488 -0.96 -1.1064 -0.97 -1.11793 -0.98 -1.12945 -0.99 -1.14098 -1 -1.1525 -1.01 -1.16403 -1.02 -1.17555 -1.03 -1.18708 -1.04 -1.1986 -1.05 -1.21013 -1.06 -1.22165 -1.07 -1.23318 -1.08 -1.2447 -1.09 -1.25623 -1.1 -1.26775 -1.11 -1.27928 -1.12 -1.2908 -1.13 -1.30233 -1.14 -1.31385 -1.15 -1.32538 -1.16 -1.3369 -1.17 -1.34843 -1.18 -1.35995 -1.19 -1.37148 -1.2 -1.383 -1.21 -1.39453 -1.22 -1.40605 -1.23 -1.41758 -1.24 -1.4291 -1.25 -1.44063 -1.26 -1.45215 -1.27 -1.46368 -1.28 -1.4752 -1.29 -1.48673 -1.3 -1.49825 -1.31 -1.50978 -1.32 -1.5213 -1.33 -1.53283 -1.34 -1.54435 -1.35 -1.55588 -1.36 -1.5674 -1.37 -1.57893 -1.38 -1.59045 -1.39 -1.60198 -1.4 -1.6135 -1.41 -1.62503 -1.42 -1.63655 -1.43 -1.64808 -1.44 -1.6596 -1.45 -1.67113 -1.46 -1.68265 -1.47 -1.69418 -1.48 -1.7057 -1.49 -1.71723 -1.5 -1.72875 -1.51 -1.74028 -1.52 -1.7518 -1.53 -1.76333 -1.54 -1.77485 -1.55 -1.78638 -1.56 -1.7979 -1.57 -1.80943 -1.58 -1.82095 -1.59 -1.83248 -1.6 -1.844 -1.61 -1.85553 -1.62 -1.86705 -1.63 -1.87858 -1.64 -1.8901 -1.65 -1.90163 -1.66 -1.91315 -1.67 -1.92468 -1.68 -1.9362 -1.69 -1.94773 -1.7 -1.95925 -1.71 -1.97078 -1.72 -1.9823 -1.73 -1.99383 -1.74 -2.00535 -1.75 -2.01688 -1.76 -2.0284 -1.77 -2.03993 -1.78 -2.05145 -1.79 -2.06298 -1.8 -2.0745 -1.81 -2.08603 -1.82 -2.09755 -1.83 -2.10908 -1.84 -2.1206 -1.85 -2.13213 -1.86 -2.14365 -1.87 -2.15518 -1.88 -2.1667 -1.89 -2.17823 -1.9 -2.18975 -1.91 -2.20128 -1.92 -2.2128 -1.93 -2.22433 -1.94 -2.23585 -1.95 -2.24738 -1.96 -2.2589 -1.97 -2.27043 -1.98 -2.28195 -1.99 -2.29348 -2 -2.305 -2.01 -2.31653 -2.02 -2.32805 -2.03 -2.33958 -2.04 -2.35111 -2.05 -2.36263 -2.06 -2.37416 -2.07 -2.38568 -2.08 -2.39721 -2.09 -2.40873 -2.1 -2.42026 -2.11 -2.43178 -2.12 -2.44331 -2.13 -2.45483 -2.14 -2.46636 -2.15 -2.47788 -2.16 -2.48941 -2.17 -2.50093 -2.18 -2.51246 -2.19 -2.52398 -2.2 -2.53551 -2.21 -2.54703 -2.22 -2.55856 -2.23 -2.57008 -2.24 -2.5814 -2.25 -2.5926 -2.26 -2.60331 -2.27 -2.61294 -2.28 -2.6202 -2.29 -2.62252 -2.3 -2.61496 -2.31 -2.58859 -2.32 -2.52796 -2.33 -2.40785 -2.34 -2.18936 -2.35 -1.8161 -2.36 -1.2118 -2.37 -0.281097 -2.38 1.08424 -2.39 2.99195 -2.4 5.52826 -2.41 8.73101 -2.42 12.5615 -2.43 16.8824 -2.44 21.4495 -2.45 25.9245 -2.46 29.9111 -2.47 33.0105 -2.48 34.8861 -2.49 35.3238 -2.5 34.2713 -2.51 31.8488 -2.52 28.3257 -2.53 24.0713 -2.54 19.4909 -2.55 14.9634 -2.56 10.7925 -2.57 7.17968 -2.58 4.221 -2.59 1.92127 -2.6 0.219841 -2.61 -0.981108 -2.62 -1.79163 -2.63 -2.31598 -2.64 -2.64227 -2.65 -2.83868 -2.66 -2.9542 -2.67 -3.02175 -2.68 -3.06221 -2.69 -3.08805 -2.7 -3.10638 -2.71 -3.121 -2.72 -3.13387 -2.73 -3.14597 -2.74 -3.15772 -2.75 -3.16938 -2.76 -3.18091 -2.77 -3.19243 -2.78 -3.20396 -2.79 -3.21548 -2.8 -3.22701 -2.81 -3.23853 -2.82 -3.25006 -2.83 -3.26158 -2.84 -3.27311 -2.85 -3.28463 -2.86 -3.29616 -2.87 -3.30768 -2.88 -3.31921 -2.89 -3.33073 -2.9 -3.34226 -2.91 -3.35378 -2.92 -3.36531 -2.93 -3.37683 -2.94 -3.38836 -2.95 -3.39988 -2.96 -3.41141 -2.97 -3.42293 -2.98 -3.43446 -2.99 -3.44598 -3 -3.45751 -3.01 -3.46903 -3.02 -3.48056 -3.03 -3.49208 -3.04 -3.50361 -3.05 -3.51513 -3.06 -3.52666 -3.07 -3.53818 -3.08 -3.54971 -3.09 -3.56123 -3.1 -3.57276 -3.11 -3.58428 -3.12 -3.59581 -3.13 -3.60733 -3.14 -3.61886 -3.15 -3.63038 -3.16 -3.64191 -3.17 -3.65343 -3.18 -3.66496 -3.19 -3.67648 -3.2 -3.68801 -3.21 -3.69953 -3.22 -3.71106 -3.23 -3.72258 -3.24 -3.73411 -3.25 -3.74563 -3.26 -3.75716 -3.27 -3.76862 -3.28 -3.78004 -3.29 -3.79131 -3.3 -3.80224 -3.31 -3.8124 -3.32 -3.82097 -3.33 -3.82635 -3.34 -3.82559 -3.35 -3.8136 -3.36 -3.78198 -3.37 -3.71768 -3.38 -3.60164 -3.39 -3.4078 -3.4 -3.10324 -3.41 -2.65008 -3.42 -2.00981 -3.43 -1.15048 -3.44 -0.0559007 -3.45 1.26424 -3.46 2.76617 -3.47 4.36832 -3.48 5.95482 -3.49 7.38716 -3.5 8.52317 -3.51 9.23974 -3.52 9.45456 -3.53 9.14142 -3.54 8.33518 -3.55 7.12518 -3.56 5.63867 -3.57 4.01869 -3.58 2.40149 -3.59 0.898532 -3.6 -0.414021 -3.61 -1.49767 -3.62 -2.34704 -3.63 -2.9812 -3.64 -3.4336 -3.65 -3.74301 -3.66 -3.94682 -3.67 -4.07702 -3.68 -4.15864 -3.69 -4.20981 -3.7 -4.24281 -3.71 -4.26548 -3.72 -4.28255 -3.73 -4.29672 -3.74 -4.30946 -3.75 -4.32151 -3.76 -4.33326 -3.77 -4.34488 -3.78 -4.35646 -3.79 -4.36798 -3.8 -4.37951 -3.81 -4.39103 -3.82 -4.40256 -3.83 -4.41408 -3.84 -4.42561 -3.85 -4.43713 -3.86 -4.44866 -3.87 -4.46018 -3.88 -4.47171 -3.89 -4.48323 -3.9 -4.49476 -3.91 -4.50628 -3.92 -4.51781 -3.93 -4.52933 -3.94 -4.54086 -3.95 -4.55238 -3.96 -4.56391 -3.97 -4.57543 -3.98 -4.58696 -3.99 -4.59848 -4 -4.61001 -4.01 -4.62153 -4.02 -4.63306 -4.03 -4.64458 -4.04 -4.65611 -4.05 -4.66764 -4.06 -4.67898 -4.07 -4.6902 -4.08 -4.70098 -4.09 -4.71074 -4.1 -4.71824 -4.11 -4.72099 -4.12 -4.71414 -4.13 -4.68876 -4.14 -4.62926 -4.15 -4.50979 -4.16 -4.28985 -4.17 -3.90981 -4.18 -3.2875 -4.19 -2.31797 -4.2 -0.87888 -4.21 1.15633 -4.22 3.89627 -4.23 7.40192 -4.24 11.6538 -4.25 16.5237 -4.26 21.7605 -4.27 26.9979 -4.28 31.7898 -4.29 35.6693 -4.3 38.2227 -4.31 39.1614 -4.32 38.3754 -4.33 35.9544 -4.34 32.1707 -4.35 27.4283 -4.36 22.1922 -4.37 16.9137 -4.38 11.9693 -4.39 7.6228 -4.4 4.0148 -4.41 1.17476 -4.42 -0.951527 -4.43 -2.46924 -4.44 -3.50425 -4.45 -4.18012 -4.46 -4.60393 -4.47 -4.86027 -4.48 -5.01097 -4.49 -5.09828 -4.5 -5.14935 -4.51 -5.18066 -4.52 -5.20167 -4.53 -5.21756 -4.54 -5.23101 -4.55 -5.24335 -4.56 -5.25521 -4.57 -5.26694 -4.58 -5.27846 -4.59 -5.28999 -4.6 -5.30151 -4.61 -5.31304 -4.62 -5.32456 -4.63 -5.33609 -4.64 -5.34761 -4.65 -5.35914 -4.66 -5.37066 -4.67 -5.38219 -4.68 -5.39371 -4.69 -5.40524 -4.7 -5.41676 -4.71 -5.42829 -4.72 -5.43981 -4.73 -5.45123 -4.74 -5.46258 -4.75 -5.47369 -4.76 -5.48423 -4.77 -5.49355 -4.78 -5.50031 -4.79 -5.50199 -4.8 -5.494 -4.81 -5.46843 -4.82 -5.41241 -4.83 -5.30611 -4.84 -5.12092 -4.85 -4.81822 -4.86 -4.34994 -4.87 -3.66176 -4.88 -2.70006 -4.89 -1.42249 -4.9 0.188406 -4.91 2.1112 -4.92 4.27473 -4.93 6.55445 -4.94 8.77932 -4.95 10.7504 -4.96 12.2689 -4.97 13.1687 -4.98 13.3463 -4.99 12.7797 -5 11.5329 -5.01 9.74355 -5.02 7.5981 -5.03 5.29931 -5.04 3.03532 -5.05 0.95574 -5.06 -0.841188 -5.07 -2.30994 -5.08 -3.45 -5.09 -4.29295 -5.1 -4.88827 -5.11 -5.29106 -5.12 -5.55313 -5.13 -5.71809 -5.14 -5.81954 -5.15 -5.88153 -5.16 -5.92018 -5.17 -5.94569 -5.18 -5.96411 -5.19 -5.97891 -5.2 -5.99192 -5.21 -6.00409 -5.22 -6.01589 -5.23 -6.02752 -5.24 -6.03911 -5.25 -6.05064 -5.26 -6.06216 -5.27 -6.07369 -5.28 -6.08521 -5.29 -6.09674 -5.3 -6.10826 -5.31 -6.1197 -5.32 -6.13107 -5.33 -6.14222 -5.34 -6.15282 -5.35 -6.16221 -5.36 -6.16898 -5.37 -6.17035 -5.38 -6.16109 -5.39 -6.13181 -5.4 -6.06657 -5.41 -5.9397 -5.42 -5.71232 -5.43 -5.32909 -5.44 -4.7167 -5.45 -3.78575 -5.46 -2.43802 -5.47 -0.580369 -5.48 1.8547 -5.49 4.88413 -5.5 8.44991 -5.51 12.4021 -5.52 16.4962 -5.53 20.4108 -5.54 23.7849 -5.55 26.2717 -5.56 27.5961 -5.57 27.6052 -5.58 26.2965 -5.59 23.8189 -5.6 20.444 -5.61 16.5175 -5.62 12.4007 -5.63 8.41704 -5.64 4.81362 -5.65 1.74337 -5.66 -0.733074 -5.67 -2.6307 -5.68 -4.01582 -5.69 -4.98113 -5.7 -5.62495 -5.71 -6.03708 -5.72 -6.29138 -5.73 -6.44373 -5.74 -6.53347 -5.75 -6.58663 -5.76 -6.61938 -5.77 -6.64129 -5.78 -6.65769 -5.79 -6.6714 -5.8 -6.68387 -5.81 -6.69579 -5.82 -6.70747 -5.83 -6.71909 -5.84 -6.73061 -5.85 -6.74207 -5.86 -6.7535 -5.87 -6.76477 -5.88 -6.77571 -5.89 -6.78592 -5.9 -6.79463 -5.91 -6.80036 -5.92 -6.80045 -5.93 -6.79034 -5.94 -6.76265 -5.95 -6.70612 -5.96 -6.60456 -5.97 -6.43636 -5.98 -6.17483 -5.99 -5.79025 -6 -5.25375 -6.01 -4.54345 -6.02 -3.65182 -6.03 -2.59332 -6.04 -1.40993 -6.05 -0.172587 -6.06 1.0233 -6.07 2.06859 -6.08 2.8562 -6.09 3.29883 -6.1 3.34462 -6.11 2.98692 -6.12 2.26554 -6.13 1.25924 -6.14 0.0713207 -6.15 -1.18791 -6.16 -2.41785 -6.17 -3.53995 -6.18 -4.50404 -6.19 -5.28834 -6.2 -5.89493 -6.21 -6.34246 -6.22 -6.65852 -6.23 -6.87309 -6.24 -7.01398 -6.25 -7.10434 -6.26 -7.16184 -6.27 -7.19904 -6.28 -7.2243 -6.29 -7.24287 -6.3 -7.25786 -6.31 -7.27101 -6.32 -7.28328 -6.33 -7.29497 -6.34 -7.30636 -6.35 -7.31729 -6.36 -7.32726 -6.37 -7.33511 -6.38 -7.33845 -6.39 -7.33254 -6.4 -7.30839 -6.41 -7.24995 -6.42 -7.12997 -6.43 -6.90464 -6.44 -6.50768 -6.45 -5.84488 -6.46 -4.79167 -6.47 -3.19645 -6.48 -0.893068 -6.49 2.27538 -6.5 6.42156 -6.51 11.5717 -6.52 17.6247 -6.53 24.3233 -6.54 31.2512 -6.55 37.8625 -6.56 43.5467 -6.57 47.719 -6.58 49.9185 -6.59 49.8916 -6.6 47.6402 -6.61 43.4209 -6.62 37.697 -6.63 31.0543 -6.64 24.1031 -6.65 17.3877 -6.66 11.3226 -6.67 6.16258 -6.68 2.007 -6.69 -1.17189 -6.7 -3.48763 -6.71 -5.09747 -6.72 -6.16748 -6.73 -6.84897 -6.74 -7.2661 -6.75 -7.51266 -6.76 -7.65461 -6.77 -7.73548 -6.78 -7.78235 -6.79 -7.81111 -6.8 -7.83067 -6.81 -7.84571 -6.82 -7.85851 -6.83 -7.87003 -6.84 -7.88037 -6.85 -7.88906 -6.86 -7.8946 -6.87 -7.89464 -6.88 -7.88505 -6.89 -7.85943 -6.9 -7.80834 -6.91 -7.71889 -6.92 -7.57475 -6.93 -7.35702 -6.94 -7.04641 -6.95 -6.62673 -6.96 -6.08953 -6.97 -5.43907 -6.98 -4.69658 -6.99 -3.90217 -7 -3.11323 -7.01 -2.39876 -7.02 -1.82999 -7.03 -1.46903 -7.04 -1.35793 -7.05 -1.5109 -7.06 -1.91156 -7.07 -2.51611 -7.08 -3.26141 -7.09 -4.076 -7.1 -4.89146 -7.11 -5.65149 -7.12 -6.31734 -7.13 -6.8691 -7.14 -7.30358 -7.15 -7.62995 -7.16 -7.86478 -7.17 -8.02743 -7.18 -8.13665 -7.19 -8.20857 -7.2 -8.25582 -7.21 -8.28757 -7.22 -8.30984 -7.23 -8.3267 -7.24 -8.34017 -7.25 -8.35095 -7.26 -8.3584 -7.27 -8.36008 -7.28 -8.35088 -7.29 -8.32127 -7.3 -8.25482 -7.31 -8.12479 -7.32 -7.89029 -7.33 -7.49248 -7.34 -6.85252 -7.35 -5.87289 -7.36 -4.4445 -7.37 -2.46096 -7.38 0.159396 -7.39 3.4462 -7.4 7.34918 -7.41 11.7174 -7.42 16.2932 -7.43 20.7285 -7.44 24.6229 -7.45 27.5817 -7.46 29.2812 -7.47 29.526 -7.48 28.2864 -7.49 25.7037 -7.5 22.0638 -7.51 17.7442 -7.52 13.1505 -7.53 8.65424 -7.54 4.54685 -7.55 1.01607 -7.56 -1.85518 -7.57 -4.07218 -7.58 -5.70206 -7.59 -6.84555 -7.6 -7.61285 -7.61 -8.10657 -7.62 -8.41222 -7.63 -8.59539 -7.64 -8.70259 -7.65 -8.76463 -7.66 -8.80041 -7.67 -8.82018 -7.68 -8.82788 -7.69 -8.82215 -7.7 -8.7963 -7.71 -8.73713 -7.72 -8.62299 -7.73 -8.42157 -7.74 -8.08799 -7.75 -7.56504 -7.76 -6.78579 -7.77 -5.68087 -7.78 -4.19057 -7.79 -2.28104 -7.8 0.037722 -7.81 2.69632 -7.82 5.55799 -7.83 8.42287 -7.84 11.0469 -7.85 13.1744 -7.86 14.5778 -7.87 15.0982 -7.88 14.674 -7.89 13.3531 -7.9 11.2833 -7.91 8.68546 -7.92 5.81405 -7.93 2.91663 -7.94 0.200069 -7.95 -2.1903 -7.96 -4.17672 -7.97 -5.74238 -7.98 -6.91652 -7.99 -7.75655 -8 -8.3313 -8.01 -8.70853 -8.02 -8.94692 -8.03 -9.09275 -8.04 -9.17954 -8.05 -9.22959 -8.06 -9.25593 -8.07 -9.26405 -8.08 -9.25272 -8.09 -9.21386 -8.1 -9.13141 -8.11 -8.97955 -8.12 -8.72093 -8.13 -8.30593 -8.14 -7.67394 -8.15 -6.75878 -8.16 -5.49797 -8.17 -3.84686 -8.18 -1.79542 -8.19 0.615343 -8.2 3.2822 -8.21 6.03841 -8.22 8.66584 -8.23 10.9209 -8.24 12.5705 -8.25 13.4317 -8.26 13.4043 -8.27 12.4902 -8.28 10.7928 -8.29 8.49759 -8.3 5.83855 -8.31 3.05897 -8.32 0.375561 -8.33 -2.04704 -8.34 -4.10786 -8.35 -5.76793 -8.36 -7.03877 -8.37 -7.96587 -8.38 -8.61207 -8.39 -9.04346 -8.4 -9.32003 -8.41 -9.49062 -8.42 -9.59137 -8.43 -9.64627 -8.44 -9.66849 -8.45 -9.66153 -8.46 -9.61963 -8.47 -9.52723 -8.48 -9.35785 -8.49 -9.07299 -8.5 -8.62213 -8.51 -7.94522 -8.52 -6.97883 -8.53 -5.66654 -8.54 -3.97359 -8.55 -1.90314 -8.56 0.488959 -8.57 3.08574 -8.58 5.7114 -8.59 8.1469 -8.6 10.1581 -8.61 11.5321 -8.62 12.1139 -8.63 11.8351 -8.64 10.7266 -8.65 8.91301 -8.66 6.58922 -8.67 3.98574 -8.68 1.33129 -8.69 -1.17924 -8.7 -3.40544 -8.71 -5.26861 -8.72 -6.74678 -8.73 -7.86225 -8.74 -8.66471 -8.75 -9.21581 -8.76 -9.57664 -8.77 -9.79934 -8.78 -9.92224 -8.79 -9.96732 -8.8 -9.93832 -8.81 -9.81829 -8.82 -9.56585 -8.83 -9.11048 -8.84 -8.34824 -8.85 -7.14038 -8.86 -5.31851 -8.87 -2.69973 -8.88 0.885705 -8.89 5.55497 -8.9 11.3255 -8.91 18.0707 -8.92 25.4908 -8.93 33.1121 -8.94 40.3234 -8.95 46.4508 -8.96 50.859 -8.97 53.0585 -8.98 52.7952 -8.99 50.0984 -9 45.275 -9.01 38.8521 -9.02 31.4815 -9.03 23.8322 -9.04 16.4922 -9.05 9.90213 -9.06 4.32558 -9.07 -0.142963 -9.08 -3.54494 -9.09 -6.01176 -9.1 -7.71888 -9.11 -8.84849 -9.12 -9.56471 -9.13 -10.0011 -9.14 -10.2578 -9.15 -10.4049 -9.16 -10.4881 -9.17 -10.5361 -9.18 -10.5653 -9.19 -10.5851 -9.2 -10.6004 -9.21 -10.6135 -9.22 -10.6257 -9.23 -10.6374 -9.24 -10.6491 -9.25 -10.6606 -9.26 -10.6722 -9.27 -10.6837 -9.28 -10.6952 -9.29 -10.7067 -9.3 -10.7183 -9.31 -10.7298 -9.32 -10.7413 -9.33 -10.7528 -9.34 -10.7644 -9.35 -10.7759 -9.36 -10.7874 -9.37 -10.7989 -9.38 -10.8105 -9.39 -10.8218 -9.4 -10.8331 -9.41 -10.8439 -9.42 -10.8537 -9.43 -10.8614 -9.44 -10.8645 -9.45 -10.8586 -9.46 -10.8351 -9.47 -10.7796 -9.48 -10.668 -9.49 -10.4626 -9.5 -10.1086 -9.51 -9.53068 -9.52 -8.63332 -9.53 -7.3062 -9.54 -5.4366 -9.55 -2.9299 -9.56 0.263436 -9.57 4.11854 -9.58 8.51159 -9.59 13.2084 -9.6 17.8739 -9.61 22.1048 -9.62 25.4851 -9.63 27.6517 -9.64 28.3587 -9.65 27.523 -9.66 25.2398 -9.67 21.765 -9.68 17.4674 -9.69 12.7643 -9.7 8.05566 -9.71 3.67053 -9.72 -0.164514 -9.73 -3.33297 -9.74 -5.81582 -9.75 -7.6663 -9.76 -8.98035 -9.77 -9.86969 -9.78 -10.4414 -9.79 -10.7854 -9.8 -10.9685 -9.81 -11.0338 -9.82 -11.0026 -9.83 -10.8781 -9.84 -10.6495 -9.85 -10.2976 -9.86 -9.80035 -9.87 -9.14059 -9.88 -8.31351 -9.89 -7.33429 -9.9 -6.24337 -9.91 -5.10737 -9.92 -4.01517 -9.93 -3.06735 -9.94 -2.36166 -9.95 -1.97672 -9.96 -1.95789 -9.97 -2.30868 -9.98 -2.99013 -9.99 -3.92814 -10 -5.02696 diff --git a/tests/testdata/Ni.cif b/tests/testdata/Ni.cif deleted file mode 100644 index c455635f..00000000 --- a/tests/testdata/Ni.cif +++ /dev/null @@ -1,236 +0,0 @@ -#------------------------------------------------------------------------------ -#$Date: 2008-03-10 08:25:41 +0000 (Mon, 10 Mar 2008) $ -#$Revision: 255 $ -#$URL: svn://cod.ibt.lt/cod/cif/9/9008476.cif $ -#------------------------------------------------------------------------------ -# -# This file is available in the Crystallography Open Database (COD), -# http://www.crystallography.net/ -# -# All data on this site have been placed in the public domain by the -# contributors. -# -data_9008476 -loop_ -_publ_author_name -'Wyckoff R W G' -_publ_section_title -; - Second edition. Interscience Publishers, New York, New York - Cubic closest packed, ccp, structure -; -_journal_name_full 'Crystal Structures' -_journal_page_first 7 -_journal_page_last 83 -_journal_volume 1 -_journal_year 1963 -_chemical_formula_sum Ni -_chemical_name_mineral Nickel -_symmetry_space_group_name_H-M 'F m 3 m' -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 90 -_cell_length_a 3.52387 -_cell_length_b 3.52387 -_cell_length_c 3.52387 -_cell_volume 43.758 -loop_ -_symmetry_equiv_pos_as_xyz -x,y,z -x,1/2+y,1/2+z -1/2+x,y,1/2+z -1/2+x,1/2+y,z -z,-x,y -z,1/2-x,1/2+y -1/2+z,-x,1/2+y -1/2+z,1/2-x,y --y,z,-x --y,1/2+z,1/2-x -1/2-y,z,1/2-x -1/2-y,1/2+z,-x -x,-y,z -x,1/2-y,1/2+z -1/2+x,-y,1/2+z -1/2+x,1/2-y,z --z,x,-y --z,1/2+x,1/2-y -1/2-z,x,1/2-y -1/2-z,1/2+x,-y -y,-z,x -y,1/2-z,1/2+x -1/2+y,-z,1/2+x -1/2+y,1/2-z,x --x,y,-z --x,1/2+y,1/2-z -1/2-x,y,1/2-z -1/2-x,1/2+y,-z -x,-z,-y -x,1/2-z,1/2-y -1/2+x,-z,1/2-y -1/2+x,1/2-z,-y --z,y,x --z,1/2+y,1/2+x -1/2-z,y,1/2+x -1/2-z,1/2+y,x -y,-x,-z -y,1/2-x,1/2-z -1/2+y,-x,1/2-z -1/2+y,1/2-x,-z --x,z,y --x,1/2+z,1/2+y -1/2-x,z,1/2+y -1/2-x,1/2+z,y -z,-y,-x -z,1/2-y,1/2-x -1/2+z,-y,1/2-x -1/2+z,1/2-y,-x --y,x,z --y,1/2+x,1/2+z -1/2-y,x,1/2+z -1/2-y,1/2+x,z -x,z,y -x,1/2+z,1/2+y -1/2+x,z,1/2+y -1/2+x,1/2+z,y --z,-y,-x --z,1/2-y,1/2-x -1/2-z,-y,1/2-x -1/2-z,1/2-y,-x -y,x,z -y,1/2+x,1/2+z -1/2+y,x,1/2+z -1/2+y,1/2+x,z --x,-z,-y --x,1/2-z,1/2-y -1/2-x,-z,1/2-y -1/2-x,1/2-z,-y -z,y,x -z,1/2+y,1/2+x -1/2+z,y,1/2+x -1/2+z,1/2+y,x --y,-x,-z --y,1/2-x,1/2-z -1/2-y,-x,1/2-z -1/2-y,1/2-x,-z -z,x,-y -z,1/2+x,1/2-y -1/2+z,x,1/2-y -1/2+z,1/2+x,-y --y,-z,x --y,1/2-z,1/2+x -1/2-y,-z,1/2+x -1/2-y,1/2-z,x -x,y,-z -x,1/2+y,1/2-z -1/2+x,y,1/2-z -1/2+x,1/2+y,-z --z,-x,y --z,1/2-x,1/2+y -1/2-z,-x,1/2+y -1/2-z,1/2-x,y -y,z,-x -y,1/2+z,1/2-x -1/2+y,z,1/2-x -1/2+y,1/2+z,-x --x,-y,z --x,1/2-y,1/2+z -1/2-x,-y,1/2+z -1/2-x,1/2-y,z --z,x,y --z,1/2+x,1/2+y -1/2-z,x,1/2+y -1/2-z,1/2+x,y -y,-z,-x -y,1/2-z,1/2-x -1/2+y,-z,1/2-x -1/2+y,1/2-z,-x --x,y,z --x,1/2+y,1/2+z -1/2-x,y,1/2+z -1/2-x,1/2+y,z -z,-x,-y -z,1/2-x,1/2-y -1/2+z,-x,1/2-y -1/2+z,1/2-x,-y --y,z,x --y,1/2+z,1/2+x -1/2-y,z,1/2+x -1/2-y,1/2+z,x -x,-y,-z -x,1/2-y,1/2-z -1/2+x,-y,1/2-z -1/2+x,1/2-y,-z --x,z,-y --x,1/2+z,1/2-y -1/2-x,z,1/2-y -1/2-x,1/2+z,-y -z,-y,x -z,1/2-y,1/2+x -1/2+z,-y,1/2+x -1/2+z,1/2-y,x --y,x,-z --y,1/2+x,1/2-z -1/2-y,x,1/2-z -1/2-y,1/2+x,-z -x,-z,y -x,1/2-z,1/2+y -1/2+x,-z,1/2+y -1/2+x,1/2-z,y --z,y,-x --z,1/2+y,1/2-x -1/2-z,y,1/2-x -1/2-z,1/2+y,-x -y,-x,z -y,1/2-x,1/2+z -1/2+y,-x,1/2+z -1/2+y,1/2-x,z --x,-z,y --x,1/2-z,1/2+y -1/2-x,-z,1/2+y -1/2-x,1/2-z,y -z,y,-x -z,1/2+y,1/2-x -1/2+z,y,1/2-x -1/2+z,1/2+y,-x --y,-x,z --y,1/2-x,1/2+z -1/2-y,-x,1/2+z -1/2-y,1/2-x,z -x,z,-y -x,1/2+z,1/2-y -1/2+x,z,1/2-y -1/2+x,1/2+z,-y --z,-y,x --z,1/2-y,1/2+x -1/2-z,-y,1/2+x -1/2-z,1/2-y,x -y,x,-z -y,1/2+x,1/2-z -1/2+y,x,1/2-z -1/2+y,1/2+x,-z --z,-x,-y --z,1/2-x,1/2-y -1/2-z,-x,1/2-y -1/2-z,1/2-x,-y -y,z,x -y,1/2+z,1/2+x -1/2+y,z,1/2+x -1/2+y,1/2+z,x --x,-y,-z --x,1/2-y,1/2-z -1/2-x,-y,1/2-z -1/2-x,1/2-y,-z -z,x,y -z,1/2+x,1/2+y -1/2+z,x,1/2+y -1/2+z,1/2+x,y --y,-z,-x --y,1/2-z,1/2-x -1/2-y,-z,1/2-x -1/2-y,1/2-z,-x -loop_ -_atom_site_label -_atom_site_fract_x -_atom_site_fract_y -_atom_site_fract_z -Ni 0.00000 0.00000 0.00000 diff --git a/tests/testdata/Ni.stru b/tests/testdata/Ni.stru deleted file mode 100644 index e13f2693..00000000 --- a/tests/testdata/Ni.stru +++ /dev/null @@ -1,33 +0,0 @@ -title structure Ni FCC -format pdffit -scale 1.000000 -sharp 0.000000, 0.000000, 1.000000, 0.000000 -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 -NI 0.00000000 0.00000000 0.00000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.00126651 0.00126651 0.00126651 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -NI 0.00000000 0.50000000 0.50000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.00126651 0.00126651 0.00126651 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -NI 0.50000000 0.00000000 0.50000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.00126651 0.00126651 0.00126651 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -NI 0.50000000 0.50000000 0.00000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.00126651 0.00126651 0.00126651 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 diff --git a/tests/testdata/Ni_primitive.stru b/tests/testdata/Ni_primitive.stru deleted file mode 100644 index d14e8df7..00000000 --- a/tests/testdata/Ni_primitive.stru +++ /dev/null @@ -1,15 +0,0 @@ -title nickel structure in a smallest primitive unit cell -format pdffit -scale 1.000000 -sharp 0.000000, 0.000000, 1.000000, 0.000000 -spcgr Fm-3m -cell 2.489016, 2.489016, 2.489016, 60.000000, 60.000000, 60.000000 -dcell 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000 -ncell 1, 1, 1, 1 -atoms -NI 0.00000000 0.00000000 0.00000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.00126651 0.00126651 0.00126651 - 0.00000000 0.00000000 0.00000000 - -0.00042217 -0.00042217 -0.00042217 - 0.00000000 0.00000000 0.00000000 diff --git a/tests/testdata/TiO2_rutile-fit.cif b/tests/testdata/TiO2_rutile-fit.cif deleted file mode 100644 index 9951458b..00000000 --- a/tests/testdata/TiO2_rutile-fit.cif +++ /dev/null @@ -1,59 +0,0 @@ -# TiO2_rutile fitted by PDFgui - -data_3D -_audit_creation_date 2010-03-21 -_audit_creation_method P_cif.py - -_chemical_name 'Rutile' -_chemical_formula_sum 'Ti O2' - -_cell_length_a 4.60586 -_cell_length_b 4.60586 -_cell_length_c 2.9544 -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 90 - -_symmetry_space_group_name_H-M 'P 42/m n m' - -loop_ -_symmetry_equiv_pos_as_xyz - 'x,y,z' - '-y,-x,z' - 'y,x,-z' - '1/2+y,1/2-x,1/2-z' - '1/2-y,1/2+x,1/2+z' - '1/2+x,1/2-y,1/2+z' - '1/2-x,1/2+y,1/2-z' - 'x,y,-z' - '-x,-y,z' - 'y,x,z' - '-y,-x,-z' - '1/2-y,1/2+x,1/2-z' - '1/2+y,1/2-x,1/2+z' - '1/2-x,1/2+y,1/2+z' - '1/2+x,1/2-y,1/2-z' - '-x,-y,-z' - -loop_ - _atom_site_label - _atom_site_type_symbol - _atom_site_fract_x - _atom_site_fract_y - _atom_site_fract_z - _atom_site_U_iso_or_equiv - _atom_site_adp_type - _atom_site_occupancy - Ti1 Ti 0.000000 0.000000 0.000000 0.007629 Uani 1.0000 - O1 O 0.305100 0.305100 0.000000 0.017058 Uani 1.0000 - -loop_ - _atom_site_aniso_label - _atom_site_aniso_U_11 - _atom_site_aniso_U_22 - _atom_site_aniso_U_33 - _atom_site_aniso_U_12 - _atom_site_aniso_U_13 - _atom_site_aniso_U_23 - Ti1 0.008698 0.008698 0.005492 0.000000 0.000000 0.000000 - O1 0.021733 0.021733 0.007707 0.000000 0.000000 0.000000 diff --git a/tests/testdata/TiO2_rutile-fit.fgr b/tests/testdata/TiO2_rutile-fit.fgr deleted file mode 100644 index d9e8154a..00000000 --- a/tests/testdata/TiO2_rutile-fit.fgr +++ /dev/null @@ -1,2911 +0,0 @@ -##### PDFgui fit -# type = X -# qmax = 26.00 -# qdamp = 0.0665649 -# scale = 0.655857 -# rmin = 1 -# rmax = 30.0001 -# delta2 = 2.309118 -##### start data -#L r(A) G(r) -1 -0.515795 -1.01 -0.586443 -1.02 -0.652914 -1.03 -0.713758 -1.04 -0.767798 -1.05 -0.814183 -1.06 -0.852415 -1.07 -0.88237 -1.08 -0.904285 -1.09 -0.918735 -1.1 -0.926588 -1.11 -0.928951 -1.12 -0.927096 -1.13 -0.922386 -1.14 -0.916197 -1.15 -0.909838 -1.16 -0.904485 -1.17 -0.901119 -1.18 -0.900481 -1.19 -0.90304 -1.2 -0.908988 -1.21 -0.918239 -1.22 -0.930458 -1.23 -0.945098 -1.24 -0.961449 -1.25 -0.978702 -1.26 -0.996013 -1.27 -1.01256 -1.28 -1.02763 -1.29 -1.04062 -1.3 -1.05113 -1.31 -1.05898 -1.32 -1.06419 -1.33 -1.067 -1.34 -1.06784 -1.35 -1.06732 -1.36 -1.06614 -1.37 -1.06505 -1.38 -1.06481 -1.39 -1.06612 -1.4 -1.06953 -1.41 -1.07547 -1.42 -1.08412 -1.43 -1.09548 -1.44 -1.10932 -1.45 -1.12519 -1.46 -1.14248 -1.47 -1.16041 -1.48 -1.17818 -1.49 -1.19493 -1.5 -1.20987 -1.51 -1.22232 -1.52 -1.23179 -1.53 -1.23798 -1.54 -1.24084 -1.55 -1.2406 -1.56 -1.2377 -1.57 -1.23279 -1.58 -1.22668 -1.59 -1.22024 -1.6 -1.21434 -1.61 -1.20972 -1.62 -1.20691 -1.63 -1.20613 -1.64 -1.20717 -1.65 -1.20937 -1.66 -1.21151 -1.67 -1.21183 -1.68 -1.20805 -1.69 -1.19737 -1.7 -1.17658 -1.71 -1.14219 -1.72 -1.09054 -1.73 -1.018 -1.74 -0.921126 -1.75 -0.796885 -1.76 -0.642821 -1.77 -0.45725 -1.78 -0.239419 -1.79 0.0103651 -1.8 0.290645 -1.81 0.598763 -1.82 0.930867 -1.83 1.28196 -1.84 1.64603 -1.85 2.01616 -1.86 2.38477 -1.87 2.74384 -1.88 3.08517 -1.89 3.40064 -1.9 3.68255 -1.91 3.92384 -1.92 4.11834 -1.93 4.26107 -1.94 4.34833 -1.95 4.37788 -1.96 4.34903 -1.97 4.26262 -1.98 4.12101 -1.99 3.92799 -2 3.68859 -2.01 3.40893 -2.02 3.09595 -2.03 2.7572 -2.04 2.40051 -2.05 2.03377 -2.06 1.66463 -2.07 1.30028 -2.08 0.947211 -2.09 0.611069 -2.1 0.296493 -2.11 0.00705189 -2.12 -0.254802 -2.13 -0.487712 -2.14 -0.691368 -2.15 -0.866401 -2.16 -1.01426 -2.17 -1.13706 -2.18 -1.23741 -2.19 -1.31824 -2.2 -1.38263 -2.21 -1.43364 -2.22 -1.4742 -2.23 -1.50696 -2.24 -1.5342 -2.25 -1.55779 -2.26 -1.57915 -2.27 -1.59926 -2.28 -1.61865 -2.29 -1.63749 -2.3 -1.65565 -2.31 -1.67275 -2.32 -1.68826 -2.33 -1.70159 -2.34 -1.71214 -2.35 -1.71938 -2.36 -1.72292 -2.37 -1.72251 -2.38 -1.71809 -2.39 -1.70975 -2.4 -1.69777 -2.41 -1.68256 -2.42 -1.66463 -2.43 -1.64452 -2.44 -1.62281 -2.45 -1.60004 -2.46 -1.57667 -2.47 -1.55305 -2.48 -1.52943 -2.49 -1.50589 -2.5 -1.48241 -2.51 -1.45883 -2.52 -1.43492 -2.53 -1.41036 -2.54 -1.38484 -2.55 -1.35802 -2.56 -1.32964 -2.57 -1.29951 -2.58 -1.26752 -2.59 -1.23371 -2.6 -1.1982 -2.61 -1.16123 -2.62 -1.12312 -2.63 -1.08426 -2.64 -1.04501 -2.65 -1.00575 -2.66 -0.966746 -2.67 -0.928167 -2.68 -0.890019 -2.69 -0.852129 -2.7 -0.814127 -2.71 -0.775449 -2.72 -0.735348 -2.73 -0.692934 -2.74 -0.647213 -2.75 -0.597156 -2.76 -0.541763 -2.77 -0.480149 -2.78 -0.411619 -2.79 -0.335745 -2.8 -0.252444 -2.81 -0.162026 -2.82 -0.0652407 -2.83 0.0367015 -2.84 0.142134 -2.85 0.248959 -2.86 0.354699 -2.87 0.456567 -2.88 0.551564 -2.89 0.636591 -2.9 0.708565 -2.91 0.764553 -2.92 0.801898 -2.93 0.81834 -2.94 0.812128 -2.95 0.78211 -2.96 0.7278 -2.97 0.64942 -2.98 0.547912 -2.99 0.42492 -3 0.282742 -3.01 0.124251 -3.02 -0.0472031 -3.03 -0.227915 -3.04 -0.413959 -3.05 -0.601333 -3.06 -0.7861 -3.07 -0.964528 -3.08 -1.13322 -3.09 -1.2892 -3.1 -1.43005 -3.11 -1.5539 -3.12 -1.65951 -3.13 -1.74624 -3.14 -1.81405 -3.15 -1.86338 -3.16 -1.89516 -3.17 -1.91063 -3.18 -1.91126 -3.19 -1.89864 -3.2 -1.87433 -3.21 -1.83975 -3.22 -1.7961 -3.23 -1.74423 -3.24 -1.68463 -3.25 -1.61732 -3.26 -1.54191 -3.27 -1.45755 -3.28 -1.36302 -3.29 -1.25676 -3.3 -1.13701 -3.31 -1.00185 -3.32 -0.849394 -3.33 -0.67785 -3.34 -0.485698 -3.35 -0.271789 -3.36 -0.0354625 -3.37 0.223355 -3.38 0.504078 -3.39 0.805409 -3.4 1.12531 -3.41 1.46103 -3.42 1.80909 -3.43 2.16539 -3.44 2.52528 -3.45 2.88364 -3.46 3.23505 -3.47 3.5739 -3.48 3.89453 -3.49 4.19141 -3.5 4.45927 -3.51 4.69323 -3.52 4.88897 -3.53 5.04281 -3.54 5.15182 -3.55 5.21388 -3.56 5.22776 -3.57 5.19313 -3.58 5.11057 -3.59 4.98151 -3.6 4.80826 -3.61 4.59387 -3.62 4.3421 -3.63 4.05729 -3.64 3.74425 -3.65 3.40819 -3.66 3.05451 -3.67 2.68875 -3.68 2.31644 -3.69 1.94298 -3.7 1.57354 -3.71 1.21293 -3.72 0.865589 -3.73 0.535418 -3.74 0.225797 -3.75 -0.0604867 -3.76 -0.321252 -3.77 -0.554934 -3.78 -0.760574 -3.79 -0.937793 -3.8 -1.08676 -3.81 -1.20815 -3.82 -1.30308 -3.83 -1.37303 -3.84 -1.41981 -3.85 -1.44548 -3.86 -1.45226 -3.87 -1.44247 -3.88 -1.41849 -3.89 -1.38267 -3.9 -1.3373 -3.91 -1.28456 -3.92 -1.22647 -3.93 -1.16492 -3.94 -1.10157 -3.95 -1.03792 -3.96 -0.975259 -3.97 -0.914707 -3.98 -0.857201 -3.99 -0.803526 -4 -0.754327 -4.01 -0.710135 -4.02 -0.67138 -4.03 -0.638414 -4.04 -0.61152 -4.05 -0.59093 -4.06 -0.576828 -4.07 -0.569353 -4.08 -0.568598 -4.09 -0.574604 -4.1 -0.587354 -4.11 -0.606755 -4.12 -0.632633 -4.13 -0.664711 -4.14 -0.702604 -4.15 -0.7458 -4.16 -0.793656 -4.17 -0.845393 -4.18 -0.90009 -4.19 -0.956692 -4.2 -1.01402 -4.21 -1.07076 -4.22 -1.12554 -4.23 -1.17686 -4.24 -1.22321 -4.25 -1.26303 -4.26 -1.29477 -4.27 -1.3169 -4.28 -1.32797 -4.29 -1.32662 -4.3 -1.31159 -4.31 -1.28178 -4.32 -1.23626 -4.33 -1.17429 -4.34 -1.09533 -4.35 -0.999078 -4.36 -0.885477 -4.37 -0.754718 -4.38 -0.607256 -4.39 -0.443819 -4.4 -0.265408 -4.41 -0.0733003 -4.42 0.130953 -4.43 0.345533 -4.44 0.568358 -4.45 0.797105 -4.46 1.02922 -4.47 1.26196 -4.48 1.49241 -4.49 1.71751 -4.5 1.93412 -4.51 2.13909 -4.52 2.32926 -4.53 2.50155 -4.54 2.65307 -4.55 2.7811 -4.56 2.88321 -4.57 2.95734 -4.58 3.00182 -4.59 3.01544 -4.6 2.99749 -4.61 2.94782 -4.62 2.86682 -4.63 2.75546 -4.64 2.61526 -4.65 2.44826 -4.66 2.25701 -4.67 2.04448 -4.68 1.81399 -4.69 1.56916 -4.7 1.31378 -4.71 1.05175 -4.72 0.786927 -4.73 0.523091 -4.74 0.2638 -4.75 0.0123259 -4.76 -0.22843 -4.77 -0.455994 -4.78 -0.668371 -4.79 -0.86407 -4.8 -1.04212 -4.81 -1.20205 -4.82 -1.34389 -4.83 -1.46811 -4.84 -1.57556 -4.85 -1.66744 -4.86 -1.7452 -4.87 -1.81046 -4.88 -1.86496 -4.89 -1.91045 -4.9 -1.94866 -4.91 -1.98121 -4.92 -2.00958 -4.93 -2.03504 -4.94 -2.05867 -4.95 -2.08131 -4.96 -2.10358 -4.97 -2.12589 -4.98 -2.14844 -4.99 -2.17127 -5 -2.19428 -5.01 -2.21729 -5.02 -2.24001 -5.03 -2.26215 -5.04 -2.28337 -5.05 -2.30335 -5.06 -2.32178 -5.07 -2.33834 -5.08 -2.35273 -5.09 -2.36461 -5.1 -2.37361 -5.11 -2.37929 -5.12 -2.38111 -5.13 -2.37839 -5.14 -2.37031 -5.15 -2.35585 -5.16 -2.33382 -5.17 -2.30284 -5.18 -2.26134 -5.19 -2.2076 -5.2 -2.13979 -5.21 -2.05602 -5.22 -1.95439 -5.23 -1.83306 -5.24 -1.69038 -5.25 -1.52491 -5.26 -1.33555 -5.27 -1.12161 -5.28 -0.882878 -5.29 -0.619708 -5.3 -0.333051 -5.31 -0.0244989 -5.32 0.303701 -5.33 0.648655 -5.34 1.00685 -5.35 1.37421 -5.36 1.74616 -5.37 2.11772 -5.38 2.48363 -5.39 2.83847 -5.4 3.17676 -5.41 3.49316 -5.42 3.78257 -5.43 4.04028 -5.44 4.26208 -5.45 4.44442 -5.46 4.58448 -5.47 4.68026 -5.48 4.73061 -5.49 4.73532 -5.5 4.69509 -5.51 4.61151 -5.52 4.48702 -5.53 4.32488 -5.54 4.12902 -5.55 3.90398 -5.56 3.65476 -5.57 3.38673 -5.58 3.10542 -5.59 2.81646 -5.6 2.52538 -5.61 2.23748 -5.62 1.95774 -5.63 1.69069 -5.64 1.44028 -5.65 1.20985 -5.66 1.00205 -5.67 0.818793 -5.68 0.661255 -5.69 0.529864 -5.7 0.424331 -5.71 0.343691 -5.72 0.286356 -5.73 0.250195 -5.74 0.232614 -5.75 0.230649 -5.76 0.241066 -5.77 0.260459 -5.78 0.285358 -5.79 0.312321 -5.8 0.338027 -5.81 0.359366 -5.82 0.373511 -5.83 0.377979 -5.84 0.370689 -5.85 0.349994 -5.86 0.314708 -5.87 0.264117 -5.88 0.197974 -5.89 0.116488 -5.9 0.0202922 -5.91 -0.0895883 -5.92 -0.211784 -5.93 -0.344635 -5.94 -0.486242 -5.95 -0.634538 -5.96 -0.787339 -5.97 -0.942417 -5.98 -1.09755 -5.99 -1.25059 -6 -1.39951 -6.01 -1.54244 -6.02 -1.67773 -6.03 -1.80397 -6.04 -1.91999 -6.05 -2.02492 -6.06 -2.11817 -6.07 -2.19944 -6.08 -2.26868 -6.09 -2.32614 -6.1 -2.37227 -6.11 -2.40776 -6.12 -2.43346 -6.13 -2.45036 -6.14 -2.45958 -6.15 -2.46227 -6.16 -2.45965 -6.17 -2.45289 -6.18 -2.44315 -6.19 -2.43148 -6.2 -2.41887 -6.21 -2.40613 -6.22 -2.39396 -6.23 -2.3829 -6.24 -2.37331 -6.25 -2.3654 -6.26 -2.35921 -6.27 -2.35464 -6.28 -2.35144 -6.29 -2.34928 -6.3 -2.3477 -6.31 -2.34619 -6.32 -2.34422 -6.33 -2.34122 -6.34 -2.33664 -6.35 -2.32999 -6.36 -2.32081 -6.37 -2.30874 -6.38 -2.2935 -6.39 -2.27491 -6.4 -2.25289 -6.41 -2.22748 -6.42 -2.19877 -6.43 -2.16698 -6.44 -2.13234 -6.45 -2.09516 -6.46 -2.05575 -6.47 -2.0144 -6.48 -1.97138 -6.49 -1.9269 -6.5 -1.88109 -6.51 -1.83397 -6.52 -1.78546 -6.53 -1.73536 -6.54 -1.68334 -6.55 -1.62896 -6.56 -1.57167 -6.57 -1.51083 -6.58 -1.44576 -6.59 -1.37571 -6.6 -1.29998 -6.61 -1.21787 -6.62 -1.12879 -6.63 -1.03224 -6.64 -0.927893 -6.65 -0.815604 -6.66 -0.695436 -6.67 -0.567688 -6.68 -0.432904 -6.69 -0.291877 -6.7 -0.145642 -6.71 0.00453966 -6.72 0.157203 -6.73 0.310717 -6.74 0.463323 -6.75 0.613185 -6.76 0.758438 -6.77 0.897248 -6.78 1.02787 -6.79 1.14868 -6.8 1.25827 -6.81 1.35545 -6.82 1.43931 -6.83 1.50924 -6.84 1.56495 -6.85 1.60648 -6.86 1.63419 -6.87 1.64877 -6.88 1.65117 -6.89 1.64261 -6.9 1.6245 -6.91 1.59842 -6.92 1.56604 -6.93 1.52907 -6.94 1.48922 -6.95 1.44811 -6.96 1.40723 -6.97 1.36792 -6.98 1.3313 -6.99 1.29823 -7 1.26935 -7.01 1.24501 -7.02 1.22534 -7.03 1.21019 -7.04 1.19922 -7.05 1.19194 -7.06 1.1877 -7.07 1.1858 -7.08 1.18552 -7.09 1.18618 -7.1 1.18722 -7.11 1.18819 -7.12 1.1889 -7.13 1.18934 -7.14 1.18983 -7.15 1.19091 -7.16 1.19346 -7.17 1.1986 -7.18 1.20772 -7.19 1.22241 -7.2 1.24439 -7.21 1.27551 -7.22 1.31758 -7.23 1.37239 -7.24 1.44153 -7.25 1.52637 -7.26 1.62792 -7.27 1.7468 -7.28 1.88313 -7.29 2.03652 -7.3 2.20595 -7.31 2.38982 -7.32 2.58593 -7.33 2.79147 -7.34 3.00307 -7.35 3.21687 -7.36 3.4286 -7.37 3.63366 -7.38 3.82728 -7.39 4.00456 -7.4 4.1607 -7.41 4.29109 -7.42 4.39142 -7.43 4.45789 -7.44 4.48725 -7.45 4.47695 -7.46 4.42523 -7.47 4.33116 -7.48 4.19469 -7.49 4.01669 -7.5 3.79888 -7.51 3.54385 -7.52 3.25493 -7.53 2.93618 -7.54 2.59218 -7.55 2.22799 -7.56 1.84896 -7.57 1.46058 -7.58 1.06837 -7.59 0.677707 -7.6 0.293688 -7.61 -0.0789814 -7.62 -0.436095 -7.63 -0.774031 -7.64 -1.08981 -7.65 -1.38112 -7.66 -1.64636 -7.67 -1.88457 -7.68 -2.09544 -7.69 -2.27923 -7.7 -2.43669 -7.71 -2.56899 -7.72 -2.67762 -7.73 -2.76426 -7.74 -2.83075 -7.75 -2.8789 -7.76 -2.91052 -7.77 -2.92724 -7.78 -2.93056 -7.79 -2.92174 -7.8 -2.90181 -7.81 -2.87157 -7.82 -2.83162 -7.83 -2.78236 -7.84 -2.72407 -7.85 -2.65695 -7.86 -2.58118 -7.87 -2.49697 -7.88 -2.40464 -7.89 -2.30463 -7.9 -2.19762 -7.91 -2.08447 -7.92 -1.96629 -7.93 -1.84443 -7.94 -1.72046 -7.95 -1.59614 -7.96 -1.47338 -7.97 -1.35419 -7.98 -1.2406 -7.99 -1.13461 -8 -1.03811 -8.01 -0.952792 -8.02 -0.880118 -8.03 -0.821236 -8.04 -0.776939 -8.05 -0.747632 -8.06 -0.733307 -8.07 -0.73354 -8.08 -0.747498 -8.09 -0.773962 -8.1 -0.811361 -8.11 -0.857823 -8.12 -0.911229 -8.13 -0.969275 -8.14 -1.02954 -8.15 -1.08955 -8.16 -1.14685 -8.17 -1.19905 -8.18 -1.2439 -8.19 -1.27933 -8.2 -1.30348 -8.21 -1.31474 -8.22 -1.31177 -8.23 -1.29351 -8.24 -1.2592 -8.25 -1.20833 -8.26 -1.14072 -8.27 -1.05644 -8.28 -0.955798 -8.29 -0.839382 -8.3 -0.707997 -8.31 -0.562675 -8.32 -0.404658 -8.33 -0.235387 -8.34 -0.056497 -8.35 0.130199 -8.36 0.322717 -8.37 0.518918 -8.38 0.716525 -8.39 0.91314 -8.4 1.10628 -8.41 1.2934 -8.42 1.47194 -8.43 1.63936 -8.44 1.79321 -8.45 1.93116 -8.46 2.05107 -8.47 2.15104 -8.48 2.22951 -8.49 2.28523 -8.5 2.31738 -8.51 2.32557 -8.52 2.3099 -8.53 2.27093 -8.54 2.20971 -8.55 2.12775 -8.56 2.02702 -8.57 1.90984 -8.58 1.7789 -8.59 1.63712 -8.6 1.48761 -8.61 1.33357 -8.62 1.17819 -8.63 1.02458 -8.64 0.875664 -8.65 0.734091 -8.66 0.602189 -8.67 0.48189 -8.68 0.374691 -8.69 0.281624 -8.7 0.203252 -8.71 0.13967 -8.72 0.0905368 -8.73 0.0551066 -8.74 0.0322878 -8.75 0.0207043 -8.76 0.0187665 -8.77 0.0247475 -8.78 0.036859 -8.79 0.0533259 -8.8 0.0724553 -8.81 0.0926972 -8.82 0.112695 -8.83 0.131325 -8.84 0.14772 -8.85 0.161282 -8.86 0.171681 -8.87 0.178841 -8.88 0.182914 -8.89 0.184247 -8.9 0.183337 -8.91 0.180791 -8.92 0.17727 -8.93 0.173447 -8.94 0.169958 -8.95 0.167358 -8.96 0.166095 -8.97 0.166472 -8.98 0.168637 -8.99 0.172566 -9 0.178067 -9.01 0.184784 -9.02 0.192214 -9.03 0.199725 -9.04 0.206583 -9.05 0.211983 -9.06 0.215079 -9.07 0.215013 -9.08 0.210951 -9.09 0.202107 -9.1 0.18777 -9.11 0.167326 -9.12 0.140272 -9.13 0.106232 -9.14 0.064964 -9.15 0.0163592 -9.16 -0.0395536 -9.17 -0.102615 -9.18 -0.172543 -9.19 -0.248938 -9.2 -0.3313 -9.21 -0.419036 -9.22 -0.511472 -9.23 -0.607869 -9.24 -0.707434 -9.25 -0.809332 -9.26 -0.912698 -9.27 -1.01665 -9.28 -1.12029 -9.29 -1.22274 -9.3 -1.32312 -9.31 -1.42059 -9.32 -1.51434 -9.33 -1.60362 -9.34 -1.68772 -9.35 -1.76603 -9.36 -1.838 -9.37 -1.90318 -9.38 -1.96124 -9.39 -2.01192 -9.4 -2.05511 -9.41 -2.09079 -9.42 -2.11909 -9.43 -2.14022 -9.44 -2.1545 -9.45 -2.16237 -9.46 -2.16433 -9.47 -2.16097 -9.48 -2.15291 -9.49 -2.14083 -9.5 -2.12538 -9.51 -2.10723 -9.52 -2.08701 -9.53 -2.06529 -9.54 -2.04257 -9.55 -2.01926 -9.56 -1.99564 -9.57 -1.97191 -9.58 -1.94811 -9.59 -1.92416 -9.6 -1.89986 -9.61 -1.87485 -9.62 -1.84867 -9.63 -1.82077 -9.64 -1.79047 -9.65 -1.75704 -9.66 -1.71968 -9.67 -1.67756 -9.68 -1.62987 -9.69 -1.57579 -9.7 -1.51457 -9.71 -1.44552 -9.72 -1.36807 -9.73 -1.28176 -9.74 -1.18629 -9.75 -1.08155 -9.76 -0.967603 -9.77 -0.844718 -9.78 -0.713392 -9.79 -0.574343 -9.8 -0.428515 -9.81 -0.277069 -9.82 -0.121379 -9.83 0.0369909 -9.84 0.196304 -9.85 0.354686 -9.86 0.510154 -9.87 0.660663 -9.88 0.804143 -9.89 0.938554 -9.9 1.06193 -9.91 1.17246 -9.92 1.26847 -9.93 1.34856 -9.94 1.41159 -9.95 1.45676 -9.96 1.4836 -9.97 1.49206 -9.98 1.48247 -9.99 1.45557 -10 1.41252 -10.01 1.35486 -10.02 1.28449 -10.03 1.20366 -10.04 1.11486 -10.05 1.02082 -10.06 0.924402 -10.07 0.828544 -10.08 0.736179 -10.09 0.650152 -10.1 0.573137 -10.11 0.507563 -10.12 0.455538 -10.13 0.418788 -10.14 0.398596 -10.15 0.395764 -10.16 0.410577 -10.17 0.442792 -10.18 0.491632 -10.19 0.555801 -10.2 0.633513 -10.21 0.722537 -10.22 0.82025 -10.23 0.923704 -10.24 1.02971 -10.25 1.13491 -10.26 1.23588 -10.27 1.32923 -10.28 1.41167 -10.29 1.48011 -10.3 1.53177 -10.31 1.56424 -10.32 1.57553 -10.33 1.56418 -10.34 1.52924 -10.35 1.47035 -10.36 1.38775 -10.37 1.28227 -10.38 1.15529 -10.39 1.0088 -10.4 0.845251 -10.41 0.667573 -10.42 0.479085 -10.43 0.283416 -10.44 0.0844284 -10.45 -0.113872 -10.46 -0.307432 -10.47 -0.492241 -10.48 -0.664424 -10.49 -0.820333 -10.5 -0.956624 -10.51 -1.07034 -10.52 -1.15896 -10.53 -1.22048 -10.54 -1.25342 -10.55 -1.25687 -10.56 -1.23051 -10.57 -1.17459 -10.58 -1.08991 -10.59 -0.977827 -10.6 -0.840157 -10.61 -0.679162 -10.62 -0.497471 -10.63 -0.298009 -10.64 -0.0839216 -10.65 0.141506 -10.66 0.374929 -10.67 0.613022 -10.68 0.852552 -10.69 1.09045 -10.7 1.32387 -10.71 1.55023 -10.72 1.76727 -10.73 1.97305 -10.74 2.16601 -10.75 2.34493 -10.76 2.50892 -10.77 2.65744 -10.78 2.79025 -10.79 2.90736 -10.8 3.00899 -10.81 3.09555 -10.82 3.16757 -10.83 3.22566 -10.84 3.27046 -10.85 3.30258 -10.86 3.32262 -10.87 3.33109 -10.88 3.3284 -10.89 3.31486 -10.9 3.29067 -10.91 3.25593 -10.92 3.21064 -10.93 3.15472 -10.94 3.08804 -10.95 3.01044 -10.96 2.92176 -10.97 2.82188 -10.98 2.71074 -10.99 2.58835 -11 2.45486 -11.01 2.31052 -11.02 2.15573 -11.03 1.99103 -11.04 1.81712 -11.05 1.63483 -11.06 1.44513 -11.07 1.24908 -11.08 1.04788 -11.09 0.842745 -11.1 0.634978 -11.11 0.425883 -11.12 0.216761 -11.13 0.00888435 -11.14 -0.196528 -11.15 -0.398325 -11.16 -0.595446 -11.17 -0.786925 -11.18 -0.971901 -11.19 -1.14962 -11.2 -1.31945 -11.21 -1.48084 -11.22 -1.63335 -11.23 -1.77665 -11.24 -1.91046 -11.25 -2.03461 -11.26 -2.14895 -11.27 -2.25343 -11.28 -2.34801 -11.29 -2.43272 -11.3 -2.50761 -11.31 -2.57277 -11.32 -2.6283 -11.33 -2.67437 -11.34 -2.71113 -11.35 -2.73881 -11.36 -2.75763 -11.37 -2.76787 -11.38 -2.76982 -11.39 -2.76379 -11.4 -2.75014 -11.41 -2.72922 -11.42 -2.7014 -11.43 -2.66704 -11.44 -2.62651 -11.45 -2.58012 -11.46 -2.52818 -11.47 -2.47094 -11.48 -2.40857 -11.49 -2.34121 -11.5 -2.26891 -11.51 -2.19162 -11.52 -2.10926 -11.53 -2.02162 -11.54 -1.92847 -11.55 -1.82951 -11.56 -1.72439 -11.57 -1.61277 -11.58 -1.49431 -11.59 -1.36869 -11.6 -1.23569 -11.61 -1.09517 -11.62 -0.947113 -11.63 -0.791677 -11.64 -0.629198 -11.65 -0.460223 -11.66 -0.285527 -11.67 -0.106127 -11.68 0.0767145 -11.69 0.261492 -11.7 0.446463 -11.71 0.629671 -11.72 0.808968 -11.73 0.982055 -11.74 1.14652 -11.75 1.29987 -11.76 1.43964 -11.77 1.56336 -11.78 1.66872 -11.79 1.75354 -11.8 1.81587 -11.81 1.85407 -11.82 1.86682 -11.83 1.85317 -11.84 1.81261 -11.85 1.74508 -11.86 1.65096 -11.87 1.53114 -11.88 1.38695 -11.89 1.2202 -11.9 1.03311 -11.91 0.828303 -11.92 0.608723 -11.93 0.377617 -11.94 0.138444 -11.95 -0.105183 -11.96 -0.349578 -11.97 -0.59105 -11.98 -0.825983 -11.99 -1.05091 -12 -1.26256 -12.01 -1.45797 -12.02 -1.6345 -12.03 -1.78987 -12.04 -1.92224 -12.05 -2.03022 -12.06 -2.11286 -12.07 -2.1697 -12.08 -2.20073 -12.09 -2.20639 -12.1 -2.18755 -12.11 -2.14546 -12.12 -2.08175 -12.13 -1.99831 -12.14 -1.89733 -12.15 -1.78118 -12.16 -1.65236 -12.17 -1.51349 -12.18 -1.36718 -12.19 -1.21605 -12.2 -1.06262 -12.21 -0.909281 -12.22 -0.758254 -12.23 -0.611542 -12.24 -0.470896 -12.25 -0.337786 -12.26 -0.213381 -12.27 -0.0985266 -12.28 0.0062607 -12.29 0.100796 -12.3 0.185222 -12.31 0.259997 -12.32 0.325875 -12.33 0.383881 -12.34 0.435274 -12.35 0.481514 -12.36 0.524211 -12.37 0.565082 -12.38 0.605889 -12.39 0.648387 -12.4 0.694269 -12.41 0.745098 -12.42 0.80226 -12.43 0.866904 -12.44 0.939895 -12.45 1.02177 -12.46 1.1127 -12.47 1.21248 -12.48 1.32049 -12.49 1.43572 -12.5 1.55674 -12.51 1.68177 -12.52 1.80867 -12.53 1.93504 -12.54 2.05821 -12.55 2.17535 -12.56 2.28355 -12.57 2.37987 -12.58 2.46143 -12.59 2.52552 -12.6 2.56964 -12.61 2.5916 -12.62 2.5896 -12.63 2.56224 -12.64 2.50861 -12.65 2.42832 -12.66 2.32148 -12.67 2.18873 -12.68 2.03125 -12.69 1.85067 -12.7 1.64908 -12.71 1.42895 -12.72 1.19309 -12.73 0.944523 -12.74 0.686473 -12.75 0.422238 -12.76 0.155124 -12.77 -0.111636 -12.78 -0.374957 -12.79 -0.631965 -12.8 -0.880057 -12.81 -1.11695 -12.82 -1.3407 -12.83 -1.54976 -12.84 -1.74293 -12.85 -1.91943 -12.86 -2.0788 -12.87 -2.22096 -12.88 -2.34611 -12.89 -2.45475 -12.9 -2.54759 -12.91 -2.62551 -12.92 -2.68955 -12.93 -2.74081 -12.94 -2.78045 -12.95 -2.80963 -12.96 -2.82948 -12.97 -2.84106 -12.98 -2.84534 -12.99 -2.8432 -13 -2.83541 -13.01 -2.8226 -13.02 -2.80528 -13.03 -2.78386 -13.04 -2.75864 -13.05 -2.72978 -13.06 -2.69741 -13.07 -2.66153 -13.08 -2.62211 -13.09 -2.57906 -13.1 -2.53224 -13.11 -2.4815 -13.12 -2.42665 -13.13 -2.3675 -13.14 -2.30384 -13.15 -2.23549 -13.16 -2.16223 -13.17 -2.08389 -13.18 -2.00028 -13.19 -1.91123 -13.2 -1.8166 -13.21 -1.71624 -13.22 -1.61006 -13.23 -1.49797 -13.24 -1.37992 -13.25 -1.25589 -13.26 -1.12591 -13.27 -0.990044 -13.28 -0.848418 -13.29 -0.70121 -13.3 -0.548657 -13.31 -0.391063 -13.32 -0.228802 -13.33 -0.0623142 -13.34 0.107882 -13.35 0.281198 -13.36 0.456969 -13.37 0.63446 -13.38 0.812866 -13.39 0.991315 -13.4 1.16888 -13.41 1.34457 -13.42 1.51736 -13.43 1.68618 -13.44 1.84994 -13.45 2.00755 -13.46 2.1579 -13.47 2.29993 -13.48 2.43258 -13.49 2.55487 -13.5 2.66589 -13.51 2.76481 -13.52 2.85092 -13.53 2.92364 -13.54 2.98251 -13.55 3.02726 -13.56 3.05776 -13.57 3.07407 -13.58 3.0764 -13.59 3.06517 -13.6 3.04093 -13.61 3.00441 -13.62 2.95647 -13.63 2.89809 -13.64 2.83032 -13.65 2.7543 -13.66 2.6712 -13.67 2.58217 -13.68 2.48835 -13.69 2.39081 -13.7 2.29054 -13.71 2.18841 -13.72 2.08518 -13.73 1.98144 -13.74 1.87768 -13.75 1.77421 -13.76 1.67124 -13.77 1.56884 -13.78 1.467 -13.79 1.36567 -13.8 1.26474 -13.81 1.16411 -13.82 1.06373 -13.83 0.963628 -13.84 0.863924 -13.85 0.764879 -13.86 0.666901 -13.87 0.570561 -13.88 0.476598 -13.89 0.385909 -13.9 0.299533 -13.91 0.21863 -13.92 0.144443 -13.93 0.0782582 -13.94 0.0213578 -13.95 -0.0250295 -13.96 -0.0597813 -13.97 -0.0819339 -13.98 -0.09073 -13.99 -0.0856633 -14 -0.066514 -14.01 -0.0333771 -14.02 0.0133213 -14.03 0.0728182 -14.04 0.144019 -14.05 0.225518 -14.06 0.315624 -14.07 0.412402 -14.08 0.513724 -14.09 0.617319 -14.1 0.720837 -14.11 0.821913 -14.12 0.918225 -14.13 1.00756 -14.14 1.08787 -14.15 1.15733 -14.16 1.21435 -14.17 1.25766 -14.18 1.28627 -14.19 1.29955 -14.2 1.29717 -14.21 1.27914 -14.22 1.24576 -14.23 1.19761 -14.24 1.13551 -14.25 1.06048 -14.26 0.973714 -14.27 0.876516 -14.28 0.77027 -14.29 0.656392 -14.3 0.536294 -14.31 0.411344 -14.32 0.282844 -14.33 0.151995 -14.34 0.0198866 -14.35 -0.112521 -14.36 -0.244401 -14.37 -0.375066 -14.38 -0.503959 -14.39 -0.630653 -14.4 -0.754835 -14.41 -0.876292 -14.42 -0.9949 -14.43 -1.1106 -14.44 -1.22339 -14.45 -1.3333 -14.46 -1.44036 -14.47 -1.54461 -14.48 -1.64608 -14.49 -1.74473 -14.5 -1.84052 -14.51 -1.93331 -14.52 -2.02289 -14.53 -2.10901 -14.54 -2.19128 -14.55 -2.26926 -14.56 -2.3424 -14.57 -2.4101 -14.58 -2.47163 -14.59 -2.52623 -14.6 -2.57308 -14.61 -2.61132 -14.62 -2.64006 -14.63 -2.65844 -14.64 -2.66562 -14.65 -2.66084 -14.66 -2.64342 -14.67 -2.6128 -14.68 -2.56858 -14.69 -2.51054 -14.7 -2.43865 -14.71 -2.3531 -14.72 -2.25433 -14.73 -2.143 -14.74 -2.02001 -14.75 -1.88649 -14.76 -1.74378 -14.77 -1.59342 -14.78 -1.43707 -14.79 -1.27656 -14.8 -1.11377 -14.81 -0.950598 -14.82 -0.788958 -14.83 -0.630679 -14.84 -0.477487 -14.85 -0.330954 -14.86 -0.192464 -14.87 -0.063178 -14.88 0.0559829 -14.89 0.164357 -14.9 0.261542 -14.91 0.347397 -14.92 0.422022 -14.93 0.48574 -14.94 0.539068 -14.95 0.582683 -14.96 0.617383 -14.97 0.644044 -14.98 0.663585 -14.99 0.676923 -15 0.68494 -15.01 0.688454 -15.02 0.688188 -15.03 0.684758 -15.04 0.678663 -15.05 0.670276 -15.06 0.659856 -15.07 0.647555 -15.08 0.633439 -15.09 0.617504 -15.1 0.599704 -15.11 0.579978 -15.12 0.558269 -15.13 0.534555 -15.14 0.50886 -15.15 0.481278 -15.16 0.451977 -15.17 0.421204 -15.18 0.389286 -15.19 0.356619 -15.2 0.323658 -15.21 0.290897 -15.22 0.258853 -15.23 0.228041 -15.24 0.198954 -15.25 0.172043 -15.26 0.147699 -15.27 0.126235 -15.28 0.107885 -15.29 0.0927929 -15.3 0.0810196 -15.31 0.0725488 -15.32 0.0673014 -15.33 0.0651534 -15.34 0.0659578 -15.35 0.0695682 -15.36 0.0758633 -15.37 0.0847702 -15.38 0.0962853 -15.39 0.110491 -15.4 0.127566 -15.41 0.147791 -15.42 0.171544 -15.43 0.199291 -15.44 0.231568 -15.45 0.268952 -15.46 0.312034 -15.47 0.361378 -15.48 0.417483 -15.49 0.480739 -15.5 0.551389 -15.51 0.629484 -15.52 0.714857 -15.53 0.807088 -15.54 0.905487 -15.55 1.00908 -15.56 1.11663 -15.57 1.22662 -15.58 1.33727 -15.59 1.44663 -15.6 1.55255 -15.61 1.65277 -15.62 1.74499 -15.63 1.82688 -15.64 1.89622 -15.65 1.95091 -15.66 1.98904 -15.67 2.00897 -15.68 2.00938 -15.69 1.98928 -15.7 1.9481 -15.71 1.88565 -15.72 1.80216 -15.73 1.69828 -15.74 1.57508 -15.75 1.43395 -15.76 1.27667 -15.77 1.10526 -15.78 0.922009 -15.79 0.729352 -15.8 0.529849 -15.81 0.326104 -15.82 0.120708 -15.83 -0.0838251 -15.84 -0.285108 -15.85 -0.480932 -15.86 -0.669303 -15.87 -0.848476 -15.88 -1.01698 -15.89 -1.17362 -15.9 -1.31749 -15.91 -1.44796 -15.92 -1.5647 -15.93 -1.66758 -15.94 -1.75673 -15.95 -1.83245 -15.96 -1.89521 -15.97 -1.9456 -15.98 -1.98431 -15.99 -2.01207 -16 -2.02966 -16.01 -2.03784 -16.02 -2.03734 -16.03 -2.02889 -16.04 -2.01311 -16.05 -1.99059 -16.06 -1.96185 -16.07 -1.92733 -16.08 -1.88743 -16.09 -1.84248 -16.1 -1.79276 -16.11 -1.73855 -16.12 -1.68009 -16.13 -1.61761 -16.14 -1.55137 -16.15 -1.48164 -16.16 -1.40871 -16.17 -1.3329 -16.18 -1.25458 -16.19 -1.17416 -16.2 -1.09206 -16.21 -1.00876 -16.22 -0.924746 -16.23 -0.84053 -16.24 -0.756624 -16.25 -0.673537 -16.26 -0.591766 -16.27 -0.511778 -16.28 -0.434012 -16.29 -0.358861 -16.3 -0.286676 -16.31 -0.217752 -16.32 -0.152335 -16.33 -0.0906187 -16.34 -0.0327483 -16.35 0.0211757 -16.36 0.0710911 -16.37 0.116967 -16.38 0.158794 -16.39 0.196583 -16.4 0.230348 -16.41 0.260109 -16.42 0.285881 -16.43 0.307675 -16.44 0.325494 -16.45 0.339337 -16.46 0.349199 -16.47 0.355082 -16.48 0.356995 -16.49 0.354973 -16.5 0.349078 -16.51 0.339419 -16.52 0.326155 -16.53 0.309512 -16.54 0.289789 -16.55 0.267367 -16.56 0.242714 -16.57 0.216387 -16.58 0.189032 -16.59 0.161376 -16.6 0.134224 -16.61 0.108444 -16.62 0.0849522 -16.63 0.0646946 -16.64 0.0486268 -16.65 0.0376907 -16.66 0.0327893 -16.67 0.0347628 -16.68 0.0443625 -16.69 0.0622276 -16.7 0.0888622 -16.71 0.124616 -16.72 0.169667 -16.73 0.224009 -16.74 0.287442 -16.75 0.359569 -16.76 0.439793 -16.77 0.527328 -16.78 0.6212 -16.79 0.720271 -16.8 0.823248 -16.81 0.928712 -16.82 1.03514 -16.83 1.14093 -16.84 1.24442 -16.85 1.34397 -16.86 1.43791 -16.87 1.52464 -16.88 1.60262 -16.89 1.67042 -16.9 1.72673 -16.91 1.7704 -16.92 1.80045 -16.93 1.81608 -16.94 1.81668 -16.95 1.80188 -16.96 1.77148 -16.97 1.72554 -16.98 1.66428 -16.99 1.58816 -17 1.49782 -17.01 1.39409 -17.02 1.27794 -17.03 1.1505 -17.04 1.01303 -17.05 0.866871 -17.06 0.713462 -17.07 0.554292 -17.08 0.390882 -17.09 0.224768 -17.1 0.0574743 -17.11 -0.109503 -17.12 -0.274712 -17.13 -0.436766 -17.14 -0.594351 -17.15 -0.74624 -17.16 -0.8913 -17.17 -1.0285 -17.18 -1.15692 -17.19 -1.27573 -17.2 -1.38423 -17.21 -1.48182 -17.22 -1.56799 -17.23 -1.64237 -17.24 -1.70464 -17.25 -1.75461 -17.26 -1.79219 -17.27 -1.81734 -17.28 -1.83015 -17.29 -1.83075 -17.3 -1.81938 -17.31 -1.79634 -17.32 -1.76202 -17.33 -1.71687 -17.34 -1.66141 -17.35 -1.59622 -17.36 -1.52194 -17.37 -1.43927 -17.38 -1.34896 -17.39 -1.25179 -17.4 -1.14857 -17.41 -1.04015 -17.42 -0.92737 -17.43 -0.811079 -17.44 -0.692117 -17.45 -0.571301 -17.46 -0.449417 -17.47 -0.327208 -17.48 -0.205371 -17.49 -0.0845462 -17.5 0.0346841 -17.51 0.151799 -17.52 0.266339 -17.53 0.377902 -17.54 0.486139 -17.55 0.590748 -17.56 0.691466 -17.57 0.788058 -17.58 0.880312 -17.59 0.968023 -17.6 1.05099 -17.61 1.12902 -17.62 1.20187 -17.63 1.26934 -17.64 1.33118 -17.65 1.38713 -17.66 1.43695 -17.67 1.48037 -17.68 1.51715 -17.69 1.5471 -17.7 1.57002 -17.71 1.58581 -17.72 1.59442 -17.73 1.59587 -17.74 1.5903 -17.75 1.57792 -17.76 1.55906 -17.77 1.53416 -17.78 1.50375 -17.79 1.46846 -17.8 1.42899 -17.81 1.38612 -17.82 1.34065 -17.83 1.29342 -17.84 1.24525 -17.85 1.19694 -17.86 1.14922 -17.87 1.10275 -17.88 1.05808 -17.89 1.01563 -17.9 0.975706 -17.91 0.938454 -17.92 0.903877 -17.93 0.871838 -17.94 0.842064 -17.95 0.814162 -17.96 0.78764 -17.97 0.76193 -17.98 0.736414 -17.99 0.710452 -18 0.683411 -18.01 0.654698 -18.02 0.623778 -18.03 0.590206 -18.04 0.553639 -18.05 0.513855 -18.06 0.470757 -18.07 0.424381 -18.08 0.374887 -18.09 0.322552 -18.1 0.267756 -18.11 0.210962 -18.12 0.152696 -18.13 0.0935189 -18.14 0.0340024 -18.15 -0.0252963 -18.16 -0.0838597 -18.17 -0.141231 -18.18 -0.197035 -18.19 -0.250987 -18.2 -0.302908 -18.21 -0.352725 -18.22 -0.400471 -18.23 -0.446277 -18.24 -0.490363 -18.25 -0.533022 -18.26 -0.5746 -18.27 -0.615477 -18.28 -0.656046 -18.29 -0.696686 -18.3 -0.737745 -18.31 -0.77952 -18.32 -0.822237 -18.33 -0.866041 -18.34 -0.910985 -18.35 -0.957021 -18.36 -1.004 -18.37 -1.05169 -18.38 -1.09976 -18.39 -1.14778 -18.4 -1.19529 -18.41 -1.24175 -18.42 -1.2866 -18.43 -1.32925 -18.44 -1.36911 -18.45 -1.40561 -18.46 -1.4382 -18.47 -1.46637 -18.48 -1.48966 -18.49 -1.50767 -18.5 -1.52005 -18.51 -1.52652 -18.52 -1.52687 -18.53 -1.52092 -18.54 -1.50858 -18.55 -1.48979 -18.56 -1.46455 -18.57 -1.43287 -18.58 -1.39482 -18.59 -1.3505 -18.6 -1.30002 -18.61 -1.24351 -18.62 -1.18115 -18.63 -1.11313 -18.64 -1.03965 -18.65 -0.960972 -18.66 -0.87737 -18.67 -0.789174 -18.68 -0.696757 -18.69 -0.60055 -18.7 -0.501045 -18.71 -0.398798 -18.72 -0.294436 -18.73 -0.188654 -18.74 -0.0822202 -18.75 0.0240328 -18.76 0.12921 -18.77 0.232364 -18.78 0.332505 -18.79 0.428616 -18.8 0.519667 -18.81 0.604634 -18.82 0.68252 -18.83 0.752373 -18.84 0.813313 -18.85 0.864548 -18.86 0.905399 -18.87 0.93532 -18.88 0.953914 -18.89 0.960952 -18.9 0.956387 -18.91 0.940356 -18.92 0.913196 -18.93 0.875436 -18.94 0.827798 -18.95 0.771184 -18.96 0.70667 -18.97 0.635477 -18.98 0.55896 -18.99 0.478571 -19 0.395836 -19.01 0.312318 -19.02 0.229584 -19.03 0.149173 -19.04 0.0725522 -19.05 0.00109255 -19.06 -0.0639702 -19.07 -0.121561 -19.08 -0.170793 -19.09 -0.210983 -19.1 -0.241672 -19.11 -0.262627 -19.12 -0.273851 -19.13 -0.275571 -19.14 -0.268231 -19.15 -0.25248 -19.16 -0.229143 -19.17 -0.199198 -19.18 -0.163749 -19.19 -0.12399 -19.2 -0.0811707 -19.21 -0.0365662 -19.22 0.00856115 -19.23 0.0529915 -19.24 0.095577 -19.25 0.135268 -19.26 0.171132 -19.27 0.202373 -19.28 0.228342 -19.29 0.248542 -19.3 0.262631 -19.31 0.270416 -19.32 0.271847 -19.33 0.267008 -19.34 0.256097 -19.35 0.239415 -19.36 0.217348 -19.37 0.190346 -19.38 0.158911 -19.39 0.123574 -19.4 0.0848873 -19.41 0.0434063 -19.42 -0.000318026 -19.43 -0.0457482 -19.44 -0.0923661 -19.45 -0.139676 -19.46 -0.187209 -19.47 -0.234517 -19.48 -0.281181 -19.49 -0.3268 -19.5 -0.370996 -19.51 -0.413411 -19.52 -0.453704 -19.53 -0.49155 -19.54 -0.526644 -19.55 -0.558699 -19.56 -0.58745 -19.57 -0.612657 -19.58 -0.634107 -19.59 -0.651618 -19.6 -0.665045 -19.61 -0.674282 -19.62 -0.679264 -19.63 -0.679969 -19.64 -0.676423 -19.65 -0.668694 -19.66 -0.656896 -19.67 -0.641184 -19.68 -0.62175 -19.69 -0.598823 -19.7 -0.572659 -19.71 -0.543543 -19.72 -0.511778 -19.73 -0.477686 -19.74 -0.441602 -19.75 -0.403873 -19.76 -0.364855 -19.77 -0.324913 -19.78 -0.284422 -19.79 -0.243767 -19.8 -0.203343 -19.81 -0.16356 -19.82 -0.124841 -19.83 -0.0876217 -19.84 -0.0523517 -19.85 -0.0194905 -19.86 0.0104968 -19.87 0.037146 -19.88 0.0600022 -19.89 0.0786309 -19.9 0.0926302 -19.91 0.101645 -19.92 0.105382 -19.93 0.103625 -19.94 0.0962485 -19.95 0.0832347 -19.96 0.0646819 -19.97 0.0408149 -19.98 0.0119907 -19.99 -0.0212999 -20 -0.0584354 -20.01 -0.0986708 -20.02 -0.14115 -20.03 -0.184923 -20.04 -0.228965 -20.05 -0.272204 -20.06 -0.313545 -20.07 -0.3519 -20.08 -0.386221 -20.09 -0.415523 -20.1 -0.438919 -20.11 -0.455641 -20.12 -0.465064 -20.13 -0.466723 -20.14 -0.460327 -20.15 -0.445764 -20.16 -0.423103 -20.17 -0.392592 -20.18 -0.354646 -20.19 -0.309835 -20.2 -0.25886 -20.21 -0.202538 -20.22 -0.141773 -20.23 -0.077531 -20.24 -0.0108148 -20.25 0.057363 -20.26 0.126003 -20.27 0.194141 -20.28 0.260865 -20.29 0.325336 -20.3 0.386793 -20.31 0.444563 -20.32 0.49807 -20.33 0.546832 -20.34 0.590458 -20.35 0.628653 -20.36 0.661205 -20.37 0.687982 -20.38 0.70893 -20.39 0.724061 -20.4 0.733454 -20.41 0.73725 -20.42 0.735644 -20.43 0.728895 -20.44 0.717313 -20.45 0.701269 -20.46 0.681191 -20.47 0.657566 -20.48 0.630941 -20.49 0.601919 -20.5 0.571159 -20.51 0.539368 -20.52 0.507297 -20.53 0.47573 -20.54 0.445469 -20.55 0.417324 -20.56 0.392093 -20.57 0.370546 -20.58 0.353403 -20.59 0.341322 -20.6 0.334871 -20.61 0.334519 -20.62 0.340622 -20.63 0.353403 -20.64 0.372956 -20.65 0.399233 -20.66 0.43205 -20.67 0.471088 -20.68 0.515907 -20.69 0.565955 -20.7 0.620585 -20.71 0.679078 -20.72 0.740657 -20.73 0.804515 -20.74 0.869834 -20.75 0.935806 -20.76 1.00165 -20.77 1.06664 -20.78 1.1301 -20.79 1.19142 -20.8 1.25008 -20.81 1.30561 -20.82 1.35763 -20.83 1.40584 -20.84 1.44997 -20.85 1.48981 -20.86 1.52519 -20.87 1.55597 -20.88 1.58199 -20.89 1.60311 -20.9 1.61918 -20.91 1.63002 -20.92 1.63542 -20.93 1.63514 -20.94 1.62895 -20.95 1.61655 -20.96 1.59766 -20.97 1.57199 -20.98 1.53928 -20.99 1.49926 -21 1.45175 -21.01 1.3966 -21.02 1.33374 -21.03 1.26318 -21.04 1.18505 -21.05 1.09956 -21.06 1.00705 -21.07 0.907961 -21.08 0.80286 -21.09 0.692406 -21.1 0.577362 -21.11 0.458576 -21.12 0.336964 -21.13 0.2135 -21.14 0.0891953 -21.15 -0.0349217 -21.16 -0.157822 -21.17 -0.278494 -21.18 -0.395964 -21.19 -0.50931 -21.2 -0.617676 -21.21 -0.720285 -21.22 -0.81645 -21.23 -0.905581 -21.24 -0.987192 -21.25 -1.0609 -21.26 -1.12644 -21.27 -1.18364 -21.28 -1.23246 -21.29 -1.27292 -21.3 -1.30518 -21.31 -1.32948 -21.32 -1.34613 -21.33 -1.35554 -21.34 -1.35818 -21.35 -1.35459 -21.36 -1.34537 -21.37 -1.33114 -21.38 -1.31259 -21.39 -1.29042 -21.4 -1.26534 -21.41 -1.23809 -21.42 -1.2094 -21.43 -1.17997 -21.44 -1.15049 -21.45 -1.12163 -21.46 -1.09399 -21.47 -1.06814 -21.48 -1.04458 -21.49 -1.02374 -21.5 -1.006 -21.51 -0.991629 -21.52 -0.980834 -21.53 -0.973731 -21.54 -0.970354 -21.55 -0.970652 -21.56 -0.974492 -21.57 -0.981666 -21.58 -0.991889 -21.59 -1.00481 -21.6 -1.02003 -21.61 -1.03708 -21.62 -1.05546 -21.63 -1.07464 -21.64 -1.09404 -21.65 -1.1131 -21.66 -1.13122 -21.67 -1.14783 -21.68 -1.16234 -21.69 -1.1742 -21.7 -1.18288 -21.71 -1.1879 -21.72 -1.18879 -21.73 -1.18516 -21.74 -1.17665 -21.75 -1.163 -21.76 -1.14398 -21.77 -1.11946 -21.78 -1.08937 -21.79 -1.05373 -21.8 -1.01266 -21.81 -0.966338 -21.82 -0.915051 -21.83 -0.85916 -21.84 -0.799105 -21.85 -0.735404 -21.86 -0.668641 -21.87 -0.599455 -21.88 -0.528532 -21.89 -0.456589 -21.9 -0.38436 -21.91 -0.31258 -21.92 -0.241969 -21.93 -0.173214 -21.94 -0.106954 -21.95 -0.04376 -21.96 0.0158728 -21.97 0.0715433 -21.98 0.122953 -21.99 0.169912 -22 0.212347 -22.01 0.250299 -22.02 0.283924 -22.03 0.313486 -22.04 0.339348 -22.05 0.361961 -22.06 0.38185 -22.07 0.399598 -22.08 0.415824 -22.09 0.43117 -22.1 0.446276 -22.11 0.461762 -22.12 0.478211 -22.13 0.496151 -22.14 0.516035 -22.15 0.538236 -22.16 0.563029 -22.17 0.590586 -22.18 0.620972 -22.19 0.654138 -22.2 0.689931 -22.21 0.728086 -22.22 0.768243 -22.23 0.809946 -22.24 0.85266 -22.25 0.895778 -22.26 0.938634 -22.27 0.98052 -22.28 1.0207 -22.29 1.0584 -22.3 1.09289 -22.31 1.12339 -22.32 1.1492 -22.33 1.16962 -22.34 1.184 -22.35 1.19176 -22.36 1.19239 -22.37 1.18544 -22.38 1.17055 -22.39 1.14747 -22.4 1.116 -22.41 1.07609 -22.42 1.02777 -22.43 0.971158 -22.44 0.906504 -22.45 0.834145 -22.46 0.754523 -22.47 0.668174 -22.48 0.575722 -22.49 0.477874 -22.5 0.375409 -22.51 0.269165 -22.52 0.160033 -22.53 0.0489398 -22.54 -0.0631627 -22.55 -0.175313 -22.56 -0.286553 -22.57 -0.39594 -22.58 -0.502562 -22.59 -0.605548 -22.6 -0.704076 -22.61 -0.797387 -22.62 -0.884789 -22.63 -0.965663 -22.64 -1.03947 -22.65 -1.10574 -22.66 -1.16409 -22.67 -1.21421 -22.68 -1.25588 -22.69 -1.28893 -22.7 -1.31327 -22.71 -1.32886 -22.72 -1.33574 -22.73 -1.33397 -22.74 -1.3237 -22.75 -1.30508 -22.76 -1.27835 -22.77 -1.24376 -22.78 -1.20161 -22.79 -1.15225 -22.8 -1.09606 -22.81 -1.03346 -22.82 -0.964931 -22.83 -0.890989 -22.84 -0.812195 -22.85 -0.729154 -22.86 -0.642516 -22.87 -0.55297 -22.88 -0.461238 -22.89 -0.368072 -22.9 -0.274245 -22.91 -0.180539 -22.92 -0.0877377 -22.93 0.00338898 -22.94 0.0920952 -22.95 0.177673 -22.96 0.259466 -22.97 0.336881 -22.98 0.409399 -22.99 0.476585 -23 0.538098 -23.01 0.593692 -23.02 0.643222 -23.03 0.686644 -23.04 0.724011 -23.05 0.755469 -23.06 0.781246 -23.07 0.801645 -23.08 0.817028 -23.09 0.827805 -23.1 0.834416 -23.11 0.837318 -23.12 0.836967 -23.13 0.833803 -23.14 0.828237 -23.15 0.820639 -23.16 0.811325 -23.17 0.800551 -23.18 0.788507 -23.19 0.775315 -23.2 0.761026 -23.21 0.745627 -23.22 0.729043 -23.23 0.711147 -23.24 0.691767 -23.25 0.670701 -23.26 0.647727 -23.27 0.622616 -23.28 0.595147 -23.29 0.565122 -23.3 0.532374 -23.31 0.496786 -23.32 0.458292 -23.33 0.416895 -23.34 0.372669 -23.35 0.325762 -23.36 0.276404 -23.37 0.2249 -23.38 0.171632 -23.39 0.117052 -23.4 0.0616786 -23.41 0.00608221 -23.42 -0.0491209 -23.43 -0.103283 -23.44 -0.155736 -23.45 -0.205808 -23.46 -0.252839 -23.47 -0.296191 -23.48 -0.335265 -23.49 -0.369519 -23.5 -0.398474 -23.51 -0.421731 -23.52 -0.438978 -23.53 -0.450001 -23.54 -0.454691 -23.55 -0.453045 -23.56 -0.445169 -23.57 -0.431279 -23.58 -0.411696 -23.59 -0.386841 -23.6 -0.357229 -23.61 -0.323453 -23.62 -0.286178 -23.63 -0.246124 -23.64 -0.20405 -23.65 -0.160739 -23.66 -0.11698 -23.67 -0.0735517 -23.68 -0.0312034 -23.69 0.00936038 -23.7 0.0474956 -23.71 0.0826329 -23.72 0.11429 -23.73 0.14208 -23.74 0.165723 -23.75 0.185047 -23.76 0.199994 -23.77 0.210614 -23.78 0.21707 -23.79 0.219625 -23.8 0.218637 -23.81 0.214547 -23.82 0.207871 -23.83 0.199178 -23.84 0.189082 -23.85 0.178224 -23.86 0.167251 -23.87 0.156807 -23.88 0.14751 -23.89 0.139942 -23.9 0.134629 -23.91 0.132035 -23.92 0.132542 -23.93 0.136451 -23.94 0.143965 -23.95 0.155191 -23.96 0.170131 -23.97 0.188687 -23.98 0.210659 -23.99 0.235751 -24 0.263574 -24.01 0.293656 -24.02 0.325452 -24.03 0.358354 -24.04 0.391702 -24.05 0.4248 -24.06 0.456932 -24.07 0.487372 -24.08 0.515403 -24.09 0.540332 -24.1 0.561502 -24.11 0.578313 -24.12 0.590228 -24.13 0.59679 -24.14 0.597631 -24.15 0.592484 -24.16 0.581183 -24.17 0.563677 -24.18 0.540027 -24.19 0.510405 -24.2 0.475097 -24.21 0.434493 -24.22 0.389082 -24.23 0.339441 -24.24 0.286227 -24.25 0.230156 -24.26 0.171997 -24.27 0.112546 -24.28 0.0526185 -24.29 -0.00697525 -24.3 -0.0654433 -24.31 -0.12203 -24.32 -0.17603 -24.33 -0.226803 -24.34 -0.273788 -24.35 -0.316506 -24.36 -0.354575 -24.37 -0.387709 -24.38 -0.415723 -24.39 -0.43853 -24.4 -0.456138 -24.41 -0.468644 -24.42 -0.476226 -24.43 -0.479133 -24.44 -0.477672 -24.45 -0.472202 -24.46 -0.46311 -24.47 -0.450812 -24.48 -0.435728 -24.49 -0.41828 -24.5 -0.398879 -24.51 -0.377913 -24.52 -0.355748 -24.53 -0.332716 -24.54 -0.309117 -24.55 -0.285215 -24.56 -0.261243 -24.57 -0.237401 -24.58 -0.213866 -24.59 -0.190789 -24.6 -0.168307 -24.61 -0.146547 -24.62 -0.125628 -24.63 -0.105671 -24.64 -0.0867981 -24.65 -0.0691386 -24.66 -0.052828 -24.67 -0.0380084 -24.68 -0.0248268 -24.69 -0.0134319 -24.7 -0.00396903 -24.71 0.00342524 -24.72 0.00862949 -24.73 0.0115444 -24.74 0.0120996 -24.75 0.01026 -24.76 0.00603171 -24.77 -0.000533807 -24.78 -0.00933648 -24.79 -0.0202266 -24.8 -0.0330052 -24.81 -0.0474274 -24.82 -0.0632065 -24.83 -0.0800208 -24.84 -0.0975224 -24.85 -0.115346 -24.86 -0.133121 -24.87 -0.15048 -24.88 -0.167075 -24.89 -0.182583 -24.9 -0.19672 -24.91 -0.209249 -24.92 -0.219984 -24.93 -0.2288 -24.94 -0.235633 -24.95 -0.24048 -24.96 -0.243398 -24.97 -0.244498 -24.98 -0.243941 -24.99 -0.241926 -25 -0.238682 -25.01 -0.234459 -25.02 -0.229511 -25.03 -0.224091 -25.04 -0.218435 -25.05 -0.212755 -25.06 -0.207228 -25.07 -0.201995 -25.08 -0.197151 -25.09 -0.192744 -25.1 -0.188779 -25.11 -0.185218 -25.12 -0.181985 -25.13 -0.178974 -25.14 -0.176059 -25.15 -0.173097 -25.16 -0.169947 -25.17 -0.166472 -25.18 -0.162555 -25.19 -0.158102 -25.2 -0.153054 -25.21 -0.147386 -25.22 -0.141118 -25.23 -0.13431 -25.24 -0.127061 -25.25 -0.119507 -25.26 -0.111817 -25.27 -0.104179 -25.28 -0.0967973 -25.29 -0.0898812 -25.3 -0.083633 -25.31 -0.0782393 -25.32 -0.0738614 -25.33 -0.0706267 -25.34 -0.0686226 -25.35 -0.0678912 -25.36 -0.0684268 -25.37 -0.0701758 -25.38 -0.0730382 -25.39 -0.0768721 -25.4 -0.0814995 -25.41 -0.0867141 -25.42 -0.0922901 -25.43 -0.0979919 -25.44 -0.103584 -25.45 -0.108839 -25.46 -0.113549 -25.47 -0.117531 -25.48 -0.120633 -25.49 -0.122737 -25.5 -0.123762 -25.51 -0.123664 -25.52 -0.122432 -25.53 -0.120081 -25.54 -0.116654 -25.55 -0.112204 -25.56 -0.106795 -25.57 -0.10049 -25.58 -0.0933423 -25.59 -0.0853897 -25.6 -0.0766493 -25.61 -0.0671129 -25.62 -0.0567458 -25.63 -0.0454868 -25.64 -0.0332516 -25.65 -0.0199382 -25.66 -0.00543403 -25.67 0.0103743 -25.68 0.0275905 -25.69 0.0462969 -25.7 0.0665427 -25.71 0.0883321 -25.72 0.111614 -25.73 0.136274 -25.74 0.162127 -25.75 0.188911 -25.76 0.216292 -25.77 0.243861 -25.78 0.271143 -25.79 0.297606 -25.8 0.32267 -25.81 0.345727 -25.82 0.366156 -25.83 0.383342 -25.84 0.396695 -25.85 0.405671 -25.86 0.409793 -25.87 0.408666 -25.88 0.401995 -25.89 0.389595 -25.9 0.371408 -25.91 0.347501 -25.92 0.318074 -25.93 0.283456 -25.94 0.244101 -25.95 0.200577 -25.96 0.153554 -25.97 0.103789 -25.98 0.0521083 -25.99 -0.000612943 -26 -0.0534716 -26.01 -0.105557 -26.02 -0.155971 -26.03 -0.203849 -26.04 -0.248378 -26.05 -0.288811 -26.06 -0.324482 -26.07 -0.35482 -26.08 -0.379349 -26.09 -0.397705 -26.1 -0.409627 -26.11 -0.414968 -26.12 -0.413684 -26.13 -0.405834 -26.14 -0.391576 -26.15 -0.371155 -26.16 -0.344896 -26.17 -0.313199 -26.18 -0.276524 -26.19 -0.235386 -26.2 -0.190343 -26.21 -0.141988 -26.22 -0.090942 -26.23 -0.0378413 -26.24 0.016666 -26.25 0.0719299 -26.26 0.127305 -26.27 0.182156 -26.28 0.235869 -26.29 0.287852 -26.3 0.337545 -26.31 0.384425 -26.32 0.428013 -26.33 0.467876 -26.34 0.503637 -26.35 0.534975 -26.36 0.561631 -26.37 0.583411 -26.38 0.600185 -26.39 0.611889 -26.4 0.618524 -26.41 0.620153 -26.42 0.616899 -26.43 0.608935 -26.44 0.596484 -26.45 0.579807 -26.46 0.559197 -26.47 0.534969 -26.48 0.507453 -26.49 0.476982 -26.5 0.443888 -26.51 0.408493 -26.52 0.371102 -26.53 0.331998 -26.54 0.291441 -26.55 0.249666 -26.56 0.206881 -26.57 0.163271 -26.58 0.119002 -26.59 0.0742224 -26.6 0.0290729 -26.61 -0.0163103 -26.62 -0.0617881 -26.63 -0.107212 -26.64 -0.152419 -26.65 -0.197226 -26.66 -0.241428 -26.67 -0.284795 -26.68 -0.327075 -26.69 -0.367992 -26.7 -0.407252 -26.71 -0.44455 -26.72 -0.479575 -26.73 -0.512021 -26.74 -0.541595 -26.75 -0.568029 -26.76 -0.591085 -26.77 -0.610572 -26.78 -0.626348 -26.79 -0.63833 -26.8 -0.646497 -26.81 -0.650896 -26.82 -0.651641 -26.83 -0.648907 -26.84 -0.642932 -26.85 -0.634006 -26.86 -0.622462 -26.87 -0.608666 -26.88 -0.593004 -26.89 -0.57587 -26.9 -0.55765 -26.91 -0.538711 -26.92 -0.519388 -26.93 -0.499973 -26.94 -0.480704 -26.95 -0.46176 -26.96 -0.443258 -26.97 -0.425245 -26.98 -0.407706 -26.99 -0.390561 -27 -0.373676 -27.01 -0.356867 -27.02 -0.339911 -27.03 -0.32256 -27.04 -0.304548 -27.05 -0.285604 -27.06 -0.265468 -27.07 -0.243896 -27.08 -0.220675 -27.09 -0.19563 -27.1 -0.168626 -27.11 -0.139581 -27.12 -0.108462 -27.13 -0.0752872 -27.14 -0.0401245 -27.15 -0.00308947 -27.16 0.0356604 -27.17 0.0759308 -27.18 0.117497 -27.19 0.16011 -27.2 0.203505 -27.21 0.247404 -27.22 0.291524 -27.23 0.335582 -27.24 0.379296 -27.25 0.42239 -27.26 0.464595 -27.27 0.505648 -27.28 0.545295 -27.29 0.583288 -27.3 0.619386 -27.31 0.653353 -27.32 0.68496 -27.33 0.713983 -27.34 0.740205 -27.35 0.76342 -27.36 0.783433 -27.37 0.800068 -27.38 0.813168 -27.39 0.822608 -27.4 0.828293 -27.41 0.830171 -27.42 0.828234 -27.43 0.822528 -27.44 0.813152 -27.45 0.800264 -27.46 0.78408 -27.47 0.764872 -27.48 0.742969 -27.49 0.718743 -27.5 0.692608 -27.51 0.665005 -27.52 0.636392 -27.53 0.607229 -27.54 0.577966 -27.55 0.549025 -27.56 0.520788 -27.57 0.49358 -27.58 0.467662 -27.59 0.443216 -27.6 0.420342 -27.61 0.39905 -27.62 0.37926 -27.63 0.360805 -27.64 0.343439 -27.65 0.326842 -27.66 0.310633 -27.67 0.294388 -27.68 0.277652 -27.69 0.259963 -27.7 0.240865 -27.71 0.219931 -27.72 0.196777 -27.73 0.171083 -27.74 0.142605 -27.75 0.111187 -27.76 0.0767693 -27.77 0.0393945 -27.78 -0.000790909 -27.79 -0.0435385 -27.8 -0.0885031 -27.81 -0.135251 -27.82 -0.183272 -27.83 -0.231991 -27.84 -0.280786 -27.85 -0.328999 -27.86 -0.375961 -27.87 -0.421 -27.88 -0.463464 -27.89 -0.502731 -27.9 -0.538226 -27.91 -0.56943 -27.92 -0.595892 -27.93 -0.617234 -27.94 -0.633159 -27.95 -0.643451 -27.96 -0.647979 -27.97 -0.646696 -27.98 -0.639638 -27.99 -0.626918 -28 -0.608725 -28.01 -0.585321 -28.02 -0.557032 -28.03 -0.524247 -28.04 -0.48741 -28.05 -0.447014 -28.06 -0.4036 -28.07 -0.357748 -28.08 -0.310069 -28.09 -0.261204 -28.1 -0.211813 -28.11 -0.162568 -28.12 -0.114147 -28.13 -0.0672219 -28.14 -0.0224522 -28.15 0.019529 -28.16 0.0581239 -28.17 0.0927814 -28.18 0.123009 -28.19 0.148382 -28.2 0.168557 -28.21 0.183275 -28.22 0.192376 -28.23 0.195799 -28.24 0.193585 -28.25 0.185881 -28.26 0.172935 -28.27 0.155094 -28.28 0.132789 -28.29 0.106535 -28.3 0.0769078 -28.31 0.0445372 -28.32 0.0100861 -28.33 -0.0257651 -28.34 -0.0623357 -28.35 -0.0989626 -28.36 -0.135016 -28.37 -0.169915 -28.38 -0.203137 -28.39 -0.234233 -28.4 -0.262831 -28.41 -0.288641 -28.42 -0.311457 -28.43 -0.331153 -28.44 -0.347682 -28.45 -0.361066 -28.46 -0.371386 -28.47 -0.378775 -28.48 -0.383403 -28.49 -0.385466 -28.5 -0.385174 -28.51 -0.382742 -28.52 -0.378377 -28.53 -0.372272 -28.54 -0.364602 -28.55 -0.355516 -28.56 -0.34514 -28.57 -0.333573 -28.58 -0.320895 -28.59 -0.307167 -28.6 -0.292439 -28.61 -0.276756 -28.62 -0.260165 -28.63 -0.242721 -28.64 -0.224493 -28.65 -0.205571 -28.66 -0.186064 -28.67 -0.16611 -28.68 -0.14587 -28.69 -0.125526 -28.7 -0.10528 -28.71 -0.0853495 -28.72 -0.0659555 -28.73 -0.0473195 -28.74 -0.0296537 -28.75 -0.0131524 -28.76 0.00201555 -28.77 0.0157141 -28.78 0.0278458 -28.79 0.0383559 -28.8 0.047235 -28.81 0.054519 -28.82 0.0602876 -28.83 0.0646603 -28.84 0.0677911 -28.85 0.069861 -28.86 0.0710693 -28.87 0.0716252 -28.88 0.0717372 -28.89 0.0716044 -28.9 0.0714076 -28.91 0.0713014 -28.92 0.0714079 -28.93 0.0718127 -28.94 0.0725617 -28.95 0.0736616 -28.96 0.0750808 -28.97 0.0767535 -28.98 0.0785854 -28.99 0.0804603 -29 0.0822487 -29.01 0.0838162 -29.02 0.0850328 -29.03 0.0857818 -29.04 0.0859679 -29.05 0.0855238 -29.06 0.0844164 -29.07 0.0826501 -29.08 0.0802686 -29.09 0.0773548 -29.1 0.0740283 -29.11 0.0704411 -29.12 0.0667716 -29.13 0.0632165 -29.14 0.0599828 -29.15 0.0572777 -29.16 0.055299 -29.17 0.0542251 -29.18 0.0542065 -29.19 0.055357 -29.2 0.0577473 -29.21 0.0613998 -29.22 0.0662853 -29.23 0.0723221 -29.24 0.0793765 -29.25 0.0872665 -29.26 0.0957663 -29.27 0.104613 -29.28 0.113517 -29.29 0.122168 -29.3 0.130248 -29.31 0.137442 -29.32 0.143448 -29.33 0.14799 -29.34 0.150824 -29.35 0.151751 -29.36 0.15062 -29.37 0.147338 -29.38 0.14187 -29.39 0.134243 -29.4 0.124546 -29.41 0.112927 -29.42 0.0995856 -29.43 0.0847727 -29.44 0.0687784 -29.45 0.0519245 -29.46 0.0345542 -29.47 0.0170214 -29.48 -0.000320095 -29.49 -0.0171277 -29.5 -0.0330802 -29.51 -0.0478873 -29.52 -0.061298 -29.53 -0.0731076 -29.54 -0.0831627 -29.55 -0.0913643 -29.56 -0.0976695 -29.57 -0.102091 -29.58 -0.104693 -29.59 -0.105589 -29.6 -0.104934 -29.61 -0.102917 -29.62 -0.0997513 -29.63 -0.0956689 -29.64 -0.090906 -29.65 -0.0856958 -29.66 -0.0802587 -29.67 -0.0747934 -29.68 -0.0694701 -29.69 -0.0644245 -29.7 -0.0597538 -29.71 -0.0555145 -29.72 -0.0517226 -29.73 -0.0483555 -29.74 -0.0453558 -29.75 -0.0426373 -29.76 -0.0400919 -29.77 -0.037598 -29.78 -0.03503 -29.79 -0.0322675 -29.8 -0.0292046 -29.81 -0.0257591 -29.82 -0.0218797 -29.83 -0.0175527 -29.84 -0.0128061 -29.85 -0.00771258 -29.86 -0.00238888 -29.87 0.00300586 -29.88 0.00827489 -29.89 0.0131905 -29.9 0.0175029 -29.91 0.0209501 -29.92 0.0232701 -29.93 0.0242126 -29.94 0.0235514 -29.95 0.0210971 -29.96 0.0167076 -29.97 0.0102985 -29.98 0.00185044 -29.99 -0.0085847 -30 -0.020881 diff --git a/tests/testdata/TiO2_rutile-fit.stru b/tests/testdata/TiO2_rutile-fit.stru deleted file mode 100644 index a7c0b253..00000000 --- a/tests/testdata/TiO2_rutile-fit.stru +++ /dev/null @@ -1,45 +0,0 @@ -title TiO2_rutile -format pdffit -scale 1.000000 -sharp 2.309118, 0.000000, 1.000000, 0.000000 -spcgr P42/mnm -cell 4.605859, 4.605859, 2.954396, 90.000000, 90.000000, 90.000000 -dcell 0.000012, 0.000012, 0.000011, 0.000000, 0.000000, 0.000000 -ncell 1, 1, 1, 6 -atoms -TI 0.00000000 0.00000000 0.00000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.00869753 0.00869753 0.00549226 - 0.00000411 0.00000411 0.00000544 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -TI 0.50000000 0.50000000 0.50000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.00869753 0.00869753 0.00549226 - 0.00000411 0.00000411 0.00000544 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -O 0.30510000 0.30510000 0.00000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.02173269 0.02173269 0.00770728 - 0.00001744 0.00001744 0.00001714 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -O 0.69490000 0.69490000 0.00000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.02173269 0.02173269 0.00770728 - 0.00001744 0.00001744 0.00001714 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -O 0.80510000 0.19490000 0.50000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.02173269 0.02173269 0.00770728 - 0.00001744 0.00001744 0.00001714 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 -O 0.19490000 0.80510000 0.50000000 1.0000 - 0.00000000 0.00000000 0.00000000 0.0000 - 0.02173269 0.02173269 0.00770728 - 0.00001744 0.00001744 0.00001714 - 0.00000000 0.00000000 0.00000000 - 0.00000000 0.00000000 0.00000000 diff --git a/tests/testdata/rutile.cif b/tests/testdata/rutile.cif deleted file mode 100644 index d176b0c6..00000000 --- a/tests/testdata/rutile.cif +++ /dev/null @@ -1,52 +0,0 @@ -data_9004141 -_chemical_name 'Rutile' -loop_ -_publ_author_name -'Meagher E P' -'Lager G A' -_journal_name_full "The Canadian Mineralogist" -_journal_volume 17 -_journal_year 1979 -_journal_page_first 77 -_journal_page_last 85 -_publ_section_title -; - Polyhedral thermal expansion in the TiO2 polymorphs: Refinement - of the crystal structure of rutile and brookite at high temperature - Sample at 25 degrees C -; -_chemical_formula_sum 'Ti O2' -_cell_length_a 4.593 -_cell_length_b 4.593 -_cell_length_c 2.959 -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 90 -_cell_volume 62.422 -_symmetry_space_group_name_H-M 'P 42/m n m' -loop_ -_symmetry_equiv_pos_as_xyz - 'x,y,z' - '-y,-x,z' - 'y,x,-z' - '1/2+y,1/2-x,1/2-z' - '1/2-y,1/2+x,1/2+z' - '1/2+x,1/2-y,1/2+z' - '1/2-x,1/2+y,1/2-z' - 'x,y,-z' - '-x,-y,z' - 'y,x,z' - '-y,-x,-z' - '1/2-y,1/2+x,1/2-z' - '1/2+y,1/2-x,1/2+z' - '1/2-x,1/2+y,1/2+z' - '1/2+x,1/2-y,1/2-z' - '-x,-y,-z' -loop_ -_atom_site_label -_atom_site_fract_x -_atom_site_fract_y -_atom_site_fract_z -_atom_site_U_iso_or_equiv -Ti 0.00000 0.00000 0.00000 0.00532 -O 0.30510 0.30510 0.00000 0.00760 diff --git a/tests/testdata/silicon.cif b/tests/testdata/silicon.cif deleted file mode 100644 index ddcf81b9..00000000 --- a/tests/testdata/silicon.cif +++ /dev/null @@ -1,224 +0,0 @@ -data_9008565 -_chemical_name 'Silicon' -loop_ -_publ_author_name -'Wyckoff R W G' -_journal_name_full "Crystal Structures" -_journal_volume 1 -_journal_year 1963 -_journal_page_first 7 -_journal_page_last 83 -_publ_section_title -; - Second edition. Interscience Publishers, New York, New York - Sample at T = 300 K -; -_chemical_formula_sum 'Si' -_cell_length_a 5.43070 -_cell_length_b 5.43070 -_cell_length_c 5.43070 -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 90 -_cell_volume 160.165 -_symmetry_space_group_name_H-M 'F d 3 m' -loop_ -_symmetry_equiv_pos_as_xyz - 'x,y,z' - 'x,1/2+y,1/2+z' - '1/2+x,y,1/2+z' - '1/2+x,1/2+y,z' - '3/4+z,3/4-x,1/4+y' - '3/4+z,1/4-x,3/4+y' - '1/4+z,3/4-x,3/4+y' - '1/4+z,1/4-x,1/4+y' - '-y,1/2+z,1/2-x' - '-y,+z,-x' - '1/2-y,1/2+z,-x' - '1/2-y,+z,1/2-x' - '3/4+x,3/4-y,1/4+z' - '3/4+x,1/4-y,3/4+z' - '1/4+x,3/4-y,3/4+z' - '1/4+x,1/4-y,1/4+z' - '-z,1/2+x,1/2-y' - '-z,+x,-y' - '1/2-z,1/2+x,-y' - '1/2-z,+x,1/2-y' - '3/4+y,3/4-z,1/4+x' - '3/4+y,1/4-z,3/4+x' - '1/4+y,3/4-z,3/4+x' - '1/4+y,1/4-z,1/4+x' - '-x,1/2+y,1/2-z' - '-x,+y,-z' - '1/2-x,1/2+y,-z' - '1/2-x,+y,1/2-z' - '1/2+x,-z,1/2-y' - '1/2+x,1/2-z,-y' - '+x,-z,-y' - '+x,1/2-z,1/2-y' - '3/4-z,3/4+y,1/4+x' - '3/4-z,1/4+y,3/4+x' - '1/4-z,3/4+y,3/4+x' - '1/4-z,1/4+y,1/4+x' - '1/2+y,-x,1/2-z' - '1/2+y,1/2-x,-z' - '+y,-x,-z' - '+y,1/2-x,1/2-z' - '3/4-x,3/4+z,1/4+y' - '3/4-x,1/4+z,3/4+y' - '1/4-x,3/4+z,3/4+y' - '1/4-x,1/4+z,1/4+y' - '1/2+z,-y,1/2-x' - '1/2+z,1/2-y,-x' - '+z,-y,-x' - '+z,1/2-y,1/2-x' - '3/4-y,3/4+x,1/4+z' - '3/4-y,1/4+x,3/4+z' - '1/4-y,3/4+x,3/4+z' - '1/4-y,1/4+x,1/4+z' - 'x,1/2+z,1/2+y' - 'x,+z,+y' - '1/2+x,1/2+z,+y' - '1/2+x,+z,1/2+y' - '1/4-z,3/4-y,3/4-x' - '1/4-z,1/4-y,1/4-x' - '3/4-z,3/4-y,1/4-x' - '3/4-z,1/4-y,3/4-x' - 'y,1/2+x,1/2+z' - 'y,+x,+z' - '1/2+y,1/2+x,+z' - '1/2+y,+x,1/2+z' - '1/4-x,3/4-z,3/4-y' - '1/4-x,1/4-z,1/4-y' - '3/4-x,3/4-z,1/4-y' - '3/4-x,1/4-z,3/4-y' - 'z,1/2+y,1/2+x' - 'z,+y,+x' - '1/2+z,1/2+y,+x' - '1/2+z,+y,1/2+x' - '1/4-y,3/4-x,3/4-z' - '1/4-y,1/4-x,1/4-z' - '3/4-y,3/4-x,1/4-z' - '3/4-y,1/4-x,3/4-z' - '3/4+z,1/4+x,3/4-y' - '3/4+z,3/4+x,1/4-y' - '1/4+z,1/4+x,1/4-y' - '1/4+z,3/4+x,3/4-y' - '-y,1/2-z,1/2+x' - '-y,-z,+x' - '1/2-y,1/2-z,+x' - '1/2-y,-z,1/2+x' - '3/4+x,1/4+y,3/4-z' - '3/4+x,3/4+y,1/4-z' - '1/4+x,1/4+y,1/4-z' - '1/4+x,3/4+y,3/4-z' - '-z,1/2-x,1/2+y' - '-z,-x,+y' - '1/2-z,1/2-x,+y' - '1/2-z,-x,1/2+y' - '3/4+y,1/4+z,3/4-x' - '3/4+y,3/4+z,1/4-x' - '1/4+y,1/4+z,1/4-x' - '1/4+y,3/4+z,3/4-x' - '-x,1/2-y,1/2+z' - '-x,-y,+z' - '1/2-x,1/2-y,+z' - '1/2-x,-y,1/2+z' - '1/4-z,3/4+x,3/4+y' - '1/4-z,1/4+x,1/4+y' - '3/4-z,3/4+x,1/4+y' - '3/4-z,1/4+x,3/4+y' - 'y,-z,-x' - 'y,1/2-z,1/2-x' - '1/2+y,-z,1/2-x' - '1/2+y,1/2-z,-x' - '1/4-x,3/4+y,3/4+z' - '1/4-x,1/4+y,1/4+z' - '3/4-x,3/4+y,1/4+z' - '3/4-x,1/4+y,3/4+z' - 'z,-x,-y' - 'z,1/2-x,1/2-y' - '1/2+z,-x,1/2-y' - '1/2+z,1/2-x,-y' - '1/4-y,3/4+z,3/4+x' - '1/4-y,1/4+z,1/4+x' - '3/4-y,3/4+z,1/4+x' - '3/4-y,1/4+z,3/4+x' - 'x,-y,-z' - 'x,1/2-y,1/2-z' - '1/2+x,-y,1/2-z' - '1/2+x,1/2-y,-z' - '1/2-x,1/2+z,-y' - '1/2-x,+z,1/2-y' - '-x,1/2+z,1/2-y' - '-x,+z,-y' - '1/4+z,3/4-y,3/4+x' - '1/4+z,1/4-y,1/4+x' - '3/4+z,3/4-y,1/4+x' - '3/4+z,1/4-y,3/4+x' - '1/2-y,1/2+x,-z' - '1/2-y,+x,1/2-z' - '-y,1/2+x,1/2-z' - '-y,+x,-z' - '1/4+x,3/4-z,3/4+y' - '1/4+x,1/4-z,1/4+y' - '3/4+x,3/4-z,1/4+y' - '3/4+x,1/4-z,3/4+y' - '1/2-z,1/2+y,-x' - '1/2-z,+y,1/2-x' - '-z,1/2+y,1/2-x' - '-z,+y,-x' - '1/4+y,3/4-x,3/4+z' - '1/4+y,1/4-x,1/4+z' - '3/4+y,3/4-x,1/4+z' - '3/4+y,1/4-x,3/4+z' - '-x,-z,y' - '-x,1/2-z,1/2+y' - '1/2-x,-z,1/2+y' - '1/2-x,1/2-z,y' - '3/4+z,3/4+y,1/4-x' - '3/4+z,1/4+y,3/4-x' - '1/4+z,3/4+y,3/4-x' - '1/4+z,1/4+y,1/4-x' - '-y,-x,z' - '-y,1/2-x,1/2+z' - '1/2-y,-x,1/2+z' - '1/2-y,1/2-x,z' - '3/4+x,3/4+z,1/4-y' - '3/4+x,1/4+z,3/4-y' - '1/4+x,3/4+z,3/4-y' - '1/4+x,1/4+z,1/4-y' - '-z,-y,x' - '-z,1/2-y,1/2+x' - '1/2-z,-y,1/2+x' - '1/2-z,1/2-y,x' - '3/4+y,3/4+x,1/4-z' - '3/4+y,1/4+x,3/4-z' - '1/4+y,3/4+x,3/4-z' - '1/4+y,1/4+x,1/4-z' - '1/4-z,1/4-x,1/4-y' - '1/4-z,3/4-x,3/4-y' - '3/4-z,1/4-x,3/4-y' - '3/4-z,3/4-x,1/4-y' - 'y,z,x' - 'y,1/2+z,1/2+x' - '1/2+y,z,1/2+x' - '1/2+y,1/2+z,x' - '1/4-x,1/4-y,1/4-z' - '1/4-x,3/4-y,3/4-z' - '3/4-x,1/4-y,3/4-z' - '3/4-x,3/4-y,1/4-z' - 'z,x,y' - 'z,1/2+x,1/2+y' - '1/2+z,x,1/2+y' - '1/2+z,1/2+x,y' - '1/4-y,1/4-z,1/4-x' - '1/4-y,3/4-z,3/4-x' - '3/4-y,1/4-z,3/4-x' - '3/4-y,3/4-z,1/4-x' -loop_ -_atom_site_label -_atom_site_fract_x -_atom_site_fract_y -_atom_site_fract_z -Si 0.00000 0.00000 0.00000 diff --git a/tests/testdata/sphalerite.cif b/tests/testdata/sphalerite.cif deleted file mode 100644 index 99e395e4..00000000 --- a/tests/testdata/sphalerite.cif +++ /dev/null @@ -1,128 +0,0 @@ -data_9000107 -_chemical_name 'Sphalerite' -loop_ -_publ_author_name -'Skinner B J' -_journal_name_full "American Mineralogist" -_journal_volume 46 -_journal_year 1961 -_journal_page_first 1399 -_journal_page_last 1411 -_publ_section_title -; - Unit-cell edges of natural and synthetic sphalerites -; -_chemical_formula_sum 'Zn S' -_cell_length_a 5.4093 -_cell_length_b 5.4093 -_cell_length_c 5.4093 -_cell_angle_alpha 90 -_cell_angle_beta 90 -_cell_angle_gamma 90 -_cell_volume 158.279 -_symmetry_space_group_name_H-M 'F -4 3 m' -loop_ -_symmetry_equiv_pos_as_xyz - 'x,y,z' - 'x,1/2+y,1/2+z' - '1/2+x,y,1/2+z' - '1/2+x,1/2+y,z' - '-z,x,-y' - '-z,1/2+x,1/2-y' - '1/2-z,x,1/2-y' - '1/2-z,1/2+x,-y' - '-y,z,-x' - '-y,1/2+z,1/2-x' - '1/2-y,z,1/2-x' - '1/2-y,1/2+z,-x' - '-x,y,-z' - '-x,1/2+y,1/2-z' - '1/2-x,y,1/2-z' - '1/2-x,1/2+y,-z' - 'x,-z,-y' - 'x,1/2-z,1/2-y' - '1/2+x,-z,1/2-y' - '1/2+x,1/2-z,-y' - 'z,-y,-x' - 'z,1/2-y,1/2-x' - '1/2+z,-y,1/2-x' - '1/2+z,1/2-y,-x' - 'y,-x,-z' - 'y,1/2-x,1/2-z' - '1/2+y,-x,1/2-z' - '1/2+y,1/2-x,-z' - 'x,z,y' - 'x,1/2+z,1/2+y' - '1/2+x,z,1/2+y' - '1/2+x,1/2+z,y' - 'z,y,x' - 'z,1/2+y,1/2+x' - '1/2+z,y,1/2+x' - '1/2+z,1/2+y,x' - 'y,x,z' - 'y,1/2+x,1/2+z' - '1/2+y,x,1/2+z' - '1/2+y,1/2+x,z' - '-z,-x,y' - '-z,1/2-x,1/2+y' - '1/2-z,-x,1/2+y' - '1/2-z,1/2-x,y' - '-y,-z,x' - '-y,1/2-z,1/2+x' - '1/2-y,-z,1/2+x' - '1/2-y,1/2-z,x' - '-x,-y,z' - '-x,1/2-y,1/2+z' - '1/2-x,-y,1/2+z' - '1/2-x,1/2-y,z' - 'z,-x,-y' - 'z,1/2-x,1/2-y' - '1/2+z,-x,1/2-y' - '1/2+z,1/2-x,-y' - 'y,-z,-x' - 'y,1/2-z,1/2-x' - '1/2+y,-z,1/2-x' - '1/2+y,1/2-z,-x' - 'x,-y,-z' - 'x,1/2-y,1/2-z' - '1/2+x,-y,1/2-z' - '1/2+x,1/2-y,-z' - '-x,z,-y' - '-x,1/2+z,1/2-y' - '1/2-x,z,1/2-y' - '1/2-x,1/2+z,-y' - '-z,y,-x' - '-z,1/2+y,1/2-x' - '1/2-z,y,1/2-x' - '1/2-z,1/2+y,-x' - '-y,x,-z' - '-y,1/2+x,1/2-z' - '1/2-y,x,1/2-z' - '1/2-y,1/2+x,-z' - '-x,-z,y' - '-x,1/2-z,1/2+y' - '1/2-x,-z,1/2+y' - '1/2-x,1/2-z,y' - '-z,-y,x' - '-z,1/2-y,1/2+x' - '1/2-z,-y,1/2+x' - '1/2-z,1/2-y,x' - '-y,-x,z' - '-y,1/2-x,1/2+z' - '1/2-y,-x,1/2+z' - '1/2-y,1/2-x,z' - 'z,x,y' - 'z,1/2+x,1/2+y' - '1/2+z,x,1/2+y' - '1/2+z,1/2+x,y' - 'y,z,x' - 'y,1/2+z,1/2+x' - '1/2+y,z,1/2+x' - '1/2+y,1/2+z,x' -loop_ -_atom_site_label -_atom_site_fract_x -_atom_site_fract_y -_atom_site_fract_z -Zn 0.00000 0.00000 0.00000 -S 0.25000 0.25000 0.25000 diff --git a/tests/testutils.py b/tests/testutils.py deleted file mode 100644 index cee8d01f..00000000 --- a/tests/testutils.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python - -"""Helper routines for running other unit tests.""" - - -import copy -import pickle - -import numpy - -import diffpy.structure as mod_structure -from diffpy.srreal.structureadapter import ( - AtomicStructureAdapter, - CrystalStructureAdapter, - PeriodicStructureAdapter, - StructureAdapter, -) -from diffpy.structure.parsers import getParser - -# helper functions - - -def datafile(filename): - from pathlib import Path - - rv = Path(__file__).parent / "testdata" / filename - return str(rv) - - -def loadObjCrystCrystal(filename): - from pyobjcryst.crystal import create_crystal_from_cif - - fullpath = datafile(filename) - crst = create_crystal_from_cif(fullpath) - return crst - - -def loadDiffPyStructure(filename): - fullpath = datafile(filename) - stru = mod_structure.loadStructure(fullpath) - return stru - - -def loadCrystalStructureAdapter(filename): - from diffpy.srreal.structureconverters import _fetchDiffPyStructureData - - fullpath = datafile(filename) - pcif = getParser("cif") - stru = pcif.parseFile(fullpath) - asu = stru[:0] + pcif.asymmetric_unit - adpt = CrystalStructureAdapter() - _fetchDiffPyStructureData(adpt, asu) - for op in pcif.spacegroup.iter_symops(): - adpt.addSymOp(op.R, op.t) - return adpt - - -def pickle_with_attr(obj, **attr): - "Return pickle dump after setting one or more attributes." - assert attr, "keyword argument must be set" - for k, v in attr.items(): - setattr(obj, k, v) - rv = pickle.dumps(obj) - return rv - - -def _maxNormDiff(yobs, ycalc): - """Returned maximum difference normalized by RMS of the yobs.""" - yobsa = numpy.array(yobs) - obsmax = numpy.max(numpy.fabs(yobsa)) or 1 - ynmdiff = (yobsa - ycalc) / obsmax - rv = max(numpy.fabs(ynmdiff)) - return rv - - -# helper class for testing overloading of StructureAdapter - - -class HasCustomPQConfig(object): - - cpqcount = 0 - - def _customPQConfig(self, pqobj): - self.cpqcount += 1 - return - - -class DerivedStructureAdapter(HasCustomPQConfig, StructureAdapter): - - def __init__(self): - StructureAdapter.__init__(self) - self.positions = [] - - def clone(self): - rv = DerivedStructureAdapter() - rv.positions[:] = copy.deepcopy(self.positions) - return rv - - def createBondGenerator(self): - from diffpy.srreal.structureadapter import BaseBondGenerator - - return BaseBondGenerator(self) - - def countSites(self): - return len(self.positions) - - # reuse base totalOccupancy - # reuse base numberDensity - - def siteAtomType(self, idx): - self._checkindex(idx) - return "Cu" - - def siteCartesianPosition(self, idx): - return self.positions[idx] - - def siteMultiplicity(self, idx): - self._checkindex(idx) - return 2 * StructureAdapter.siteMultiplicity(self, idx) - - def siteOccupancy(self, idx): - self._checkindex(idx) - return 0.5 * StructureAdapter.siteOccupancy(self, idx) - - def siteAnisotropy(self, idx): - self._checkindex(idx) - return False - - def siteCartesianUij(self, idx): - self._checkindex(idx) - return numpy.identity(3, dtype=float) * 0.005 - - def _checkindex(self, idx): - self.positions[idx] - return - - -# End of class DerivedStructureAdapter - - -class DerivedAtomicStructureAdapter(HasCustomPQConfig, AtomicStructureAdapter): - pass - - -class DerivedPeriodicStructureAdapter( - HasCustomPQConfig, PeriodicStructureAdapter -): - pass - - -class DerivedCrystalStructureAdapter( - HasCustomPQConfig, CrystalStructureAdapter -): - pass - - -# End of file