diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 84b744b..0000000 --- a/.appveyor.yml +++ /dev/null @@ -1,43 +0,0 @@ -environment: - - PYTHON_ARCH: "64" - PYTHON: "C:\\Miniconda38-x64" - - matrix: - - PYTHON_VERSION: "3.8" - -install: - # windows config (for installation) - - cmd: "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" - - cmd: setlocal - - cmd: set ANACONDA_API_TOKEN= - # conda config - - conda config --set always_yes yes --set changeps1 no - - conda update -q conda - - conda install conda-build anaconda-client - - pip install -i https://pypi.anaconda.org/psyplot/simple --no-deps psyplot-ci-orb - - conda config --add channels conda-forge - - conda config --add channels psyplot - - conda info -a - - conda list - # windows config - - cmd: endlocal - - cmd: 'SET PYTHONWARNINGS=ignore:mode:DeprecationWarning:docutils.io:245' - - cmd: "IF NOT DEFINED APPVEYOR_REPO_TAG_NAME (SET GIT_BRANCH=%APPVEYOR_REPO_BRANCH%)" - - cmd: "IF NOT DEFINED APPVEYOR_REPO_TAG_NAME (conda config --add channels psyplot/label/%APPVEYOR_REPO_BRANCH%)" - -build: off - -test_script: - - cmd: setlocal - - cmd: set ANACONDA_API_TOKEN= - - cmd: conda build ci/conda-recipe --python %PYTHON_VERSION% - - cmd: endlocal - -deploy_script: - - cmd: " - IF NOT DEFINED APPVEYOR_REPO_TAG_NAME ( - deploy-conda-recipe -l %APPVEYOR_REPO_BRANCH% -py %PYTHON_VERSION% ci/conda-recipe - ) ELSE ( - deploy-conda-recipe -py %PYTHON_VERSION% ci/conda-recipe - )" diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index be9db88..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,114 +0,0 @@ -version: 2.1 - -orbs: - psyplot: psyplot/psyplot-ci-orb@1.5.25 - mattermost-plugin-notify: nathanaelhoun/mattermost-plugin-notify@1.2.0 - -executors: - default: psyplot/default - macos: psyplot/macos - -parameters: - unit-test-executor: - description: Executor for the unit tests. Can be default or macos - type: string - default: default - deploy-release: - description: Deploy the comment as a new release to github and pypi - type: boolean - default: false - run-tests: - description: Run the test suite - type: boolean - default: true - build_docs: - description: Build the documentation - type: boolean - default: true - -workflows: - build-and-test: - unless: << pipeline.parameters.deploy-release >> - jobs: - - psyplot/install-and-build: - name: install - exec_environment: << pipeline.parameters.unit-test-executor >> - setup_env: true - build_args: "--no-test" - build_docs: << pipeline.parameters.build_docs >> - env_packages: pytest-cov dask pytest-qt - - psyplot/test-parallel: - name: run-tests - parallelism: 1 - pytest_args: --cov=psy_view - run-job: << pipeline.parameters.run-tests >> - requires: - - install - - psyplot/build-docs: - name: test-docs - run-job: << pipeline.parameters.build_docs >> - builders: linkcheck - requires: - - install - - mattermost-plugin-notify/approval-notification: - name: notify-deploy - context: mattermost - message: >- - Hello @all! A workflow on https://app.circleci.com/pipelines/github/psyplot/psy-view is awaiting your approval. - Please check the uploaded docs and builds prior to approval. - requires: - - run-tests - - test-docs - - hold-for-deploy: - type: approval - requires: - - notify-deploy - - psyplot/deploy-pkg: - exec_environment: << pipeline.parameters.unit-test-executor >> - context: anaconda - requires: - - hold-for-deploy - - psyplot/deploy-docs: - fingerprint: "55:98:12:84:96:12:af:75:0c:fc:17:a5:0e:a2:a9:d4" - run-job: << pipeline.parameters.build_docs >> - requires: - - hold-for-deploy - filters: - branches: - only: master - - psyplot/trigger-release-workflow: - context: trigger-release - filters: - branches: - only: master - requires: - - psyplot/deploy-pkg - - psyplot/deploy-docs - publish-release: - when: << pipeline.parameters.deploy-release >> - jobs: - - psyplot/create-tag: - ssh-fingerprints: "55:98:12:84:96:12:af:75:0c:fc:17:a5:0e:a2:a9:d4" - context: psyplot-admin - user-name: psyplot-admin - publish-release: true - publish-version-tag: true - - mattermost-plugin-notify/approval-notification: - name: notify-release - context: mattermost - message: >- - Hello @all! A new release has been created at https://github.com/psyplot/psy-view/releases. - Please review it carefully, publish it and approve the upload to pypi. - requires: - - psyplot/create-tag - - hold-for-pypi: - type: approval - requires: - - notify-release - - psyplot/deploy-pypi: - context: pypi - requires: - - hold-for-pypi - filters: - branches: - only: master diff --git a/.cruft.json b/.cruft.json new file mode 100644 index 0000000..429b957 --- /dev/null +++ b/.cruft.json @@ -0,0 +1,44 @@ +{ + "template": "https://codebase.helmholtz.cloud/psyplot/psyplot-plugin-template.git", + "commit": "62c628c674047d0d592f0abc10430a0426082609", + "checkout": null, + "context": { + "cookiecutter": { + "project_authors": "Philipp S. Sommer", + "project_author_emails": "philipp.sommer@hereon.de", + "project_maintainers": "Philipp S. Sommer", + "project_maintainer_emails": "philipp.sommer@hereon.de", + "gitlab_host": "codebase.helmholtz.cloud", + "gitlab_username": "psyplot", + "git_remote_protocoll": "ssh", + "institution": "Helmholtz-Zentrum Hereon", + "institution_url": "https://www.hereon.de", + "copyright_holder": "Helmholtz-Zentrum hereon GmbH", + "copyright_year": "2021-2024", + "use_reuse": "yes", + "code_license": "LGPL-3.0-only", + "documentation_license": "CC-BY-4.0", + "supplementary_files_license": "CC0-1.0", + "project_title": "psy-view", + "project_slug": "psy-view", + "package_folder": "psy_view", + "project_short_description": "ncview-like interface to psyplot", + "keywords": "visualization,psyplot,netcdf,raster,cartopy,earth-sciences,pyqt,qt,ipython,jupyter,qtconsole,ncview", + "documentation_url": "https://psyplot.github.io/psy-view", + "use_markdown_for_documentation": "no", + "ci_matrix": "pipenv", + "requires_gui": "yes", + "deploy_package_in_ci": "yes", + "deploy_pages_in_ci": "git-push", + "_extensions": [ + "local_extensions.UnderlinedExtension" + ], + "_template": "https://codebase.helmholtz.cloud/psyplot/psyplot-plugin-template.git" + } + }, + "directory": null, + "skip": [ + ".git", + ".mypy_cache" + ] +} diff --git a/.cruft.json.license b/.cruft.json.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/.cruft.json.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..18607ff --- /dev/null +++ b/.flake8 @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +[flake8] +extend-ignore = + E203 + E402 + E501 + W503 diff --git a/.gitattributes b/.gitattributes index 231ef5d..0853744 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,5 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + psy_view/_version.py export-subst diff --git a/.github/ISSUE_TEMPLATE/change_feature.md b/.github/ISSUE_TEMPLATE/change_feature.md deleted file mode 100644 index 436208c..0000000 --- a/.github/ISSUE_TEMPLATE/change_feature.md +++ /dev/null @@ -1,17 +0,0 @@ -#### Summary -[Describe the requested change in one or two lines. -This should also be mentioned in the title of this issue.] - -#### Reason -[Why do you think, this is useful?] - -#### Current behaviour -[How is the current behaviour/framework?] - -#### New behaviour -[Provide here some more explanation that goes beyond the summary above -(or delete this paragraph, if everything is explained above), -and describe the changes you would like to see] - -#### Examples -[images, code-snippets or URLs to other repositories] diff --git a/.github/ISSUE_TEMPLATE/new_feature.md b/.github/ISSUE_TEMPLATE/new_feature.md deleted file mode 100644 index cdb2e79..0000000 --- a/.github/ISSUE_TEMPLATE/new_feature.md +++ /dev/null @@ -1,13 +0,0 @@ -#### Summary -[Describe the new requested feature in one or two lines. -This should also be mentioned in the title of this issue.] - -#### Reason -[Why do you think, this is useful?] - -#### Detailed explanation -[Provide here some more explanation that goes beyond the summary above -(or delete this paragraph, if everything is explained above)] - -#### Examples -[images, code-snippets or URLs to other repositories] diff --git a/.github/issue_template.md b/.github/issue_template.md deleted file mode 100644 index e55120c..0000000 --- a/.github/issue_template.md +++ /dev/null @@ -1,30 +0,0 @@ -#### Code Sample, a copy-pastable example if possible - -```python -# Your code here - -``` -#### Problem description - -[this should explain **why** the current behavior is a problem and why the expected output is a better solution.] - -#### Expected Output -What should have been expected? You can hide large error messages within ``
`` tags, e.g. - -
-very long error message -
- -#### Output of ``psyplot -aV`` - -
-# Paste the output of the command ``psyplot -aV`` (ran from the command line) - -
- -#### NOTE -This is a bug report. - -For requesting new features, use [this template](https://github.com/psyplot/psy-view/issues/new?template=new_feature.md&title=NEW+FEATURE:). - -For changing existing features, use [this template](https://github.com/psyplot/psy-view/issues/new?template=change_feature.md&title=CHANGE+FEATURE:). diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index 4eb59a1..0000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,4 +0,0 @@ - - [ ] Closes #xxxx (remove if there is no corresponding issue, which should only be the case for minor changes) - - [ ] Tests added (for all bug fixes or enhancements) - - [ ] Tests passed (for all non-documentation changes) - - [ ] Fully documented, including `CHANGELOG.rst` for all changes diff --git a/.gitignore b/.gitignore index b629877..c078306 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,17 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] +*$py.class # C extensions *.so -# mypy cache -.mypy_cache - # Distribution / packaging .Python -env/ build/ develop-eggs/ dist/ @@ -22,9 +23,12 @@ lib64/ parts/ sdist/ var/ +wheels/ +share/python-wheels/ *.egg-info/ .installed.cfg *.egg +MANIFEST # PyInstaller # Usually these files are written by a python script from a template @@ -39,13 +43,17 @@ pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ +.nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml -*,cover +*.cover +*.py,cover +.hypothesis/ .pytest_cache/ +cover/ # Translations *.mo @@ -53,6 +61,16 @@ coverage.xml # Django stuff: *.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy # Sphinx documentation docs/api/ @@ -61,21 +79,79 @@ docs/index.doctree docs/docs-*.png docs/_static/docs-*.png + # PyBuilder +.pybuilder/ target/ -# Spyder project +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings .spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ -# Example ipython notebook checkpoints -*.ipynb_checkpoints/ +# Cython debug symbols +cython_debug/ -# rc files -*matplotlibrc -*psyplotguirc.yml -*psyplotrc.yml -*debug_psyplot.log* +static/ -# CI Test files -ci/conda-recipe/recipe_append.yaml +docs/api +psy_view/migrations/00*.py +docs/_static/orcid.* +# ignore Pipfile.lock files in ci +# if a lock-file needs to be added, add it with `git add -f` +ci/matrix/*/Pipfile.lock diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..ad1d0f0 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,117 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +image: python:3.9 + +variables: + PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip" + +cache: + paths: + - .cache/pip + +before_script: + # replace git internal paths in order to use the CI_JOB_TOKEN + - apt-get update -y && apt-get install -y pandoc graphviz + - python -m pip install -U pip + +test-package: + stage: test + script: + - pip install build twine + - make dist + - twine check dist/* + artifacts: + name: python-artifacts + paths: + - "dist/*" + expire_in: 7 days + +test: + stage: test + variables: + PIPENV_PIPFILE: "ci/matrix/${SCENARIO}/Pipfile" + # disable sandboxing, otherwise chrome reports errors when the + # container runs as root + # https://doc.qt.io/qt-5/qtwebengine-platform-notes.html#sandboxing-support + QTWEBENGINE_DISABLE_SANDBOX: "true" + script: + # install necessary libraries for pyqt + - apt-get install -y xvfb python3-pyqt5.qtwebengine + - pip install pipenv + - pipenv install + - xvfb-run make pipenv-test + parallel: + matrix: + - SCENARIO: + - default + artifacts: + name: pipfile + paths: + - "ci/matrix/${SCENARIO}/*" + expire_in: 30 days + coverage: '/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/' + +test-docs: + stage: test + variables: + MPLBACKEND: "module://psyplot_gui.backend" + # disable sandboxing, otherwise chrome reports errors when the + # container runs as root + # https://doc.qt.io/qt-5/qtwebengine-platform-notes.html#sandboxing-support + QTWEBENGINE_DISABLE_SANDBOX: "true" + script: + # install necessary libraries for pyqt + - apt-get install -y xvfb python3-pyqt5.qtwebengine + - make dev-install + # install PyQt5 (not part of requirements.txt because this is complicated + # to install on different platforms) + - pip install PyQt5 PyQtWebEngine + - xvfb-run make -C docs html + - xvfb-run make -C docs linkcheck + artifacts: + paths: + - docs/_build + + +deploy-package: + stage: deploy + needs: + - test-package + - test-docs + - test + only: + - main + script: + - pip install twine + - TWINE_PASSWORD=${CI_JOB_TOKEN} TWINE_USERNAME=gitlab-ci-token python -m twine upload --repository-url ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi dist/* + + +deploy-docs: + stage: deploy + only: + - master + needs: + - test-docs + image: node:21 + before_script: + - npm install -g gh-pages@6.1.1 + - mkdir .gh-pages-cache + script: + # make sure, the DEPLOY_TOKEN is defined + - >- + [ ${CI_DEPLOY_TOKEN} ] || + echo "The CI_DEPLOY_TOKEN variable is not set. Please create an access + token with scope 'read_repository' and 'write_repository'" && + [ ${CI_DEPLOY_TOKEN} ] + - >- + CACHE_DIR=$(realpath .gh-pages-cache) + gh-pages + --dotfiles + --nojekyll + --branch gh-pages + --repo https://ci-user:${CI_DEPLOY_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git + --user "${CI_COMMIT_AUTHOR}" + --message "CI Pipeline ${CI_PIPELINE_ID}, commit ${CI_COMMIT_SHORT_SHA}" + --dist docs/_build/html diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..c69bf06 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +# https://pre-commit.com/ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + # isort should run before black as black sometimes tweaks the isort output + - repo: https://github.com/PyCQA/isort + rev: 5.12.0 + hooks: + - id: isort + args: + - --profile + - black + - --line-length + - "79" + - --filter-files + - -skip-gitignore + - --float-to-top + # https://github.com/python/black#version-control-integration + - repo: https://github.com/psf/black + rev: 23.1.0 + hooks: + - id: black + args: + - --line-length + - "79" + - --exclude + - venv + - repo: https://github.com/keewis/blackdoc + rev: v0.3.8 + hooks: + - id: blackdoc + - repo: https://github.com/pycqa/flake8 + rev: 6.0.0 + hooks: + - id: flake8 + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v1.0.1 + hooks: + - id: mypy + additional_dependencies: + - types-PyYAML + - types-docutils + args: + - --ignore-missing-imports + + - repo: https://github.com/fsfe/reuse-tool + rev: v1.1.2 + hooks: + - id: reuse + + - repo: https://github.com/citation-file-format/cff-converter-python + # there is no release with this hook yet + rev: "44e8fc9" + hooks: + - id: validate-cff diff --git a/.reuse/add_license.py b/.reuse/add_license.py new file mode 100644 index 0000000..3342870 --- /dev/null +++ b/.reuse/add_license.py @@ -0,0 +1,118 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: LGPL-3.0-only + +"""Helper script to add licenses to files. + +This script can be used to apply the licenses and default copyright holders +to files in the repository. + +It uses the short cuts from the ``.reuse/shortcuts.yaml`` file and +adds them to the call of ``reuse annotate``. Any command line option however +overwrites the config in ``shortcuts.yaml`` + +Usage:: + + python .reuse/add_license.py [OPTIONS] +""" + +import os.path as osp +from argparse import ArgumentParser +from textwrap import dedent +from typing import Dict, Optional, TypedDict + +import yaml +from reuse.project import Project +from reuse.vcs import find_root + +try: + from reuse._annotate import add_arguments as _orig_add_arguments + from reuse._annotate import run +except ImportError: + # reuse < 3.0 + from reuse.header import add_arguments as _orig_add_arguments + from reuse.header import run + + +class LicenseShortCut(TypedDict): + """Shortcut to add a copyright statement""" + + #: The copyright statement + copyright: str + + #: year of copyright statement + year: str + + #: SPDX Identifier of the license + license: Optional[str] + + +def load_shortcuts() -> Dict[str, LicenseShortCut]: + """Load the ``shortcuts.yaml`` file.""" + + with open(osp.join(osp.dirname(__file__), "shortcuts.yaml")) as f: + return yaml.safe_load(f) + + +def add_arguments( + parser: ArgumentParser, shortcuts: Dict[str, LicenseShortCut] +): + parser.add_argument( + "shortcut", + choices=[key for key in shortcuts if not key.startswith(".")], + help=( + "What license should be applied? Shortcuts are loaded from " + ".reuse/shortcuts.yaml. Possible shortcuts are %(choices)s" + ), + ) + + _orig_add_arguments(parser) + + parser.set_defaults(func=run) + parser.set_defaults(parser=parser) + + +def main(argv=None): + shortcuts = load_shortcuts() + + parser = ArgumentParser( + prog=".reuse/add_license.py", + description=dedent( + """ + Add copyright and licensing into the header of files with shortcuts + + This script uses the ``reuse annotate`` command to add copyright + and licensing information into the header the specified files. + + It accepts the same arguments as ``reuse annotate``, plus an + additional required `shortcuts` argument. The given `shortcut` + comes from the file at ``.reuse/shortcuts.yaml`` to fill in + copyright, year and license identifier. + + For further information, please type ``reuse annotate --help``""" + ), + ) + add_arguments(parser, shortcuts) + + args = parser.parse_args(argv) + + shortcut = shortcuts[args.shortcut] + + if args.year is None: + args.year = [] + if args.copyright is None: + args.copyright = [] + + if args.license is None and shortcut.get("license"): + args.license = [shortcut["license"]] + elif args.license and shortcut.get("license"): + args.license.append(shortcut["license"]) + args.year.append(shortcut["year"]) + args.copyright.append(shortcut["copyright"]) + + project = Project(find_root()) + args.func(args, project) + + +if __name__ == "__main__": + main() diff --git a/.reuse/shortcuts.yaml b/.reuse/shortcuts.yaml new file mode 100644 index 0000000..43a4548 --- /dev/null +++ b/.reuse/shortcuts.yaml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +.defaults: &defaults + year: "2021-2024" + copyright: "Helmholtz-Zentrum hereon GmbH" + +# The following dictionaries items map to dictionaries with three possible +# keys: +# +# copyright: The copyright statement +# year: year of copyright statement +# license: SPDX Identifier +docs: + <<: *defaults + license: "CC-BY-4.0" +code: + <<: *defaults + license: "LGPL-3.0-only" +supp: + <<: *defaults + license: "CC0-1.0" diff --git a/.vscode/settings.json b/.vscode/settings.json index 12ff2fd..5010f37 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,13 @@ { - "restructuredtext.confPath": "${workspaceFolder}/docs" -} \ No newline at end of file + "editor.formatOnSave": true, + "editor.defaultFormatter": "ms-python.python", + "gitlab.featureFlags": {"securityScansFlag": false}, + "python.formatting.provider": "black", + "python.formatting.blackArgs": [ + "--line-length", + "79" + ], + "python.linting.mypyCategorySeverity.note": "Hint", + "python.linting.mypyEnabled": true, + +} diff --git a/.vscode/settings.json.license b/.vscode/settings.json.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/.vscode/settings.json.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f3bc1a3..0ecb131 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,7 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + v0.2.0 ====== Compatibility fixes and LGPL license diff --git a/CITATION.cff b/CITATION.cff index 750ebfb..2a335a6 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + # YAML 1.2 --- cff-version: "1.2.0" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index d691b68..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,5 +0,0 @@ -# Contributing to psy-view - -:+1::tada: First off, thanks for taking the time to contribute! :tada::+1: - -For some guidelines, please see the [contribution guidelines for psyplot](https://github.com/psyplot/psyplot/blob/master/CONTRIBUTING.md). diff --git a/COPYING b/COPYING deleted file mode 100644 index f288702..0000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/COPYING.LESSER b/COPYING.LESSER deleted file mode 100644 index 0a04128..0000000 --- a/COPYING.LESSER +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/LICENSES/CC-BY-4.0.txt b/LICENSES/CC-BY-4.0.txt new file mode 100644 index 0000000..13ca539 --- /dev/null +++ b/LICENSES/CC-BY-4.0.txt @@ -0,0 +1,156 @@ +Creative Commons Attribution 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/LGPL-3.0-only.txt b/LICENSES/LGPL-3.0-only.txt new file mode 100644 index 0000000..513d1c0 --- /dev/null +++ b/LICENSES/LGPL-3.0-only.txt @@ -0,0 +1,304 @@ +GNU LESSER GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. + +0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. + +"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. +You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: + + a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. + +3. Object Code Incorporating Material from Library Header Files. +The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license document. + +4. Combined Works. +You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: + + a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license document. + + c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. + + e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) + +5. Combined Libraries. +You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. + +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/MANIFEST.in b/MANIFEST.in index 2bf217b..14791df 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,9 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + include README.rst -include LICENSE +include LICENSES/* include psy_view/icons/*.png -include versioneer.py +include psy_view/icons/*.png.license include psy_view/_version.py diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2913a2b --- /dev/null +++ b/Makefile @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +.PHONY: clean clean-build clean-pyc clean-test coverage dist docs help install lint lint/flake8 lint/black +.DEFAULT_GOAL := help + +define BROWSER_PYSCRIPT +import os, webbrowser, sys + +from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT + +BROWSER := python -c "$$BROWSER_PYSCRIPT" + +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + +clean: clean-build clean-pyc clean-test clean-venv ## remove all build, virtual environments, test, coverage and Python artifacts + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: ## remove test and coverage artifacts + rm -fr .tox/ + rm -f .coverage + rm -fr htmlcov/ + rm -fr .pytest_cache + +clean-venv: # remove the virtual environment + rm -rf venv + +lint/isort: ## check style with flake8 + isort --check psy_view tests +lint/flake8: ## check style with flake8 + flake8 psy_view tests +lint/black: ## check style with black + black --check psy_view tests + blackdoc --check psy_view tests +lint/reuse: ## check licenses + reuse lint + +lint: lint/isort lint/black lint/flake8 lint/reuse ## check style + +formatting: + isort psy_view tests + black psy_view tests + blackdoc psy_view tests + +quick-test: ## run tests quickly with the default Python + python -m pytest + +pipenv-test: ## run tox + pipenv run isort --check psy_view + pipenv run black --line-length 79 --check psy_view + pipenv run flake8 psy_view + pipenv run pytest -v --cov=psy_view -x + pipenv run reuse lint + pipenv run cffconvert --validate + +test: ## run tox + tox + +test-all: test test-docs ## run tests and test the docs + +coverage: ## check code coverage quickly with the default Python + python -m pytest --cov psy_view --cov-report=html + $(BROWSER) htmlcov/index.html + +docs: ## generate Sphinx HTML documentation, including API docs + $(MAKE) -C docs clean + $(MAKE) -C docs html + $(BROWSER) docs/_build/html/index.html + +test-docs: ## generate Sphinx HTML documentation, including API docs + $(MAKE) -C docs clean + $(MAKE) -C docs linkcheck + +servedocs: docs ## compile the docs watching for changes + watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . + +release: dist ## package and upload a release + twine upload dist/* + +dist: clean ## builds source and wheel package + python -m build + ls -l dist + +install: clean ## install the package to the active Python's site-packages + python -m pip install . + +dev-install: clean + python -m pip install -r docs/requirements.txt + python -m pip install -e .[dev] + pre-commit install + +venv-install: clean + python -m venv venv + venv/bin/python -m pip install -r docs/requirements.txt + venv/bin/python -m pip install -e .[dev] + venv/bin/pre-commit install diff --git a/README.rst b/README.rst index 4c30a1a..7254cdc 100644 --- a/README.rst +++ b/README.rst @@ -1,3 +1,7 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + ========================================= psy-view: An ncview-like GUI with psyplot ========================================= @@ -106,7 +110,7 @@ Some of the most important features offered by psy-view are: - different projections - implemented in psyplot-gui_ for full flexibility (if desired) -.. _ICON: https://mpimet.mpg.de/en/science/modeling-with-icon/icon-configurations +.. _ICON: https://code.mpimet.mpg.de/projects/iconpublic .. _UGRID: http://ugrid-conventions.github.io/ugrid-conventions/ .. _psyplot-gui: https://psyplot.github.io/psyplot-gui diff --git a/binder/apt.txt.license b/binder/apt.txt.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/binder/apt.txt.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/binder/environment.yml b/binder/environment.yml index 154fd83..71d4fcd 100644 --- a/binder/environment.yml +++ b/binder/environment.yml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + channels: - psyplot/label/master - psyplot diff --git a/binder/postBuild.license b/binder/postBuild.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/binder/postBuild.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/ci/conda-recipe/bld.bat b/ci/conda-recipe/bld.bat deleted file mode 100644 index 0579b80..0000000 --- a/ci/conda-recipe/bld.bat +++ /dev/null @@ -1,11 +0,0 @@ -%PYTHON% -m pip install . --no-deps --ignore-installed -vvv -if errorlevel 1 exit 1 - -set MENU_DIR=%PREFIX%\Menu -IF NOT EXIST (%MENU_DIR%) mkdir %MENU_DIR% - -copy %RECIPE_DIR%\psyplot.ico %MENU_DIR%\psyplot.ico -if errorlevel 1 exit 1 - -copy %RECIPE_DIR%\menu-windows.json %MENU_DIR%\psy-view_shortcut.json -if errorlevel 1 exit 1 diff --git a/ci/conda-recipe/build.sh b/ci/conda-recipe/build.sh deleted file mode 100644 index 614ec75..0000000 --- a/ci/conda-recipe/build.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -$PYTHON -m pip install . --no-deps --ignore-installed -vvv diff --git a/ci/conda-recipe/logo.png b/ci/conda-recipe/logo.png deleted file mode 100644 index b0d09f5..0000000 Binary files a/ci/conda-recipe/logo.png and /dev/null differ diff --git a/ci/conda-recipe/menu-windows.json b/ci/conda-recipe/menu-windows.json deleted file mode 100644 index dbd5f09..0000000 --- a/ci/conda-recipe/menu-windows.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "menu_name": "Psyplot", - "menu_items": - [ - { - "name": "Psy-view", - "pywscript": "${PYTHON_SCRIPTS}/psy-view-script.py", - "workdir": "${PERSONALDIR}", - "icon": "${MENU_DIR}/psyplot.ico" - } - ] -} diff --git a/ci/conda-recipe/meta.yaml b/ci/conda-recipe/meta.yaml deleted file mode 100644 index 1ef09d9..0000000 --- a/ci/conda-recipe/meta.yaml +++ /dev/null @@ -1,70 +0,0 @@ -{% set data = load_setup_py_data() %} -{% set name = "psy-view" %} - -package: - name: {{ name|lower }} - version: {{ data.get('version') }} - -source: - path: ../.. - -build: - number: {{ environ.get('GIT_DESCRIBE_NUMBER', 0) }} - string: py{{ environ.get('CONDA_PY') }}{% if environ.get("BUILD_STR_END") %}_{{ environ.get("BUILD_STR_END") }}{% endif %} - entry_points: - - psy-view = psy_view:main - skip: true # [py == 36] - -requirements: - host: - - python - - pip - run: - - python - - psyplot-gui >=1.3.0 - - psy-maps >=1.3.0 - - netcdf4 - -test: - imports: - - psy_view - - psy_view.ds_widget - - requires: - - pytest - - pytest-cov - - pytest-qt - - codecov - - dask - - netcdf4 - - seaborn - - pillow - - psy-maps - source_files: - - tests - - commands: - - psy-view --help - - pytest -sv --cov=psy_view - - codecov - -app: - entry: psy-view - icon: logo.png - summary: Quick-view for netCDF files - type: desk - -about: - home: https://github.com/psyplot/psy-view - license: LGPL-3.0-only - license_family: GPL - license_file: - - COPYING - - COPYING.LESSER - summary: ncview-like interface to psyplot - - description: | - This package provides a graphical user interface to quickly visualize the - contents of a netCDF file - doc_url: http://psyplot.github.io/psy-view - dev_url: https://github.com/psyplot/psy-view diff --git a/ci/conda-recipe/psyplot.ico b/ci/conda-recipe/psyplot.ico deleted file mode 100644 index 441a5d4..0000000 Binary files a/ci/conda-recipe/psyplot.ico and /dev/null differ diff --git a/ci/matrix/default/Pipfile b/ci/matrix/default/Pipfile new file mode 100644 index 0000000..c2999d7 --- /dev/null +++ b/ci/matrix/default/Pipfile @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +psy-view = {extras = ["testsite"], file = "../../.."} +psyplot = {ref = "package-template", git = "git+https://codebase.helmholtz.cloud/psyplot/psyplot.git"} +psy-simple = {ref = "package-template", git = "git+https://codebase.helmholtz.cloud/psyplot/psy-simple.git"} +psy-maps = {ref = "package-template", git = "git+https://codebase.helmholtz.cloud/psyplot/psy-maps.git"} +matplotlib = "3.7.*" +psyplot-gui = {ref = "package-template", git = "git+https://codebase.helmholtz.cloud/psyplot/psyplot-gui.git"} +PyQt5 = {version="*"} +PyQtWebEngine = {version="*"} + + +[dev-packages] + +[pipenv] +allow_prereleases = true + +[requires] +python_version = "3.9" diff --git a/docs/Makefile b/docs/Makefile index d4bb2cb..b1567a1 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + # Minimal makefile for Sphinx documentation # diff --git a/docs/_static/license_logo.png b/docs/_static/license_logo.png new file mode 100644 index 0000000..c8473a2 Binary files /dev/null and b/docs/_static/license_logo.png differ diff --git a/docs/_static/license_logo.png.license b/docs/_static/license_logo.png.license new file mode 100644 index 0000000..0329700 --- /dev/null +++ b/docs/_static/license_logo.png.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2024 Creative Commons + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/docs/_static/ncview.png.license b/docs/_static/ncview.png.license new file mode 100644 index 0000000..b21fae9 --- /dev/null +++ b/docs/_static/ncview.png.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/docs/_static/resize-demo.gif.license b/docs/_static/resize-demo.gif.license new file mode 100644 index 0000000..b21fae9 --- /dev/null +++ b/docs/_static/resize-demo.gif.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/docs/_static/screenshot.png.license b/docs/_static/screenshot.png.license new file mode 100644 index 0000000..b21fae9 --- /dev/null +++ b/docs/_static/screenshot.png.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/docs/_static/theme_overrides.css b/docs/_static/theme_overrides.css index 78432dc..7b69fa9 100644 --- a/docs/_static/theme_overrides.css +++ b/docs/_static/theme_overrides.css @@ -1,3 +1,9 @@ +/* + * SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + * + * SPDX-License-Identifier: CC-BY-4.0 + */ + /* override table width restrictions */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal; @@ -7,4 +13,4 @@ margin-bottom: 24px; max-width: 100%; overflow: visible; -} \ No newline at end of file +} diff --git a/docs/_templates/footer.html b/docs/_templates/footer.html new file mode 100644 index 0000000..3e57079 --- /dev/null +++ b/docs/_templates/footer.html @@ -0,0 +1,22 @@ + + +{% extends "!footer.html" %} +{% block extrafooter %} + + + +{% endblock %} diff --git a/docs/api.rst b/docs/api.rst new file mode 100644 index 0000000..4ad527e --- /dev/null +++ b/docs/api.rst @@ -0,0 +1,13 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + +.. _api: + +API Reference +============= + + +.. toctree:: + + api/psy_view diff --git a/docs/apigen.bash b/docs/apigen.bash deleted file mode 100755 index 1e7105c..0000000 --- a/docs/apigen.bash +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash -set -e -# script to automatically generate the psyplot api documentation using -# sphinx-apidoc and sed -sphinx-apidoc -f -M -e -T -o api ../psy_view/ - -# replace chapter title in psy_view.rst -sed -i -e '1,1s/.*/API Reference/' api/psy_view.rst - -# add a label to the main API file -sed -i '1 i .. _api:' api/psy_view.rst - -sphinx-autogen -o generated *.rst */*.rst diff --git a/docs/command_line.rst b/docs/command_line.rst index f771d88..0e5a749 100644 --- a/docs/command_line.rst +++ b/docs/command_line.rst @@ -1,3 +1,7 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + .. highlight:: bash .. _command-line: diff --git a/docs/conf.py b/docs/conf.py index bc90ddd..dad1180 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: LGPL-3.0-only + # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full @@ -10,66 +14,62 @@ # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # - -# Disclaimer -# ---------- -# -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . - import os import os.path as osp -import shutil -import re +import sys import warnings - -import subprocess as spr +from pathlib import Path +from typing import Optional # note: we need to import pyplot here, because otherwise it might fail to load # the ipython extension -import matplotlib.pyplot as plt - +import matplotlib.pyplot as plt # noqa: F401 from docutils import nodes -from docutils.statemachine import StringList from docutils.parsers.rst import directives from docutils.parsers.rst.directives import images - +from docutils.statemachine import StringList +from sphinx.ext import apidoc from sphinx.util.docutils import SphinxDirective +sys.path.insert(0, os.path.abspath("..")) + warnings.filterwarnings("ignore", message=r"\s*Downloading:") -# -- Project information ----------------------------------------------------- +if not os.path.exists("_static"): + os.makedirs("_static") + +# isort: off import psy_view -confdir = osp.dirname(__file__) +# isort: on + + +def generate_apidoc(app): + appdir = Path(app.__file__).parent + apidoc.main( + ["-fMEeTo", str(api), str(appdir), str(appdir / "migrations" / "*")] + ) + + +api = Path("api") + +if not api.exists(): + generate_apidoc(psy_view) + +# -- Project information ----------------------------------------------------- -project = 'psy-view' -copyright = ", ".join( - psy_view.__copyright__.strip().replace("Copyright (C) ", "").splitlines() -) -author = psy_view.__author__ +project = "psy-view" +copyright = "2021-2024 Helmholtz-Zentrum hereon GmbH" +author = "Philipp S. Sommer" -version = re.match(r'\d+\.\d+\.\d+', psy_view.__version__).group() # type: ignore -# The full version, including alpha/beta/rc tags. -release = psy_view.__version__ +linkcheck_ignore = [ + # we do not check link of the psy-view as the + # badges might not yet work everywhere. Once psy-view + # is settled, the following link should be removed + r"https://.*psy-view" +] # -- General configuration --------------------------------------------------- @@ -78,107 +78,90 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.doctest', - 'sphinx.ext.intersphinx', - 'sphinx.ext.autosummary', - 'sphinx.ext.viewcode', - 'IPython.sphinxext.ipython_console_highlighting', - 'IPython.sphinxext.ipython_directive', - 'sphinxarg.ext', - 'psyplot.sphinxext.extended_napoleon', - 'autodocsumm', - 'sphinx.ext.todo', + "hereon_nc_sphinxext", + "sphinx.ext.intersphinx", + "sphinx_design", + "sphinx.ext.todo", + "autodocsumm", + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.viewcode", + "IPython.sphinxext.ipython_console_highlighting", + "IPython.sphinxext.ipython_directive", + "sphinxarg.ext", + "psyplot.sphinxext.extended_napoleon", ] rebuild_screenshots = False -todo_include_todos = True +confdir = osp.dirname(__file__) + # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# create the api documentation -if not osp.exists(osp.join(osp.dirname(__file__), 'api')): - spr.check_call(['bash', 'apigen.bash']) +templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + + +autodoc_default_options = { + "show_inheritance": True, + "members": True, + "autosummary": 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_theme = "sphinx_rtd_theme" + +html_theme_options = { + "collapse_navigation": False, + "includehidden": False, +} # 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'] - -autodoc_default_options = { - 'show_inheritance': True, - 'autosummary': True, - } +html_static_path = ["_static"] -not_document_data = ['psy_view.rcsetup.defaultParams', - 'psy_view.rcsetup.rcParams'] -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # Additional stuff for the LaTeX preamble. - 'preamble': r'\setcounter{tocdepth}{10}' -} - -master_doc = 'index' - -# 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 = [ - (master_doc, 'psy-view.tex', u'psy-view Documentation', - u'Philipp S. Sommer', 'manual'), -] - -# -- Options for Epub output ---------------------------------------------- - -# Bibliographic Dublin Core info. -epub_title = project -epub_author = author -epub_publisher = author -epub_copyright = copyright - -# A list of files that should not be packed into the epub file. -epub_exclude_files = ['search.html'] - -# Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None), - 'numpy': ('https://numpy.org/doc/stable/', None), - 'matplotlib': ('https://matplotlib.org/stable/', None), - 'sphinx': ('https://www.sphinx-doc.org/en/master/', None), - 'xarray': ('https://xarray.pydata.org/en/stable/', None), - 'cartopy': ('https://scitools.org.uk/cartopy/docs/latest/', None), - 'psyplot': ('https://psyplot.github.io/psyplot/', None), - 'psy_simple': ('https://psyplot.github.io/psy-simple/', None), - 'psy_maps': ('https://psyplot.github.io/psy-maps/', None), - 'psyplot_gui': ('https://psyplot.github.io/psyplot-gui/', None), + "python": ("https://docs.python.org/3/", None), + "pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None), + "numpy": ("https://numpy.org/doc/stable/", None), + "matplotlib": ("https://matplotlib.org/stable/", None), + "sphinx": ("https://www.sphinx-doc.org/en/master/", None), + "xarray": ("https://xarray.pydata.org/en/stable/", None), + "cartopy": ("https://scitools.org.uk/cartopy/docs/latest/", None), + "psyplot": ("https://psyplot.github.io/psyplot/", None), + "psy_simple": ("https://psyplot.github.io/psy-simple/", None), + "psy_maps": ("https://psyplot.github.io/psy-maps/", None), + "psyplot_gui": ("https://psyplot.github.io/psyplot-gui/", None), } def create_screenshot( - code: str, output: str, make_plot: bool = False, enable: bool = None, - plotmethod: str = "mapplot", minwidth=None, - generate=rebuild_screenshots, - ) -> str: + code: str, + output: str, + make_plot: bool = False, + enable: Optional[bool] = None, + plotmethod: str = "mapplot", + minwidth=None, + generate=rebuild_screenshots, +) -> str: """Generate a screenshot of the GUI.""" - from PyQt5.QtWidgets import QApplication, QSizePolicy # pylint: disable=no-name-in-module - from psy_view.ds_widget import DatasetWidget from psyplot.data import open_dataset + from PyQt5.QtWidgets import ( # pylint: disable=no-name-in-module + QApplication, + QSizePolicy, + ) + + from psy_view.ds_widget import DatasetWidget output = osp.join("_static", output) @@ -200,7 +183,7 @@ def create_screenshot( options = {"ds_widget": ds_widget} exec("w = " + code, options) - w = options['w'] + w = options["w"] if enable is not None: w.setEnabled(enable) @@ -250,7 +233,7 @@ def add_line(self, line: str) -> None: if line.strip(): # not a blank line self.result.append(line, *source) else: - self.result.append('', *source) + self.result.append("", *source) def generate(self) -> None: """Generate the content.""" @@ -267,12 +250,14 @@ def run(self): enable = True if self.options.pop("enable", False) is None else None rebuild_screenshot = ( - self.options.pop("generate", False) or - self.env.app.config.rebuild_screenshots + self.options.pop("generate", False) + or self.env.app.config.rebuild_screenshots ) self.img_name = create_screenshot( - *self.arguments, make_plot=make_plot, enable=enable, + *self.arguments, + make_plot=make_plot, + enable=enable, plotmethod=self.options.pop("plotmethod", None) or "mapplot", minwidth=self.options.pop("minwidth", None), generate=rebuild_screenshot, @@ -307,14 +292,14 @@ def generate(self): super().generate() if self.content: - self.add_line('') + self.add_line("") indent = " " for line in self.content: self.add_line(indent + line) def setup(app): - app.add_directive('screenshot', ScreenshotDirective) + app.add_directive("screenshot", ScreenshotDirective) app.add_directive("screenshot-figure", ScreenshotFigureDirective) - app.add_config_value('rebuild_screenshots', rebuild_screenshots, 'env') + app.add_config_value("rebuild_screenshots", rebuild_screenshots, "env") app.add_css_file("theme_overrides.css") diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..4ef08d9 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1,10 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + +.. _contributing: + +Contribution and development hints +================================== + +See :ref:`psyplots contribution guidelines `. diff --git a/docs/demo.nc.license b/docs/demo.nc.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/docs/demo.nc.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/docs/environment.yml b/docs/environment.yml deleted file mode 100644 index 4142528..0000000 --- a/docs/environment.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: psy-view-docs -channels: - - local - - psyplot/label/master - - conda-forge -dependencies: - - python=3.8 - - sphinx - - sphinx_rtd_theme - - psy-view - - autodocsumm - - sphinx-argparse diff --git a/docs/getting-started.rst b/docs/getting-started.rst index 0f1dd3a..956aaeb 100644 --- a/docs/getting-started.rst +++ b/docs/getting-started.rst @@ -1,3 +1,7 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + .. _getting-started: Getting started @@ -56,10 +60,12 @@ like this: :suppress: In [1]: import psyplot.project as psy + ...: ...: with psy.plot.mapplot( - ...: "demo.nc", name="t2m", - ...: cmap="viridis", - ...: ) as sp: + ...: "demo.nc", + ...: name="t2m", + ...: cmap="viridis", + ...: ) as sp: ...: sp.export("docs-getting-started-example.png") .. image:: docs-getting-started-example.png @@ -99,4 +105,4 @@ checkout the :ref:`API reference `. .. |btn_animate_forward| screenshot:: ds_widget.btn_animate_forward docs-btn_animate_forward.png :height: 1.3em - :enable: \ No newline at end of file + :enable: diff --git a/docs/index.rst b/docs/index.rst index 75be6b7..f44ef9e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,109 +1,32 @@ -.. psy-view documentation master file, created by - sphinx-quickstart on Wed Jul 8 21:08:22 2020. +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + +.. psy-view documentation master file You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. -.. _psy-view: - -Welcome to psy-view! -==================== - -.. image:: _static/screenshot.png - :width: 50% - :alt: GUI screenshot - :align: center +Welcome to psy-view's documentation! +==================================== -*psy-view* defines a viewer application for netCDF files, that is highly -motivated by the ncview_ software but entirely built upon the psyplot framework. -It supports strucutured and unstructured grids and provides an intuitive -graphical user interface to quickly dive into the data inside a netCDF file. +|CI| +|Code coverage| +|Latest Release| +|PyPI version| +|Code style: black| +|Imports: isort| +|PEP8| +|Checked with mypy| +|REUSE status| -.. _ncview: http://meteora.ucsd.edu/~pierce/ncview_home_page.html +.. rubric:: ncview-like interface to psyplot .. warning:: - This package is currently under development and we highly appreciate your - feedback! Please try it out yourself and, if you would like to see more features, - find bugs or want to say anything else, please leave your comments and - experiences at https://github.com/psyplot/psy-view/issues or send a mail to - psyplot@hzg.de. - -.. start-badges - -.. only:: html and not epub - - .. list-table:: - :stub-columns: 1 - :widths: 10 90 - - * - docs - - |docs| |mybinder| - * - tests - - |circleci| |appveyor| |codecov| - * - package - - |version| |conda| |github| |zenodo| - * - implementations - - |supported-versions| |supported-implementations| - * - get in touch - - |gitter| |mailing-list| |issues| - - .. |docs| image:: https://img.shields.io/github/deployments/psyplot/psy-view/github-pages - :alt: Documentation - :target: http://psyplot.github.io/psy-view/ - - .. |mybinder| image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/psyplot/psy-view/master?urlpath=%2Fdesktop - :alt: mybinder.org - - .. |circleci| image:: https://circleci.com/gh/psyplot/psy-view/tree/master.svg?style=svg - :alt: CircleCI - :target: https://circleci.com/gh/psyplot/psy-view/tree/master - - .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/a7qxvvwt0e41j32h/branch/master?svg=true - :alt: AppVeyor - :target: https://ci.appveyor.com/project/psyplot/psy-view/branch/master - - .. |codecov| image:: https://codecov.io/gh/psyplot/psy-view/branch/master/graph/badge.svg - :alt: Coverage - :target: https://codecov.io/gh/psyplot/psy-view - - .. |conda| image:: https://anaconda.org/conda-forge/psy-view/badges/version.svg - :alt: conda - :target: https://anaconda.org/conda-forge/psy-view - - .. |github| image:: https://img.shields.io/github/release/psyplot/psy-view.svg - :target: https://github.com/psyplot/psy-view/releases/latest - :alt: Latest github release - - .. |version| image:: https://img.shields.io/pypi/v/psy-view.svg?style=flat - :alt: PyPI Package latest release - :target: https://pypi.python.org/pypi/psy-view - - .. |supported-versions| image:: https://img.shields.io/pypi/pyversions/psy-view.svg?style=flat - :alt: Supported versions - :target: https://pypi.python.org/pypi/psy-view - - .. |supported-implementations| image:: https://img.shields.io/pypi/implementation/psy-view.svg?style=flat - :alt: Supported implementations - :target: https://pypi.python.org/pypi/psy-view - - .. |gitter| image:: https://img.shields.io/gitter/room/psyplot/community.svg?style=flat - :target: https://gitter.im/psyplot/community - :alt: Gitter - - .. |mailing-list| image:: https://img.shields.io/badge/join-mailing%20list-brightgreen.svg?style=flat - :target: https://www.listserv.dfn.de/sympa/subscribe/psyplot - :alt: DFN mailing list - - .. |issues| image:: https://img.shields.io/github/issues-raw/psyplot/psy-view.svg?style=flat - :target: https://github.com/psyplot/psy-view/issues - :alt: GitHub issues - - .. |zenodo| image:: https://zenodo.org/badge/249615633.svg - :alt: Zenodo - :target: https://zenodo.org/badge/latestdoi/249615633 - -.. end-badges + This page has been automatically generated as has not yet been reviewed by + the authors of psy-view! + Stay tuned for updates and discuss with us at + https://codebase.helmholtz.cloud/psyplot/psy-view Features -------- @@ -119,10 +42,13 @@ Some of the most important features offered by psy-view are: Interested? Read more in the section :ref:`psy-view-vs-ncview`. -.. _ICON: https://mpimet.mpg.de/en/science/modeling-with-icon/icon-configurations +.. _ICON: https://code.mpimet.mpg.de/projects/iconpublic .. _UGRID: http://ugrid-conventions.github.io/ugrid-conventions/ .. _psyplot-gui: https://psyplot.github.io/psyplot-gui + + + .. toctree:: :maxdepth: 2 :caption: Contents: @@ -132,7 +58,8 @@ Interested? Read more in the section :ref:`psy-view-vs-ncview`. user-guide ncview command_line - api/psy_view + api + contributing todo @@ -155,6 +82,48 @@ information and a guide about good bug reports. .. _contribution guide: https://github.com/psyplot/psyplot/blob/master/CONTRIBUTING.md +How to cite this software +------------------------- + +.. card:: Please do cite this software! + + .. tab-set:: + + .. tab-item:: APA + + .. citation-info:: + :format: apalike + + .. tab-item:: BibTex + + .. citation-info:: + :format: bibtex + + .. tab-item:: RIS + + .. citation-info:: + :format: ris + + .. tab-item:: Endnote + + .. citation-info:: + :format: endnote + + .. tab-item:: CFF + + .. citation-info:: + :format: cff + + +License information +------------------- +Copyright © 2021-2024 Helmholtz-Zentrum hereon GmbH + +The source code of psy-view is licensed under +LGPL-3.0-only. + +If not stated otherwise, the contents of this documentation is licensed under +CC-BY-4.0. Indices and tables @@ -163,3 +132,25 @@ Indices and tables * :ref:`genindex` * :ref:`modindex` * :ref:`search` + + +.. |CI| image:: https://codebase.helmholtz.cloud/psyplot/psy-view/badges/main/pipeline.svg + :target: https://codebase.helmholtz.cloud/psyplot/psy-view/-/pipelines?page=1&scope=all&ref=main +.. |Code coverage| image:: https://codebase.helmholtz.cloud/psyplot/psy-view/badges/main/coverage.svg + :target: https://codebase.helmholtz.cloud/psyplot/psy-view/-/graphs/main/charts +.. |Latest Release| image:: https://codebase.helmholtz.cloud/psyplot/psy-view/-/badges/release.svg + :target: https://codebase.helmholtz.cloud/psyplot/psy-view +.. .. TODO: uncomment the following line when the package is published at https://pypi.org +.. .. |PyPI version| image:: https://img.shields.io/pypi/v/psy-view.svg +.. :target: https://pypi.python.org/pypi/psy-view/ +.. |Code style: black| image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/psf/black +.. |Imports: isort| image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336 + :target: https://pycqa.github.io/isort/ +.. |PEP8| image:: https://img.shields.io/badge/code%20style-pep8-orange.svg + :target: https://www.python.org/dev/peps/pep-0008/ +.. |Checked with mypy| image:: http://www.mypy-lang.org/static/mypy_badge.svg + :target: http://mypy-lang.org/ +.. TODO: uncomment the following line when the package is registered at https://api.reuse.software +.. .. |REUSE status| image:: https://api.reuse.software/badge/codebase.helmholtz.cloud/psyplot/psy-view +.. :target: https://api.reuse.software/info/codebase.helmholtz.cloud/psyplot/psy-view diff --git a/docs/installing.rst b/docs/installing.rst index ef70008..517b0eb 100644 --- a/docs/installing.rst +++ b/docs/installing.rst @@ -1,3 +1,7 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + .. _install: Installation diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..2e7d9b0 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,39 @@ +REM SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +REM +REM SPDX-License-Identifier: CC0-1.0 + +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +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% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/ncview.rst b/docs/ncview.rst index 9591eed..655a4bc 100644 --- a/docs/ncview.rst +++ b/docs/ncview.rst @@ -1,3 +1,7 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + .. _psy-view-vs-ncview: psy-view vs. ncview @@ -105,5 +109,5 @@ creating a new issue at https://github.com/psyplot/psy-view/issues/ .. _PyQt5: https://riverbankcomputing.com/software/pyqt .. _cartopy: https://scitools.org.uk/cartopy/docs/latest .. _psyplot GUI: https://psyplot.github.io/psyplot-gui/ -.. _ICON: https://mpimet.mpg.de/en/science/modeling-with-icon/icon-configurations +.. _ICON: https://code.mpimet.mpg.de/projects/iconpublic .. _UGRID: http://ugrid-conventions.github.io/ugrid-conventions/ diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..20e0654 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +sphinx-design +git+https://codebase.helmholtz.cloud/hcdc/hereon-netcdf/sphinxext.git +git+https://codebase.helmholtz.cloud/psyplot/psyplot.git@package-template +git+https://codebase.helmholtz.cloud/psyplot/psy-simple.git@package-template +git+https://codebase.helmholtz.cloud/psyplot/psy-maps.git@package-template +git+https://codebase.helmholtz.cloud/psyplot/psyplot-gui.git@package-template diff --git a/docs/todo.rst b/docs/todo.rst index 1892d81..c2d3870 100644 --- a/docs/todo.rst +++ b/docs/todo.rst @@ -1,6 +1,10 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + .. _todo: ToDos ===== -.. todolist:: \ No newline at end of file +.. todolist:: diff --git a/docs/user-guide.rst b/docs/user-guide.rst index 4dd7de0..5f4d3d6 100644 --- a/docs/user-guide.rst +++ b/docs/user-guide.rst @@ -1,3 +1,7 @@ +.. SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +.. +.. SPDX-License-Identifier: CC-BY-4.0 + .. _user-guide: User guide @@ -220,10 +224,14 @@ mapplot :suppress: In [1]: import psyplot.project as psy + ...: ...: with psy.plot.mapplot( - ...: "demo.nc", name="t2m", - ...: cmap="viridis", xgrid=False, ygrid=False, - ...: ) as sp: + ...: "demo.nc", + ...: name="t2m", + ...: cmap="viridis", + ...: xgrid=False, + ...: ygrid=False, + ...: ) as sp: ...: sp.export("docs-mapplot-example.png") .. image:: docs-mapplot-example.png @@ -330,10 +338,12 @@ plot2d :suppress: In [1]: import psyplot.project as psy + ...: ...: with psy.plot.plot2d( - ...: "demo.nc", name="t2m", - ...: cmap="viridis", - ...: ) as sp: + ...: "demo.nc", + ...: name="t2m", + ...: cmap="viridis", + ...: ) as sp: ...: sp.export("docs-plot2d-example.png") .. image:: docs-plot2d-example.png @@ -358,13 +368,19 @@ lineplot :okwarning: In [1]: import psyplot.project as psy + ...: ...: with psy.plot.lineplot( - ...: "demo.nc", name="t2m", x=0, y=[0, 15], z=0, - ...: xticklabels='%B', xticks='data', - ...: legendlabels='%(y)1.0f°N', - ...: legend='lower right', - ...: ylabel='{desc}', - ...: ) as sp: + ...: "demo.nc", + ...: name="t2m", + ...: x=0, + ...: y=[0, 15], + ...: z=0, + ...: xticklabels="%B", + ...: xticks="data", + ...: legendlabels="%(y)1.0f°N", + ...: legend="lower right", + ...: ylabel="{desc}", + ...: ) as sp: ...: sp.export("docs-lineplot-example.png") .. image:: docs-lineplot-example.png diff --git a/icon/CreateICNS.sh b/icon/CreateICNS.sh index 6ea7bfe..690a2a5 100644 --- a/icon/CreateICNS.sh +++ b/icon/CreateICNS.sh @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: LGPL-3.0-only + mkdir main.iconset sips -z 16 16 icon1024.png --out main.iconset/icon_16x16.png sips -z 32 32 icon1024.png --out main.iconset/icon_16x16@2x.png diff --git a/icon/CreateICO.sh b/icon/CreateICO.sh index 205b444..56c4d23 100644 --- a/icon/CreateICO.sh +++ b/icon/CreateICO.sh @@ -1 +1,5 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: LGPL-3.0-only + convert icon1024.png -define icon:auto-resize=64,48,32,16 psyplot.ico diff --git a/icon/icon.py b/icon/icon.py index c06f8f7..3ba034e 100644 --- a/icon/icon.py +++ b/icon/icon.py @@ -1,33 +1,43 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: LGPL-3.0-only + """Create the psyplot icon This script creates the psyplot icon with a dpi of 128 and a width and height of 8 inches. The file is saved it to ``'icon1024.pkl'``""" -import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cf +import matplotlib.pyplot as plt from matplotlib.text import FontProperties # The path to the font -fontpath = '/usr/share/fonts/truetype/freefont/FreeSansBoldOblique.ttf' +fontpath = "/usr/share/fonts/truetype/freefont/FreeSansBoldOblique.ttf" fig = plt.figure(figsize=(8, 8), dpi=128) -ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], projection=ccrs.Orthographic( - central_latitude=5)) +ax = fig.add_axes( + [0.0, 0.0, 1.0, 1.0], projection=ccrs.Orthographic(central_latitude=5) +) -land = ax.add_feature(cf.LAND, facecolor='0.975') -ocean = ax.add_feature(cf.OCEAN, facecolor=plt.get_cmap('Blues')(0.5)) +land = ax.add_feature(cf.LAND, facecolor="0.975") +ocean = ax.add_feature(cf.OCEAN, facecolor=plt.get_cmap("Blues")(0.5)) text = ax.text( - 0.47, 0.5, 'Psy', + 0.47, + 0.5, + "Psy", transform=fig.transFigure, - name='FreeSans', + name="FreeSans", fontproperties=FontProperties(fname=fontpath), - size=256, ha='center', va='center', - weight=400) + size=256, + ha="center", + va="center", + weight=400, +) -ax.outline_patch.set_edgecolor('none') +ax.outline_patch.set_edgecolor("none") -plt.savefig('icon1024.png', transparent=True) -plt.savefig('icon1024.svg', transparent=True) +plt.savefig("icon1024.png", transparent=True) +plt.savefig("icon1024.svg", transparent=True) diff --git a/icon/icon1024.png.license b/icon/icon1024.png.license new file mode 100644 index 0000000..b21fae9 --- /dev/null +++ b/icon/icon1024.png.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/icon/icon1024.svg b/icon/icon1024.svg index 491c49e..fc31359 100644 --- a/icon/icon1024.svg +++ b/icon/icon1024.svg @@ -10,5699 +10,5699 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icon/icon1024.svg.license b/icon/icon1024.svg.license new file mode 100644 index 0000000..b21fae9 --- /dev/null +++ b/icon/icon1024.svg.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/icon/psy-view.svg b/icon/psy-view.svg index 23540d1..d4338f7 100644 --- a/icon/psy-view.svg +++ b/icon/psy-view.svg @@ -10,5686 +10,5686 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icon/psy-view.svg.license b/icon/psy-view.svg.license new file mode 100644 index 0000000..b21fae9 --- /dev/null +++ b/icon/psy-view.svg.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/icon/psyplot.svg b/icon/psyplot.svg index 23540d1..d4338f7 100644 --- a/icon/psyplot.svg +++ b/icon/psyplot.svg @@ -10,5686 +10,5686 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icon/psyplot.svg.license b/icon/psyplot.svg.license new file mode 100644 index 0000000..b21fae9 --- /dev/null +++ b/icon/psyplot.svg.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/psy_view/__init__.py b/psy_view/__init__.py index 48715ff..98e3b71 100644 --- a/psy_view/__init__.py +++ b/psy_view/__init__.py @@ -1,49 +1,24 @@ -# -*- coding: utf-8 -*- -"""ncview-like GUI to the psyplot framework.""" - -# Disclaimer -# ---------- -# -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only + +"""psy-view + +ncview-like interface to psyplot +""" from __future__ import annotations -from typing import ( - Dict, - Any, - Optional, - Tuple, - Union, - Type, -) -import sys import argparse +import sys +from typing import Optional # importing xarray here for some reason speeds up starting the GUI... import xarray as xr -from ._version import get_versions +from . import _version -__version__ = get_versions()['version'] - -del get_versions +__version__ = _version.get_versions()["version"] __author__ = "Philipp S. Sommer" @@ -56,15 +31,17 @@ __license__ = "LGPL-3.0-only" __maintainer__ = "Philipp S. Sommer" -__email__ = "psyplot@hereon.de" +__email__ = "philipp.sommer@hereon.de" __status__ = "Production" def start_app( - ds: Optional[xr.Dataset], name: Optional[str] = None, - plotmethod: str = 'mapplot', preset: Optional[str] = None - ) -> None: + ds: Optional[xr.Dataset], + name: Optional[str] = None, + plotmethod: str = "mapplot", + preset: Optional[str] = None, +) -> None: """Start the standalone GUI application. This function creates a `QApplication` instance, an instance of the @@ -82,18 +59,19 @@ def start_app( preset: str The preset to apply """ + from psyplot_gui import rcParams from PyQt5 import QtWidgets from PyQt5.QtGui import QIcon # pylint: disable=no-name-in-module - from psyplot_gui import rcParams - rcParams['help_explorer.use_webengineview'] = False + rcParams["help_explorer.use_webengineview"] = False - from psy_view.ds_widget import DatasetWidgetStandAlone from psyplot_gui.common import get_icon + from psy_view.ds_widget import DatasetWidgetStandAlone + app = QtWidgets.QApplication(sys.argv) ds_widget = DatasetWidgetStandAlone(ds) - ds_widget.setWindowIcon(QIcon(get_icon('logo.svg'))) + ds_widget.setWindowIcon(QIcon(get_icon("logo.svg"))) if preset is not None: ds_widget.load_preset(preset) if name is not None: @@ -101,8 +79,10 @@ def start_app( raise ValueError("Variable specified but without dataset") elif name not in ds_widget.variable_buttons: valid = list(ds_widget.variable_buttons) - raise ValueError(f"{name} is not part of the dataset. " - f"Possible variables are {valid}.") + raise ValueError( + f"{name} is not part of the dataset. " + f"Possible variables are {valid}." + ) ds_widget.plotmethod = plotmethod ds_widget.variable = name ds_widget.make_plot() @@ -116,33 +96,46 @@ def start_app( def get_parser() -> argparse.ArgumentParser: """Get the command line parser for psy-view.""" from textwrap import dedent - parser = argparse.ArgumentParser('psy-view') - parser.add_argument( - 'input_file', help="The file to visualize", nargs='?', default=None) + parser = argparse.ArgumentParser("psy-view") parser.add_argument( - '-n', '--name', - help=("Variable name to display. Don't provide a variable to display " - "the first variable found in the dataset."), - const=object, nargs="?") + "input_file", help="The file to visualize", nargs="?", default=None + ) parser.add_argument( - '-pm', '--plotmethod', help="The plotmethod to use", default="mapplot", - choices=["mapplot", "plot2d", "lineplot"]) + "-n", + "--name", + help=( + "Variable name to display. Don't provide a variable to display " + "the first variable found in the dataset." + ), + const=object, + nargs="?", + ) parser.add_argument( - '--preset', help="Apply a preset to the plot") + "-pm", + "--plotmethod", + help="The plotmethod to use", + default="mapplot", + choices=["mapplot", "plot2d", "lineplot"], + ) + + parser.add_argument("--preset", help="Apply a preset to the plot") parser.add_argument( - '-V', '--version', action='version', version=__version__) + "-V", "--version", action="version", version=__version__ + ) - parser.epilog = dedent(""" + parser.epilog = dedent( + """ psy-view Copyright (C) 2020 Philipp S. Sommer This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it - under the conditions of the GNU GENERAL PUBLIC LICENSE, Version 3.""") + under the conditions of the GNU GENERAL PUBLIC LICENSE, Version 3.""" + ) return parser @@ -150,13 +143,14 @@ def get_parser() -> argparse.ArgumentParser: def main() -> None: """Start the app with the provided command-line options.""" import psyplot.project as psy + parser = get_parser() args = parser.parse_known_args()[0] if args.input_file is not None: try: ds = psy.open_dataset(args.input_file) - except: + except Exception: ds = psy.open_dataset(args.input_file, decode_times=False) else: ds = None diff --git a/psy_view/__main__.py b/psy_view/__main__.py index 39058c2..8e53215 100644 --- a/psy_view/__main__.py +++ b/psy_view/__main__.py @@ -19,29 +19,12 @@ along with this program. If not, see https://www.gnu.org/licenses/. """ -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only import psy_view -if __name__ == '__main__': +if __name__ == "__main__": psy_view.main() diff --git a/psy_view/_version.py b/psy_view/_version.py index c0f0515..e12c8ce 100644 --- a/psy_view/_version.py +++ b/psy_view/_version.py @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: LGPL-3.0-only # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag @@ -6,45 +9,16 @@ # that just contains the computed version number. # This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) +# versioneer-0.21 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" -# Disclaimer -# ---------- -# -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . -# -# This file is originally released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) - - -# pylint: skip-file - -from typing import Dict - import errno import os import re import subprocess import sys +from typing import Callable, Dict def get_keywords(): @@ -83,35 +57,41 @@ class NotThisMethod(Exception): LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f + return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): +def run_command( + commands, args, cwd=None, verbose=False, hide_stderr=False, env=None +): """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + process = subprocess.Popen( + [command] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + ) break - except EnvironmentError: + except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue @@ -123,15 +103,13 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, if verbose: print("unable to find command, tried %s" % (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): @@ -143,19 +121,24 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + return { + "version": dirname[len(parentdir_prefix) :], + "full-revisionid": None, + "dirty": False, + "error": None, + "date": None, + } + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -168,22 +151,21 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @@ -191,10 +173,14 @@ def git_get_keywords(versionfile_abs): @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -207,11 +193,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -220,7 +206,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -228,23 +214,35 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r"\d", r): + continue if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -252,11 +250,14 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): version string, meaning we're inside a checked out source tree. """ GITS = ["git"] + TAG_PREFIX_REGEX = "*" if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] + TAG_PREFIX_REGEX = r"\*" - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + _, rc = runner( + GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True + ) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -264,15 +265,24 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) + describe_out, rc = runner( + GITS, + [ + "describe", + "--tags", + "--dirty", + "--always", + "--long", + "--match", + "%s%s" % (tag_prefix, TAG_PREFIX_REGEX), + ], + cwd=root, + ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() @@ -282,6 +292,40 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner( + GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root + ) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -290,17 +334,18 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + # unparsable. Maybe git-describe is misbehaving? + pieces["error"] = ( + "unable to parse git-describe output: '%s'" % describe_out + ) return pieces # tag @@ -309,10 +354,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -323,13 +370,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) + count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ + 0 + ].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces @@ -360,26 +410,77 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces): + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver): + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces): + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post( + pieces["closest-tag"] + ) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % ( + post_version + 1, + pieces["distance"], + ) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] + rendered = "0.post0.dev%d" % pieces["distance"] return rendered @@ -410,12 +511,41 @@ def render_pep440_post(pieces): return rendered +def render_pep440_post_branch(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -475,21 +605,27 @@ def render_git_describe_long(pieces): def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -499,9 +635,13 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } def get_versions(): @@ -515,8 +655,9 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) + return git_versions_from_keywords( + get_keywords(), cfg.tag_prefix, verbose + ) except NotThisMethod: pass @@ -525,13 +666,16 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for _ in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None, + } try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) @@ -545,6 +689,10 @@ def get_versions(): except NotThisMethod: pass - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } diff --git a/psy_view/dialogs.py b/psy_view/dialogs.py index c3bc876..ceaac8d 100644 --- a/psy_view/dialogs.py +++ b/psy_view/dialogs.py @@ -1,45 +1,21 @@ """Dialogs for manipulating formatoptions.""" -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only from __future__ import annotations -from typing import ( - TYPE_CHECKING, - Dict, - Any, - Optional, - Tuple, - Union, - Type, -) + +from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Type, Union import yaml -from PyQt5 import QtWidgets, QtGui from matplotlib.backends.backend_qt5agg import ( - FigureCanvasQTAgg as FigureCanvas) + FigureCanvasQTAgg as FigureCanvas, +) from matplotlib.figure import Figure - -from psyplot.plotter import Plotter, Formatoption +from psyplot.plotter import Formatoption, Plotter +from PyQt5 import QtGui, QtWidgets if TYPE_CHECKING: from psyplot.project import Project @@ -66,13 +42,14 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: plotter: psy_maps.plotters.MapPlotter The psyplot plotter to configure """ - import psy_simple.widgets.colors as pswc import pandas as pd + import psy_simple.widgets.colors as pswc + super().__init__(*args, **kwargs) vbox = QtWidgets.QVBoxLayout(self) #: colors that affect the map background - self.colors = ['background', 'land', 'ocean', 'coast'] + self.colors = ["background", "land", "ocean", "coast"] #: QGridLayout to display the various colors grid = QtWidgets.QGridLayout() @@ -81,7 +58,8 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: #: :class:`pandas.DataFrame` of widgets to modifiy the :attr:`colors` self.widgets = widgets = pd.DataFrame( - index=['enable', 'color'], columns=self.colors, dtype=object) + index=["enable", "color"], columns=self.colors, dtype=object + ) for i, col in enumerate(self.colors): widgets.iloc[0, i] = cb = QtWidgets.QCheckBox() @@ -100,7 +78,8 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: #: Button box to cancel the operator or update the plotter self.button_box = QtWidgets.QDialogButtonBox( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, - self) + self, + ) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) @@ -110,23 +89,23 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: #: text box for the central longitude (clon formatoption) self.txt_clon = QtWidgets.QLineEdit() - self.txt_clon.setPlaceholderText('auto') - self.txt_clon.setToolTip('Central longitude in degrees East') + self.txt_clon.setPlaceholderText("auto") + self.txt_clon.setToolTip("Central longitude in degrees East") self.txt_clon.setValidator(QtGui.QDoubleValidator(-360, 360, 7)) - layout.addRow('Central longitude: ', self.txt_clon) + layout.addRow("Central longitude: ", self.txt_clon) #: text box for the central latitude (clat formatoption) self.txt_clat = QtWidgets.QLineEdit() - self.txt_clat.setPlaceholderText('auto') - self.txt_clat.setToolTip('Central latitude in degrees North') + self.txt_clat.setPlaceholderText("auto") + self.txt_clat.setToolTip("Central latitude in degrees North") self.txt_clat.setValidator(QtGui.QDoubleValidator(-90, 90, 7)) - layout.addRow('Central latitude: ', self.txt_clat) + layout.addRow("Central latitude: ", self.txt_clat) vbox.addWidget(proj_box) #: group box for modifying the resolution of the land-sea-mask, see #: :attr:`opt_110m`, :attr:`opt_50m`, :attr:`opt_10m` - self.lsm_box = QtWidgets.QGroupBox('Coastlines') + self.lsm_box = QtWidgets.QGroupBox("Coastlines") self.lsm_box.setCheckable(True) hbox = QtWidgets.QHBoxLayout(self.lsm_box) hbox.addWidget(QtWidgets.QLabel("Resolution:")) @@ -146,9 +125,10 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: vbox.addWidget(self.lsm_box) #: group box drawing grid lines and labels - self.grid_labels_box = QtWidgets.QGroupBox('Labels') - self.grid_labels_box.setToolTip("Draw labels of meridionals and " - "parallels") + self.grid_labels_box = QtWidgets.QGroupBox("Labels") + self.grid_labels_box.setToolTip( + "Draw labels of meridionals and " "parallels" + ) self.grid_labels_box.setCheckable(True) #: text box for the fontsize of grid labels @@ -162,7 +142,7 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: #: Group box for options specific to meridionals (see #: :attr:`opt_meri_auto`, :attr:`opt_meri_at` and #: :attr:`opt_meri_every`, :attr:`opt_meri_num`) - self.meridionals_box = QtWidgets.QGroupBox('Meridionals') + self.meridionals_box = QtWidgets.QGroupBox("Meridionals") self.meridionals_box.setCheckable(True) #: Radiobutton for automatic drawing of meridionals @@ -209,7 +189,7 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: #: Group box for options specific to parallels (see #: :attr:`opt_para_auto`, :attr:`opt_para_at` and #: :attr:`opt_para_every`, :attr:`opt_para_num`) - self.parallels_box = QtWidgets.QGroupBox('Parallels') + self.parallels_box = QtWidgets.QGroupBox("Parallels") self.parallels_box.setCheckable(True) #: Radiobutton for automatic drawing of parallels @@ -257,10 +237,16 @@ def __init__(self, plotter: Plotter, *args, **kwargs) -> None: self.fill_from_plotter(plotter) - for button in [self.opt_meri_at, self.opt_meri_auto, self.opt_meri_num, - self.opt_meri_every, self.opt_para_at, - self.opt_para_auto, self.opt_para_num, - self.opt_para_every]: + for button in [ + self.opt_meri_at, + self.opt_meri_auto, + self.opt_meri_num, + self.opt_meri_every, + self.opt_para_at, + self.opt_para_auto, + self.opt_para_num, + self.opt_para_every, + ]: button.clicked.connect(self.update_forms) @property @@ -268,12 +254,13 @@ def default_colors(self) -> Dict[str, Color]: """Get default colors for the color labels in :attr:`widgets`.""" import cartopy.feature as cf import matplotlib as mpl + return { - 'background': mpl.rcParams['axes.facecolor'], - 'land': cf.LAND._kwargs['facecolor'], - 'ocean': cf.OCEAN._kwargs['facecolor'], - 'coast': 'k', - } + "background": mpl.rcParams["axes.facecolor"], + "land": cf.LAND._kwargs["facecolor"], + "ocean": cf.OCEAN._kwargs["facecolor"], + "coast": "k", + } def get_colors(self, plotter: Plotter) -> Dict[str, Color]: """Get the colors for :attr:`widgets` from the plotter formatoptions. @@ -290,10 +277,10 @@ def get_colors(self, plotter: Plotter) -> Dict[str, Color]: color in the `plotter`. """ ret = {} - if plotter.background.value != 'rc': - ret['background'] = plotter.background.value + if plotter.background.value != "rc": + ret["background"] = plotter.background.value lsm = plotter.lsm.value - for part in ['land', 'ocean', 'coast']: + for part in ["land", "ocean", "coast"]: if part in lsm: ret[part] = lsm[part] return ret @@ -326,8 +313,8 @@ def fill_from_plotter(self, plotter: Plotter) -> None: if not lsm: self.lsm_box.setChecked(False) else: - res = lsm['res'] - getattr(self, 'opt_' + res).setChecked(True) + res = lsm["res"] + getattr(self, "opt_" + res).setChecked(True) grid_labels = plotter.grid_labels.value if grid_labels is None: @@ -352,7 +339,7 @@ def fill_from_plotter(self, plotter: Plotter) -> None: self.txt_meri_num.setText(str(steps)) else: self.opt_meri_at.setChecked(True) - self.txt_meri_at.setText(', '.join(map(str, value))) + self.txt_meri_at.setText(", ".join(map(str, value))) self.ygrid_value = None value = plotter.ygrid.value @@ -371,11 +358,10 @@ def fill_from_plotter(self, plotter: Plotter) -> None: self.txt_para_num.setText(str(steps)) else: self.opt_para_at.setChecked(True) - self.txt_para_at.setText(', '.join(map(str, value))) + self.txt_para_at.setText(", ".join(map(str, value))) def update_forms(self) -> None: - """Update text widgets for the options to draw merdionals and parallels. - """ + """Update text widgets for the options to draw merdionals and parallels.""" if self.meridionals_box.isChecked(): self.txt_meri_at.setEnabled(self.opt_meri_at.isChecked()) self.txt_meri_every.setEnabled(self.opt_meri_every.isChecked()) @@ -389,36 +375,43 @@ def update_forms(self) -> None: def value(self) -> Dict[str, Any]: """Get the formatoptions of this dialog to update a plotter.""" import numpy as np + ret: Dict[str, Any] = {} - ret['clon'] = None if not self.txt_clon.text().strip() else float( - self.txt_clon.text().strip()) - ret['clat'] = None if not self.txt_clat.text().strip() else float( - self.txt_clat.text().strip()) + ret["clon"] = ( + None + if not self.txt_clon.text().strip() + else float(self.txt_clon.text().strip()) + ) + ret["clat"] = ( + None + if not self.txt_clat.text().strip() + else float(self.txt_clat.text().strip()) + ) lsm: LSM_T = {} - for col in ['land', 'ocean', 'coast']: - lbl = self.widgets.loc['color', col] + for col in ["land", "ocean", "coast"]: + lbl = self.widgets.loc["color", col] if lbl.isEnabled(): lsm[col] = list(lbl.color.getRgbF()) if lsm or self.lsm_box.isChecked(): if self.opt_110m.isChecked(): - lsm['res'] = '110m' + lsm["res"] = "110m" elif self.opt_50m.isChecked(): - lsm['res'] = '50m' + lsm["res"] = "50m" elif self.opt_10m.isChecked(): - lsm['res'] = '10m' + lsm["res"] = "10m" else: - lsm['res'] = '110m' + lsm["res"] = "110m" else: - lsm['res'] = False + lsm["res"] = False if lsm: - ret['lsm'] = lsm + ret["lsm"] = lsm - bc_lbl = self.widgets.loc['color', 'background'] + bc_lbl = self.widgets.loc["color", "background"] if bc_lbl.isEnabled(): - ret['background'] = list(bc_lbl.color.getRgbF()) + ret["background"] = list(bc_lbl.color.getRgbF()) ret["grid_labels"] = self.grid_labels_box.isChecked() if ret["grid_labels"]: @@ -432,44 +425,54 @@ def value(self) -> Dict[str, Any]: ret["grid_labelsize"] = labelsize if not self.meridionals_box.isChecked(): - ret['xgrid'] = False + ret["xgrid"] = False elif self.opt_meri_auto.isChecked(): - ret['xgrid'] = True + ret["xgrid"] = True elif self.opt_meri_every.isChecked(): - ret['xgrid'] = np.arange( - -180, 180, float(self.txt_meri_every.text().strip() or 30)) + ret["xgrid"] = np.arange( + -180, 180, float(self.txt_meri_every.text().strip() or 30) + ) elif self.opt_meri_at.isChecked(): - ret['xgrid'] = list(map( - float, self.txt_meri_at.text().split(','))) or False + ret["xgrid"] = ( + list(map(float, self.txt_meri_at.text().split(","))) or False + ) elif self.opt_meri_num.isChecked(): if self.xgrid_value is None: - ret['xgrid'] = ['rounded', int(self.txt_meri_num.text() or 5)] + ret["xgrid"] = ["rounded", int(self.txt_meri_num.text() or 5)] elif isinstance(self.xgrid_value, str): - ret['xgrid'] = [self.xgrid_value, - int(self.txt_meri_num.text() or 5)] + ret["xgrid"] = [ + self.xgrid_value, + int(self.txt_meri_num.text() or 5), + ] else: - ret['xgrid'] = tuple(self.xgrid_value) + ( - int(self.txt_meri_num.text() or 5), ) + ret["xgrid"] = tuple(self.xgrid_value) + ( + int(self.txt_meri_num.text() or 5), + ) if not self.parallels_box.isChecked(): - ret['ygrid'] = False + ret["ygrid"] = False elif self.opt_para_auto.isChecked(): - ret['ygrid'] = True + ret["ygrid"] = True elif self.opt_para_every.isChecked(): - ret['ygrid'] = np.arange( - -180, 180, float(self.txt_para_every.text().strip() or 30)) + ret["ygrid"] = np.arange( + -180, 180, float(self.txt_para_every.text().strip() or 30) + ) elif self.opt_para_at.isChecked(): - ret['ygrid'] = list(map( - float, self.txt_para_at.text().split(','))) or False + ret["ygrid"] = ( + list(map(float, self.txt_para_at.text().split(","))) or False + ) elif self.opt_para_num.isChecked(): if self.ygrid_value is None: - ret['ygrid'] = ['rounded', int(self.txt_para_num.text() or 5)] + ret["ygrid"] = ["rounded", int(self.txt_para_num.text() or 5)] elif isinstance(self.ygrid_value, str): - ret['ygrid'] = [self.ygrid_value, - int(self.txt_para_num.text() or 5)] + ret["ygrid"] = [ + self.ygrid_value, + int(self.txt_para_num.text() or 5), + ] else: - ret['ygrid'] = tuple(self.ygrid_value) + ( - int(self.txt_para_num.text() or 5), ) + ret["ygrid"] = tuple(self.ygrid_value) + ( + int(self.txt_para_num.text() or 5), + ) return ret @classmethod @@ -487,8 +490,7 @@ def update_plotter(cls, plotter: Plotter) -> None: dialog.activateWindow() dialog.exec_() if dialog.result() == QtWidgets.QDialog.Accepted: - plotter.update( - **dialog.value) + plotter.update(**dialog.value) class CmapDialog(QtWidgets.QDialog): @@ -503,46 +505,60 @@ def __init__(self, project: Project, *args, **kwargs) -> None: very first plotter in this project """ import psy_simple.widgets.colors as pswc + super().__init__(*args, **kwargs) #: Button box to accept or cancel this dialog self.button_box = QtWidgets.QDialogButtonBox( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, - self) + self, + ) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) #: Mapping from formatoption key to :class:`LabelWidgetLine` widgets to #: controlling the formatoption self.fmt_widgets = {} - plotter = project(fmts=['cmap', 'bounds']).plotters[0] + plotter = project(fmts=["cmap", "bounds"]).plotters[0] #: Widget for manipulating the color map - self.cmap_widget = self.fmt_widgets['cmap'] = LabelWidgetLine( - plotter.cmap, project, pswc.CMapFmtWidget, - widget_kws=dict(properties=False)) + self.cmap_widget = self.fmt_widgets["cmap"] = LabelWidgetLine( + plotter.cmap, + project, + pswc.CMapFmtWidget, + widget_kws=dict(properties=False), + ) self.cmap_widget.editor.setVisible(False) self.cmap_widget.editor.line_edit.textChanged.connect( - self.update_preview) + self.update_preview + ) #: tabs for switching between bounds (:attr:`bounds_widget`) and #: colorbar ticks (:attr:`cticks_widget`) self.tabs = QtWidgets.QTabWidget() #: :class:`LabelWidgetLine` to controll the colorbar bounds - self.bounds_widget = self.fmt_widgets['bounds'] = LabelWidgetLine( - plotter.bounds, project, pswc.BoundsFmtWidget, - widget_kws=dict(properties=False)) + self.bounds_widget = self.fmt_widgets["bounds"] = LabelWidgetLine( + plotter.bounds, + project, + pswc.BoundsFmtWidget, + widget_kws=dict(properties=False), + ) self.bounds_widget.editor.line_edit.textChanged.connect( - self.update_preview) + self.update_preview + ) self.tabs.addTab(self.bounds_widget, "Colormap boundaries") #: :class:`LabelWidgetLine` to controll the ctick positions - self.cticks_widget = self.fmt_widgets['cticks'] = LabelWidgetLine( - plotter.cticks, project, pswc.CTicksFmtWidget, - widget_kws=dict(properties=False)) + self.cticks_widget = self.fmt_widgets["cticks"] = LabelWidgetLine( + plotter.cticks, + project, + pswc.CTicksFmtWidget, + widget_kws=dict(properties=False), + ) self.cticks_widget.editor.line_edit.textChanged.connect( - self.update_preview) + self.update_preview + ) self.tabs.addTab(self.cticks_widget, "Colorbar ticks") #: :class:`ColorbarPreview` to show a preview of the colorbar with @@ -562,8 +578,7 @@ def plotter(self) -> Plotter: return self.bounds_widget.editor.fmto.plotter def update_preview(self) -> None: - """Update the :attr:`cbar_preview` from the various :attr:`fmt_widgets`. - """ + """Update the :attr:`cbar_preview` from the various :attr:`fmt_widgets`.""" try: bounds = self.bounds_widget.editor.value except Exception: @@ -577,7 +592,8 @@ def update_preview(self) -> None: except Exception: cmap = self.plotter.cmap.value self.cbar_preview.update_colorbar( - bounds=bounds, cticks=cticks, cmap=cmap) + bounds=bounds, cticks=cticks, cmap=cmap + ) @property def fmts(self) -> Dict[str, Any]: @@ -587,9 +603,11 @@ def fmts(self) -> Dict[str, Any]: if widget.editor.changed: try: value = widget.editor.value - except: - raise IOError(f"{fmt}-value {widget.editor.text} could " - "not be parsed to python!") + except Exception: + raise IOError( + f"{fmt}-value {widget.editor.text} could " + "not be parsed to python!" + ) else: ret[fmt] = value return ret @@ -623,17 +641,20 @@ class _DummyFormatOption(Formatoption): what the :class:`FakePlotter` formatoptions are, used in :attr:`ColorbarPreview.fake_plotter` """ - def update(self,): + + def update( + self, + ): pass class FakePlotter(Plotter): """A dummy plotter for the colorbar preview.""" - bounds: Formatoption = _DummyFormatOption('bounds') - cmap: Formatoption = _DummyFormatOption('cmap') - cticks: Formatoption = _DummyFormatOption('cticks') - cbar: Formatoption = _DummyFormatOption('cbar') + bounds: Formatoption = _DummyFormatOption("bounds") + cmap: Formatoption = _DummyFormatOption("cmap") + cticks: Formatoption = _DummyFormatOption("cticks") + cbar: Formatoption = _DummyFormatOption("cbar") class ColorbarPreview(FigureCanvas): @@ -643,11 +664,12 @@ class ColorbarPreview(FigureCanvas): filled by the formatoptions of a given `plotter`.""" def __init__( - self, - plotter: Plotter, - parent: Optional[QtWidgets.QWidget] = None, - *args, **kwargs - ) -> None: + self, + plotter: Plotter, + parent: Optional[QtWidgets.QWidget] = None, + *args, + **kwargs, + ) -> None: """ Parameters ---------- @@ -661,9 +683,11 @@ def __init__( FigureCanvas.__init__(self, fig) self.setParent(parent) - FigureCanvas.setSizePolicy(self, - QtWidgets.QSizePolicy.Expanding, - QtWidgets.QSizePolicy.Expanding) + FigureCanvas.setSizePolicy( + self, + QtWidgets.QSizePolicy.Expanding, + QtWidgets.QSizePolicy.Expanding, + ) FigureCanvas.updateGeometry(self) self.axes_counter = 0 @@ -685,17 +709,20 @@ def init_colorbar(self, plotter: Plotter) -> None: the colorbar. """ from matplotlib.cm import ScalarMappable + norm = plotter.bounds.norm cmap = plotter.cmap.get_cmap(self.plotter.plot.array) self.mappable = sm = ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) - self.cax = self.figure.add_axes([0.1, 0.5, 0.8, 0.5], - label=self.axes_counter) + self.cax = self.figure.add_axes( + [0.1, 0.5, 0.8, 0.5], label=self.axes_counter + ) self.cbar = self.figure.colorbar( - sm, norm=norm, cmap=cmap, cax=self.cax, orientation='horizontal') + sm, norm=norm, cmap=cmap, cax=self.cax, orientation="horizontal" + ) @property def fake_plotter(self) -> FakePlotter: @@ -703,13 +730,12 @@ def fake_plotter(self) -> FakePlotter: We can update this plotter without impacting the origin :attr:`plotter` """ - from psyplot.plotter import Plotter class _FakePlotter(FakePlotter): - bounds = self.plotter.bounds.__class__('bounds') - cmap = self.plotter.cmap.__class__('cmap') - cticks = self.plotter.cticks.__class__('cticks') - cbar = self.plotter.cbar.__class__('cbar') + bounds = self.plotter.bounds.__class__("bounds") + cmap = self.plotter.cmap.__class__("cmap") + cticks = self.plotter.cticks.__class__("cticks") + cbar = self.plotter.cbar.__class__("cbar") _rcparams_string = self.plotter._get_rc_strings() @@ -718,8 +744,14 @@ class _FakePlotter(FakePlotter): ax = fig.add_subplot() plotter = _FakePlotter( - ref.data.copy(), make_plot=False, bounds=ref['bounds'], - cmap=ref['cmap'], cticks=ref['cticks'], cbar='', ax=ax) + ref.data.copy(), + make_plot=False, + bounds=ref["bounds"], + cmap=ref["cmap"], + cticks=ref["cticks"], + cbar="", + ax=ax, + ) plotter.cticks._colorbar = self.cbar @@ -766,11 +798,13 @@ def update_colorbar(self, **kwargs) -> None: except AttributeError: pass self.mappable.set_norm(plotter.bounds.norm) - self.mappable.set_cmap(plotter.cmap.get_cmap( - self.plotter.plot.array)) + self.mappable.set_cmap( + plotter.cmap.get_cmap(self.plotter.plot.array) + ) plotter.cticks.colorbar = self.cbar - plotter.cticks.default_locator = \ + plotter.cticks.default_locator = ( self.plotter.cticks.default_locator + ) plotter.cticks.update_axis(plotter.cticks.value) self.draw() @@ -816,7 +850,7 @@ def __init__(self, fmto: Formatoption, *args, **kwargs) -> None: #: A tool button to switch from the single line editor :attr:`line_edit` #: to the multi-line editor :attr:`text_edit` self.btn_multiline = QtWidgets.QToolButton() - self.btn_multiline.setText('⌵') + self.btn_multiline.setText("⌵") self.btn_multiline.setCheckable(True) self.btn_multiline.setToolTip("Toggle multiline editor") self.btn_multiline.clicked.connect(self.toggle_multiline) @@ -831,8 +865,7 @@ def __init__(self, fmto: Formatoption, *args, **kwargs) -> None: @property def changed(self) -> bool: - """Check if the value in this editor differs from the original `fmto`. - """ + """Check if the value in this editor differs from the original `fmto`.""" return self.fmto.diff(self.fmto.validate(self.get_obj())) def toggle_multiline(self) -> None: @@ -853,8 +886,11 @@ def multiline(self) -> bool: @property def text(self) -> str: """Text of the :attr:`text_edit` (or :attr:`line_edit`).""" - return (self.text_edit.toPlainText() if self.multiline else - self.line_edit.text()) + return ( + self.text_edit.toPlainText() + if self.multiline + else self.line_edit.text() + ) @text.setter def text(self, s: str) -> None: @@ -915,12 +951,12 @@ def insert_obj(self, obj: Any) -> None: s = '"' + obj + current + '"' else: s = '"' + current + obj + '"' - current = '' + current = "" elif isinstance(obj, str): # add quotation marks s = '"' + obj + '"' else: s = yaml.dump(obj, default_flow_style=True).strip() - if s.endswith('\n...'): + if s.endswith("\n..."): s = s[:-4] if use_line_edit: self.line_edit.insert(s) @@ -937,9 +973,15 @@ class LabelWidgetLine(QtWidgets.QGroupBox): :meth:`psyplot.plotter.Formatoption.get_fmt_widget`) to contol it. """ - def __init__(self, fmto: Formatoption, project: Project, - fmto_widget: Type[QtWidgets.QWidget], - widget_kws: Dict[str, Any] = {}, *args, **kwargs) -> None: + def __init__( + self, + fmto: Formatoption, + project: Project, + fmto_widget: Type[QtWidgets.QWidget], + widget_kws: Dict[str, Any] = {}, + *args, + **kwargs, + ) -> None: """ Parameters ---------- @@ -956,11 +998,10 @@ def __init__(self, fmto: Formatoption, project: Project, Further keywords that are passed to the creation of the `fmto_widget` instance. """ - super().__init__(f'{fmto.name} ({fmto.key})', *args, **kwargs) + super().__init__(f"{fmto.name} ({fmto.key})", *args, **kwargs) self.editor = FormatoptionsEditor(fmto) vbox = QtWidgets.QVBoxLayout() - vbox.addWidget( - fmto_widget(self.editor, fmto, project, **widget_kws)) + vbox.addWidget(fmto_widget(self.editor, fmto, project, **widget_kws)) vbox.addWidget(self.editor) self.setLayout(vbox) @@ -982,6 +1023,7 @@ def __init__(self, project: Project, *fmts: str) -> None: subclass of :class:`psy_simple.base.TextBase` """ from psy_simple.widgets.texts import LabelWidget + super().__init__() self.project = project layout = QtWidgets.QVBoxLayout() @@ -990,13 +1032,15 @@ def __init__(self, project: Project, *fmts: str) -> None: for fmt in fmts: fmto = getattr(plotter, fmt) fmt_widget = LabelWidgetLine( - fmto, project, LabelWidget, widget_kws=dict(properties=False)) + fmto, project, LabelWidget, widget_kws=dict(properties=False) + ) self.fmt_widgets[fmt] = fmt_widget layout.addWidget(fmt_widget) self.button_box = QtWidgets.QDialogButtonBox( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, - self) + self, + ) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) layout.addWidget(self.button_box) @@ -1011,8 +1055,10 @@ def fmts(self) -> Dict[str, Any]: try: value = widget.editor.value except Exception: - raise IOError(f"{fmt}-value {widget.editor.text} could " - "not be parsed to python!") + raise IOError( + f"{fmt}-value {widget.editor.text} could " + "not be parsed to python!" + ) else: ret[fmt] = value return ret @@ -1040,5 +1086,4 @@ def update_project(cls, project: Project, *fmts: str) -> None: dialog.activateWindow() dialog.exec_() if dialog.result() == QtWidgets.QDialog.Accepted: - project.update( - **dialog.fmts) + project.update(**dialog.fmts) diff --git a/psy_view/ds_widget.py b/psy_view/ds_widget.py index b85613c..d249cca 100644 --- a/psy_view/ds_widget.py +++ b/psy_view/ds_widget.py @@ -1,76 +1,59 @@ # -*- coding: utf-8 -*- """Dataset widget to display the contents of a dataset.""" -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only from __future__ import annotations -import os.path as osp +import contextlib import os - +import os.path as osp from typing import ( - List, TYPE_CHECKING, - Optional, - Union, - Dict, - Iterator, - Type, Any, Callable, + Dict, Hashable, + Iterator, + List, + Optional, Tuple, + Union, ) -import contextlib - +import psyplot.data as psyd import yaml -from PyQt5 import QtWidgets, QtGui +from matplotlib.animation import FuncAnimation +from psyplot.config.rcsetup import get_configdir +from psyplot_gui.common import DockMixin, PyErrorMessage +from psyplot_gui.common import get_icon as get_psy_icon +from psyplot_gui.content_widget import ( + DatasetTree, + DatasetTreeItem, + escape_html, +) +from PyQt5 import QtGui, QtWidgets from PyQt5.QtCore import Qt # pylint: disable=no-name-in-module + import psy_view.utils as utils -from psyplot_gui.content_widget import ( - DatasetTree, DatasetTreeItem, escape_html) -from psyplot_gui.common import ( - DockMixin, get_icon as get_psy_icon, PyErrorMessage) -import psyplot.data as psyd -from psy_view.rcsetup import rcParams from psy_view.plotmethods import ( - PlotMethodWidget, + LinePlotWidget, MapPlotWidget, Plot2DWidget, - LinePlotWidget, + PlotMethodWidget, ) -from psyplot.config.rcsetup import get_configdir - -from matplotlib.animation import FuncAnimation +from psy_view.rcsetup import rcParams if TYPE_CHECKING: - from xarray import DataArray, Dataset - from psyplot.project import PlotterInterface, Project - from psyplot.plotter import Plotter - from matplotlib.figure import Figure from matplotlib.backend_bases import MouseEvent + from matplotlib.figure import Figure + from psyplot.plotter import Plotter + from psyplot.project import PlotterInterface, Project from psyplot_gui.main import MainWindow + from xarray import DataArray, Dataset NOTSET = "__NOVARIABLEAVAILABLE" @@ -93,8 +76,12 @@ def get_dims_to_iterate(arr: DataArray) -> List[str]: The dimension strings """ base_var = next(arr.psy.iter_base_variables) - return [dim for dim, size in zip(base_var.dims, base_var.shape) - if size > 1 and arr[dim].ndim == 0] + return [ + dim + for dim, size in zip(base_var.dims, base_var.shape) + if size > 1 and arr[dim].ndim == 0 + ] + TOO_MANY_FIGURES_WARNING = """ Multiple figures are open but you specified only {} filenames: {}.
@@ -119,7 +106,7 @@ class DatasetWidget(QtWidgets.QSplitter): """A widget to control the visualization of the variables in a dataset""" #: The title of the widget - title: str = 'psy-view Plot Control' + title: str = "psy-view Plot Control" #: Display the dock widget at the right side of the GUI dock_position = Qt.RightDockWidgetArea @@ -141,7 +128,7 @@ class DatasetWidget(QtWidgets.QSplitter): _preset: Optional[Union[str, Dict]] = None #: Attributes to use in the dataset tree - ds_attr_columns: List[str] = ['long_name', 'dims', 'shape'] + ds_attr_columns: List[str] = ["long_name", "dims", "shape"] def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: """ @@ -167,13 +154,16 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: self.lbl_ds = QtWidgets.QLineEdit() self.open_box.addWidget(self.lbl_ds) self.btn_open = utils.add_pushbutton( - get_psy_icon('run_arrow.png'), lambda: self.set_dataset(), - "Select and open a netCDF dataset", self.open_box, icon=True) + get_psy_icon("run_arrow.png"), + lambda: self.set_dataset(), + "Select and open a netCDF dataset", + self.open_box, + icon=True, + ) self.open_widget = QtWidgets.QWidget() self.open_widget.setLayout(self.open_box) self.addWidget(self.open_widget) - # second row: dataset representation self.setup_ds_tree() if ds is not None: @@ -189,14 +179,20 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: # -- animate backwards button self.btn_animate_backward = utils.add_pushbutton( - "◀◀", lambda: self.animate_backward(), - "Animate the time dimension backwards", self.navigation_box) + "◀◀", + lambda: self.animate_backward(), + "Animate the time dimension backwards", + self.navigation_box, + ) self.btn_animate_backward.setCheckable(True) # -- go to previous button self.btn_prev = utils.add_pushbutton( - '◀', self.go_to_previous_step, - "Go to previous time step", self.navigation_box) + "◀", + self.go_to_previous_step, + "Go to previous time step", + self.navigation_box, + ) # -- dimension menu for animation self.combo_dims = QtWidgets.QComboBox() @@ -204,13 +200,19 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: # -- go to next button self.btn_next = utils.add_pushbutton( - '▶', self.go_to_next_step, - "Go to next time step", self.navigation_box) + "▶", + self.go_to_next_step, + "Go to next time step", + self.navigation_box, + ) # -- animate forward button self.btn_animate_forward = utils.add_pushbutton( - "▶▶", lambda: self.animate_forward(), - "Animate the time dimension", self.navigation_box) + "▶▶", + lambda: self.animate_forward(), + "Animate the time dimension", + self.navigation_box, + ) self.btn_animate_forward.setCheckable(True) # -- interval slider @@ -224,7 +226,7 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: self.navigation_box.addWidget(self.sl_interval) # -- interval label - self.lbl_interval = QtWidgets.QLabel('500 ms') + self.lbl_interval = QtWidgets.QLabel("500 ms") self.navigation_box.addWidget(self.lbl_interval) # --- export/import menus @@ -232,7 +234,7 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: # -- Export button self.btn_export = QtWidgets.QToolButton() - self.btn_export.setText('Export') + self.btn_export.setText("Export") self.btn_export.setPopupMode(QtWidgets.QToolButton.InstantPopup) self.btn_export.setMenu(self.setup_export_menu()) self.btn_export.setEnabled(False) @@ -244,28 +246,34 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: hbox = QtWidgets.QHBoxLayout(self.frm_preset) self.btn_preset = QtWidgets.QToolButton() - self.btn_preset.setText('Preset') + self.btn_preset.setText("Preset") self.btn_preset.setPopupMode(QtWidgets.QToolButton.InstantPopup) self.btn_preset.setMenu(self.setup_preset_menu()) hbox.addWidget(self.btn_preset) # --- presets label - self.lbl_preset = QtWidgets.QLabel('') + self.lbl_preset = QtWidgets.QLabel("") self.lbl_preset.setVisible(False) hbox.addWidget(self.lbl_preset) # --- unset preset button self.btn_unset_preset = utils.add_pushbutton( - get_psy_icon('invalid.png'), self.unset_preset, - "Unset the current preset", hbox, icon=True) + get_psy_icon("invalid.png"), + self.unset_preset, + "Unset the current preset", + hbox, + icon=True, + ) self.btn_unset_preset.setVisible(False) self.export_box.addWidget(self.frm_preset) self.btn_reload = utils.add_pushbutton( - get_psy_icon("refresh.png"), self.reload, + get_psy_icon("refresh.png"), + self.reload, "Close all open datasets and recreate the plots", - self.export_box, icon=True + self.export_box, + icon=True, ) self.export_box.addStretch(0) @@ -278,7 +286,7 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: # fourth row: array selector - self.array_frame = QtWidgets.QGroupBox('Current plot') + self.array_frame = QtWidgets.QGroupBox("Current plot") hbox = QtWidgets.QHBoxLayout() self.combo_array = QtWidgets.QComboBox() @@ -288,12 +296,20 @@ def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None: hbox.addWidget(self.combo_array) self.btn_add = utils.add_pushbutton( - QtGui.QIcon(get_psy_icon('plus')), self.new_plot, - "Create a new plot", hbox, icon=True) + QtGui.QIcon(get_psy_icon("plus")), + self.new_plot, + "Create a new plot", + hbox, + icon=True, + ) self.btn_add.setEnabled(ds is not None) self.btn_del = utils.add_pushbutton( - QtGui.QIcon(get_psy_icon('minus')), self.close_current_plot, - "Remove the current plot", hbox, icon=True) + QtGui.QIcon(get_psy_icon("minus")), + self.close_current_plot, + "Remove the current plot", + hbox, + icon=True, + ) self.btn_del.setEnabled(False) hbox.addWidget(self.btn_add) @@ -330,6 +346,8 @@ def reload(self) -> None: import psyplot.project as psy sp = self._sp + if sp is None: + return fname = sp.dsnames_map[self.ds.psy.num] # type: ignore project = sp.save_project() sp.close(True, True, True) @@ -349,7 +367,7 @@ def setup_ds_tree(self) -> None: """Setup the number of columns and the header of the dataset tree.""" self.ds_tree = tree = QtWidgets.QTreeWidget() tree.setColumnCount(len(self.ds_attr_columns) + 1) - tree.setHeaderLabels([''] + self.ds_attr_columns) + tree.setHeaderLabels([""] + self.ds_attr_columns) def showEvent(self, event): ret = super().showEvent(event) @@ -384,7 +402,7 @@ def arr_name(self) -> Optional[str]: if not self.combo_array.count(): return None else: - return self.combo_array.currentText().split(':')[0] + return self.combo_array.currentText().split(":")[0] def change_ds(self, ds_item: DatasetTreeItem) -> None: """Change the current dataset to another one. @@ -438,11 +456,13 @@ def _open_dataset(self) -> Optional[Dataset]: if not current or not osp.exists(current): current = os.getcwd() fname, ok = QtWidgets.QFileDialog.getOpenFileName( - self, 'Open dataset', current, - 'NetCDF files (*.nc *.nc4);;' - 'Shape files (*.shp);;' - 'All files (*)' - ) + self, + "Open dataset", + current, + "NetCDF files (*.nc *.nc4);;" + "Shape files (*.shp);;" + "All files (*)", + ) if not ok: return None ds = psyd.open_dataset(fname) @@ -487,8 +507,8 @@ def _add_ds_item(self, ds: Dataset) -> None: self.lbl_ds.setText(fname) fname = osp.basename(fname) else: - self.lbl_ds.setText('') - fname = '' + self.lbl_ds.setText("") + fname = "" ds_item.setText(0, fname) tree.addTopLevelItem(ds_item) @@ -500,7 +520,6 @@ def _add_ds_item(self, ds: Dataset) -> None: # make sure we do not loose track of open datasets self._ds_nums[ds.psy.num] = ds - @property def open_datasets(self) -> Dict[int, Dataset]: """Get a mapping from path to dataset number of the open datasets.""" @@ -522,7 +541,8 @@ def ds_item(self) -> Optional[DatasetTreeItem]: return None def expand_current_variable( - self, variable: Optional[Union[Any, Hashable]] = None) -> None: + self, variable: Optional[Union[Any, Hashable]] = None + ) -> None: """Expand the item in the dataset tree of variable. Parameters @@ -537,8 +557,9 @@ def expand_current_variable( tree.expandItem(top.child(0)) if variable is None: variable: str = self.variable # type: ignore - for var_item in map(top.child(0).child, - range(top.child(0).childCount())): + for var_item in map( + top.child(0).child, range(top.child(0).childCount()) + ): if var_item.text(0) == variable: tree.expandItem(var_item) else: @@ -546,7 +567,7 @@ def expand_current_variable( def setup_variable_buttons(self, ncols: int = 4) -> None: """Setup the variable buttons for the current dataset.""" - variable_frame = QtWidgets.QGroupBox('Variables') + variable_frame = QtWidgets.QGroupBox("Variables") self.variable_scroll.setWidget(variable_frame) self.variable_frame = variable_frame @@ -556,10 +577,10 @@ def setup_variable_buttons(self, ncols: int = 4) -> None: ds = self.ds if ds is not None: - for i, v in enumerate(ds): btn = utils.add_pushbutton( - v, self._draw_variable(v), f"Visualize variable {v}") + v, self._draw_variable(v), f"Visualize variable {v}" + ) btn.setCheckable(True) self.variable_buttons[v] = btn self.variable_layout.addWidget(btn, i // ncols, i % ncols) @@ -568,7 +589,8 @@ def setup_variable_buttons(self, ncols: int = 4) -> None: rows = len(ds) // ncols minrows = max(1, min(3, rows)) self.variable_scroll.setMinimumHeight( - (minrows + 2) * btn.sizeHint().height()) + (minrows + 2) * btn.sizeHint().height() + ) def load_variable_desc(self, item: QtWidgets.QTreeWidgetItem) -> None: """Load the description of the variable of a given tree item. @@ -583,8 +605,13 @@ def load_variable_desc(self, item: QtWidgets.QTreeWidgetItem) -> None: tree = self.ds_tree - if parent is tree or parent is None or not ( - DatasetTree.is_variable(item) or DatasetTree.is_coord(item)): + if ( + parent is tree + or parent is None + or not ( + DatasetTree.is_variable(item) or DatasetTree.is_coord(item) + ) + ): return if tree.isColumnHidden(1): @@ -598,14 +625,15 @@ def load_variable_desc(self, item: QtWidgets.QTreeWidgetItem) -> None: if ds is None: return desc = escape_html(str(ds.variables[item.text(0)])) - item.setToolTip(0, '
' + desc + '
') + item.setToolTip(0, "
" + desc + "
") def clear_table(self) -> None: """Clear the table that shows the available dimensions.""" self.dimension_table.clear() self.dimension_table.setColumnCount(5) self.dimension_table.setHorizontalHeaderLabels( - ['Type', 'First', 'Current', 'Last', 'Units']) + ["Type", "First", "Current", "Last", "Units"] + ) self.dimension_table.setRowCount(0) def addLayout(self, layout: QtWidgets.QLayout) -> QtWidgets.QWidget: @@ -643,11 +671,11 @@ def animate_backward(self) -> None: """Start the current animation in backward direction, or stop it.""" if self._animating: self.stop_animation() - self.btn_animate_backward.setText('◀◀') + self.btn_animate_backward.setText("◀◀") self.enable_navigation() else: self._animate_forward = False - self.btn_animate_backward.setText('■') + self.btn_animate_backward.setText("■") self.disable_navigation(self.btn_animate_backward) self.start_animation() @@ -655,22 +683,20 @@ def animate_forward(self, nframes=None): """Start the current animation in forward direction, or stop it.""" if self._animating: self.stop_animation() - self.btn_animate_forward.setText('▶▶') + self.btn_animate_forward.setText("▶▶") self.enable_navigation() else: self._animate_forward = True - self.btn_animate_forward.setText('■') + self.btn_animate_forward.setText("■") self.disable_navigation(self.btn_animate_forward) self.start_animation(nframes) def setup_plot_tabs(self) -> None: """Setup the tabs of the various plot methods.""" - self.plot_tabs.addTab(MapPlotWidget(self.get_sp, self.ds), - 'mapplot') - self.plot_tabs.addTab(Plot2DWidget(self.get_sp, self.ds), - 'plot2d') + self.plot_tabs.addTab(MapPlotWidget(self.get_sp, self.ds), "mapplot") + self.plot_tabs.addTab(Plot2DWidget(self.get_sp, self.ds), "plot2d") lineplot_widget = LinePlotWidget(self.get_sp, self.ds) - self.plot_tabs.addTab(lineplot_widget, 'lineplot') + self.plot_tabs.addTab(lineplot_widget, "lineplot") for w in map(self.plot_tabs.widget, range(self.plot_tabs.count())): w.replot.connect(self.replot) @@ -713,8 +739,8 @@ def reset(self, plotmethod: str) -> None: self.refresh() def disable_navigation( - self, but: Optional[QtWidgets.QPushButton] = None - ) -> None: + self, but: Optional[QtWidgets.QPushButton] = None + ) -> None: """Disable the navigation buttons. This function disables all navigation buttons but the one you specify. @@ -724,16 +750,18 @@ def disable_navigation( but: PyQt5.QtWidgets.QPushButton If not None, this button is not disabled. """ - for item in map(self.navigation_box.itemAt, - range(self.navigation_box.count())): + for item in map( + self.navigation_box.itemAt, range(self.navigation_box.count()) + ): w = item.widget() if w is not but and w is not self.sl_interval: w.setEnabled(False) def enable_navigation(self) -> None: """Enable all navigation buttons again.""" - for item in map(self.navigation_box.itemAt, - range(self.navigation_box.count())): + for item in map( + self.navigation_box.itemAt, range(self.navigation_box.count()) + ): w = item.widget() w.setEnabled(True) @@ -768,9 +796,13 @@ def start_animation(self, nframes: Optional[int] = None): if self.sp is not None: if self.animation is None or self.animation.event_source is None: self.animation = FuncAnimation( - self.fig, self.update_dims, frames=self.animation_frames(), - init_func=self.sp.draw, interval=self.sl_interval.value(), - repeat=False) + self.fig, + self.update_dims, + frames=self.animation_frames(), + init_func=self.sp.draw, + interval=self.sl_interval.value(), + repeat=False, + ) # HACK: Make sure that the animation starts although the figure # is already shown self.animation._draw_frame(next(self.animation_frames())) @@ -779,7 +811,7 @@ def start_animation(self, nframes: Optional[int] = None): def reset_timer_interval(self, value: int) -> None: """Change the interval of the timer.""" - self.lbl_interval.setText('%i ms' % value) + self.lbl_interval.setText("%i ms" % value) if self.animation is None or self.animation.event_source is None: pass else: @@ -791,8 +823,10 @@ def reset_timer_interval(self, value: int) -> None: def stop_animation(self) -> None: """Stop the current animation.""" self._animating = False - if (self.animation is not None and - self.animation.event_source is not None): + if ( + self.animation is not None + and self.animation.event_source is not None + ): self.animation.event_source.stop() self.plot_tabs.setEnabled(True) self.enable_variables() @@ -800,8 +834,11 @@ def stop_animation(self) -> None: def animation_frames(self) -> Iterator[Dict[str, int]]: """Get the animation frames for the :attr:`combo_dims` dimension.""" - while self._animating and self._animation_frames is None or \ - self._animation_frames: + while ( + self._animating + and self._animation_frames is None + or self._animation_frames + ): if self._animation_frames is not None and not self._init_step: self._animation_frames -= 1 dim = self.combo_dims.currentText() @@ -824,9 +861,11 @@ def update_dims(self, dims: Dict[str, Any]): def _load_preset(self) -> None: """Open a file dialog and load the selected preset.""" fname, ok = QtWidgets.QFileDialog.getOpenFileName( - self, 'Load preset', osp.join(get_configdir(), 'presets'), - 'YAML files (*.yml *.yaml);;' - 'All files (*)') + self, + "Load preset", + osp.join(get_configdir(), "presets"), + "YAML files (*.yml *.yaml);;" "All files (*)", + ) if ok: self.load_preset(fname) @@ -852,17 +891,21 @@ def preset(self) -> Dict[str, Any]: if self._preset is None: return {} import psyplot.project as psy + preset = self._preset try: preset = psy.Project._load_preset(preset) except yaml.constructor.ConstructorError: answer = QtWidgets.QMessageBox.question( - self, "Can I trust this?", + self, + "Can I trust this?", f"Failed to load the preset at {preset} in safe mode. Can we " - "trust this preset and load it in unsafe mode?") + "trust this preset and load it in unsafe mode?", + ) if answer == QtWidgets.QMessageBox.Yes: - psyd.rcParams['presets.trusted'].append( - psy.Project._resolve_preset_path(preset)) + psyd.rcParams["presets.trusted"].append( + psy.Project._resolve_preset_path(preset) + ) preset = psy.Project._load_preset(preset) else: preset = {} @@ -872,7 +915,6 @@ def preset(self) -> Dict[str, Any]: def preset(self, value: Optional[Union[str, Dict[str, Any]]]): self._preset = value - def unset_preset(self) -> None: """Unset the current preset and do not use it anymore.""" self.preset = None # type: ignore @@ -881,12 +923,13 @@ def unset_preset(self) -> None: def maybe_show_preset(self) -> None: """Show the name of the current preset if one is selected.""" if self._preset is not None and isinstance(self._preset, str): - self.lbl_preset.setText('' + - osp.basename(osp.splitext(self._preset)[0]) + '') + self.lbl_preset.setText( + "" + osp.basename(osp.splitext(self._preset)[0]) + "" + ) self.lbl_preset.setVisible(True) self.btn_unset_preset.setVisible(True) elif self._preset is not None: - self.lbl_preset.setText('custom') + self.lbl_preset.setText("custom") self.lbl_preset.setVisible(True) self.btn_unset_preset.setVisible(True) else: @@ -916,9 +959,11 @@ def _save_preset(self, save_func: Callable[[str], Any]) -> None: path as an argument """ fname, ok = QtWidgets.QFileDialog.getSaveFileName( - self, 'Save preset', osp.join(get_configdir(), 'presets'), - 'YAML files (*.yml *.yaml);;' - 'All files (*)') + self, + "Save preset", + osp.join(get_configdir(), "presets"), + "YAML files (*.yml *.yaml);;" "All files (*)", + ) if not ok: return None save_func(fname) @@ -929,18 +974,25 @@ def setup_preset_menu(self) -> QtWidgets.QMenu: self._save_preset_actions = [] self._load_preset_action = menu.addAction( - "Load preset", self._load_preset) + "Load preset", self._load_preset + ) self._unset_preset_action = menu.addAction( - "Unset preset", self.unset_preset) + "Unset preset", self.unset_preset + ) menu.addSeparator() self._save_preset_actions.append( - menu.addAction('Save format of current plot as preset', - self.save_current_preset)) + menu.addAction( + "Save format of current plot as preset", + self.save_current_preset, + ) + ) self._save_preset_actions.append( - menu.addAction('Save format of all plots as preset', - self.save_full_preset)) + menu.addAction( + "Save format of all plots as preset", self.save_full_preset + ) + ) for action in self._save_preset_actions: action.setEnabled(False) @@ -950,13 +1002,14 @@ def setup_preset_menu(self) -> QtWidgets.QMenu: def setup_export_menu(self) -> QtWidgets.QMenu: """Set up the menu to export the current plot.""" self.export_menu = menu = QtWidgets.QMenu() - menu.addAction('image (PDF, PNG, etc.)', self.export_image) - menu.addAction('all images (PDF, PNG, etc.)', self.export_all_images) - menu.addAction('animation (GIF, MP4, etc.', self.export_animation) - menu.addAction('psyplot project (.pkl file)', self.export_project) - menu.addAction('psyplot project with data', - self.export_project_with_data) - py_action = menu.addAction('python script (.py)', self.export_python) + menu.addAction("image (PDF, PNG, etc.)", self.export_image) + menu.addAction("all images (PDF, PNG, etc.)", self.export_all_images) + menu.addAction("animation (GIF, MP4, etc.", self.export_animation) + menu.addAction("psyplot project (.pkl file)", self.export_project) + menu.addAction( + "psyplot project with data", self.export_project_with_data + ) + py_action = menu.addAction("python script (.py)", self.export_python) py_action.setEnabled(False) # psyplot does not yet export to python return menu @@ -964,36 +1017,46 @@ def export_image(self) -> None: """Ask for a filename and export the current plot to a file.""" if self.sp is not None: fname, ok = QtWidgets.QFileDialog.getSaveFileName( - self, "Export image", os.getcwd(), - "Images (*.png *.pdf *.jpg *.svg)") + self, + "Export image", + os.getcwd(), + "Images (*.png *.pdf *.jpg *.svg)", + ) if ok: - self.sp.export(fname, **rcParams['savefig_kws']) + self.sp.export(fname, **rcParams["savefig_kws"]) def export_all_images(self) -> None: """Ask for a filename and export all plots to one (or more) files.""" fname, ok = QtWidgets.QFileDialog.getSaveFileName( - self, "Export image", os.getcwd(), - "Images (*.png *.pdf *.jpg *.svg)") + self, + "Export image", + os.getcwd(), + "Images (*.png *.pdf *.jpg *.svg)", + ) if ok and self._sp: # test filenames - if not osp.splitext(fname)[-1].lower() == '.pdf': + if not osp.splitext(fname)[-1].lower() == ".pdf": fnames = [ sp.format_string(fname, False, i) - for i, sp in enumerate(self._sp.figs.values())] + for i, sp in enumerate(self._sp.figs.values()) + ] if len(fnames) != len(set(fnames)): answer = QtWidgets.QMessageBox.question( - self, "Too many figures", + self, + "Too many figures", TOO_MANY_FIGURES_WARNING.format( - len(set(fnames)), ', '.join(set(fnames)))) + len(set(fnames)), ", ".join(set(fnames)) + ), + ) if answer == QtWidgets.QMessageBox.No: return - self._sp.export(fname, **rcParams['savefig_kws']) + self._sp.export(fname, **rcParams["savefig_kws"]) def export_animation(self) -> None: """Ask for a filename and export the animation.""" fname, ok = QtWidgets.QFileDialog.getSaveFileName( - self, "Export animation", os.getcwd(), - "Movie (*.mp4 *.mov *.gif)") + self, "Export animation", os.getcwd(), "Movie (*.mp4 *.mov *.gif)" + ) if ok: dim = self.combo_dims.currentText() nframes: int = self.ds.dims[dim] # type: ignore @@ -1002,8 +1065,10 @@ def export_animation(self) -> None: self.animate_forward(nframes) if self.animation is not None: self.animation.save( - fname, **rcParams['animations.export_kws'], - fps=round(1000. / self.sl_interval.value())) + fname, + **rcParams["animations.export_kws"], + fps=round(1000.0 / self.sl_interval.value()), + ) self.animate_forward() self.animation = None @@ -1011,8 +1076,8 @@ def export_project(self) -> None: """Ask for a filename and export the psyplot project as .pkl file.""" if self.sp is not None: fname, ok = QtWidgets.QFileDialog.getSaveFileName( - self, "Export project", os.getcwd(), - "Psyplot projects (*.pkl)") + self, "Export project", os.getcwd(), "Psyplot projects (*.pkl)" + ) if ok: self.sp.save_project(fname) @@ -1023,8 +1088,8 @@ def export_project_with_data(self) -> None: """ if self.sp is not None: fname, ok = QtWidgets.QFileDialog.getSaveFileName( - self, "Export project", os.getcwd(), - "Psyplot projects (*.pkl)") + self, "Export project", os.getcwd(), "Psyplot projects (*.pkl)" + ) if ok: self.sp.save_project(fname, ds_description={"ds"}) @@ -1105,19 +1170,23 @@ def plot(self) -> PlotterInterface: return getattr(self.ds.psy.plot, self.plotmethod) else: raise ValueError( - "No dataset has yet been selected, so no plot method!") + "No dataset has yet been selected, so no plot method!" + ) @property def plot_options(self) -> Dict[str, Any]: """Get further keyword arguments for the :attr:`plot` function.""" if self.ds is not None: ret: Dict[str, Any] = self.plotmethod_widget.get_fmts( # type: ignore - self.ds.psy[self.variable], True) + self.ds.psy[self.variable], True + ) preset = self.preset if preset: import psyplot.project as psy + preset = psy.Project.extract_fmts_from_preset( - preset, self.plotmethod) + preset, self.plotmethod + ) ret.update(dict(preset)) return ret return {} @@ -1129,8 +1198,14 @@ def plotmethod(self) -> str: @plotmethod.setter def plotmethod(self, label: str): - i = next((i for i in range(self.plot_tabs.count()) - if self.plot_tabs.tabText(i) == label), None) + i = next( + ( + i + for i in range(self.plot_tabs.count()) + if self.plot_tabs.tabText(i) == label + ), + None, + ) if i is not None: self.plot_tabs.setCurrentIndex(i) @@ -1143,15 +1218,25 @@ def plotmethods(self) -> List[str]: def plotmethod_widget(self) -> PlotMethodWidget: """Get widget of the current plotmethod.""" label = self.plotmethod - i = next((i for i in range(self.plot_tabs.count()) - if self.plot_tabs.tabText(i) == label), None) + i = next( + ( + i + for i in range(self.plot_tabs.count()) + if self.plot_tabs.tabText(i) == label + ), + None, + ) return self.plot_tabs.widget(i) @property def plotmethod_widgets(self) -> Dict[str, PlotMethodWidget]: """Get a list of available plotmethod widgets.""" - return dict(zip(self.plotmethods, map(self.plot_tabs.widget, - range(self.plot_tabs.count())))) + return dict( + zip( + self.plotmethods, + map(self.plot_tabs.widget, range(self.plot_tabs.count())), + ) + ) _sp = None @@ -1162,8 +1247,7 @@ def get_sp(self) -> Optional[Project]: return self.filter_sp(sp) def filter_sp(self, sp: Project, ds_only: bool = False) -> Project: - """Filter the psyplot project to only include the arrays of :attr:`ds` - """ + """Filter the psyplot project to only include the arrays of :attr:`ds`""" if self._new_plot: return None if self.ds is None: @@ -1171,8 +1255,8 @@ def filter_sp(self, sp: Project, ds_only: bool = False) -> Project: num = self.ds.psy.num ret = sp[:0] for i in range(len(sp)): - if list(sp[i:i+1].datasets) == [num]: - ret += sp[i:i+1] + if list(sp[i : i + 1].datasets) == [num]: + ret += sp[i : i + 1] if ds_only: return ret arr_name = self.arr_name @@ -1192,8 +1276,11 @@ def new_plot(self) -> None: """ if self.ds is not None: name, ok = QtWidgets.QInputDialog.getItem( - self, 'New plot', 'Select a variable', - self.plotmethod_widget.valid_variables(self.ds)) + self, + "New plot", + "Select a variable", + self.plotmethod_widget.valid_variables(self.ds), + ) if not ok: return with self.silence_variable_buttons(): @@ -1218,8 +1305,9 @@ def sp(self) -> Optional[Project]: @sp.setter def sp(self, sp: Optional[Project]): - if sp is None and (not self._sp or not getattr( - self._sp, self.plotmethod)): + if sp is None and ( + not self._sp or not getattr(self._sp, self.plotmethod) + ): pass else: # first remove the current arrays @@ -1278,11 +1366,14 @@ def make_plot(self) -> None: if plotmethod not in plotmethods: if not plotmethods: QtWidgets.QMessageBox.critical( - self, "Visualization impossible", - f"Found no plotmethod for variable {self.variable}") + self, + "Visualization impossible", + f"Found no plotmethod for variable {self.variable}", + ) return plotmethod, ok = QtWidgets.QInputDialog.getItem( - self, "Choose a plot method", "Plot method:", plotmethods) + self, "Choose a plot method", "Plot method:", plotmethods + ) if not ok: return self.plotmethod = plotmethod @@ -1311,7 +1402,8 @@ def make_plot(self) -> None: self.sp = sp = self.plot(name=self.variable, **self.plot_options) self._preset = None cid = sp.plotters[0].ax.figure.canvas.mpl_connect( - 'button_press_event', self.display_line) + "button_press_event", self.display_line + ) self.cids[self.plotmethod] = cid self.show_fig(sp) descr = sp[0].psy._short_info() @@ -1336,31 +1428,37 @@ def display_line(self, event: MouseEvent) -> None: return else: sl = None - for widget in map(self.plot_tabs.widget, - range(self.plot_tabs.count())): + for widget in map( + self.plot_tabs.widget, range(self.plot_tabs.count()) + ): if widget.sp and event.inaxes == widget.plotter.ax: sl = widget.get_slice(event.xdata, event.ydata) break variable = widget.data.name raw_data = widget.data.psy.base.psy[variable] - if (sl is None or widget.plotmethod not in ['mapplot', 'plot2d'] or - raw_data.ndim == 2 or - widget.plotter.ax.figure.canvas.manager.toolbar.mode != ''): + if ( + sl is None + or widget.plotmethod not in ["mapplot", "plot2d"] + or raw_data.ndim == 2 + or widget.plotter.ax.figure.canvas.manager.toolbar.mode != "" + ): return # check if the mappable contains the event if not self.plotter.plot.mappable.contains(event)[0] and ( - not hasattr(self.plotter.plot, '_wrapped_plot') or - not self.plotter.plot._wrapped_plot.contains(event)[0]): + not hasattr(self.plotter.plot, "_wrapped_plot") + or not self.plotter.plot._wrapped_plot.contains(event)[0] + ): return current_pm = self.plotmethod - self.plotmethod = 'lineplot' + self.plotmethod = "lineplot" linewidget = self.plotmethod_widget xdim = linewidget.xdim if xdim is None: xdim = self.combo_dims.currentText() - if not linewidget.sp or (linewidget.xdim and - linewidget.xdim not in raw_data.dims): + if not linewidget.sp or ( + linewidget.xdim and linewidget.xdim not in raw_data.dims + ): with self.silence_variable_buttons(): for v, btn in self.variable_buttons.items(): btn.setChecked(v == variable) @@ -1371,7 +1469,6 @@ def display_line(self, event: MouseEvent) -> None: linewidget.add_line(variable, **sl) self.plotmethod = current_pm - def close_sp(self) -> None: """Close the current subproject.""" sp = self.sp @@ -1442,7 +1539,8 @@ def reset_combo_array(self) -> None: else: idx_arr = 0 self.ds = list( - all_arrays[idx_arr:idx_arr+1].datasets.values())[0] + all_arrays[idx_arr : idx_arr + 1].datasets.values() + )[0] if self.ds is not current_ds: with self.block_tree(): self.expand_ds_item(self.ds_item) @@ -1477,7 +1575,6 @@ def refresh(self, reset_combo: bool = True) -> None: self.btn_del.setEnabled(False) self.btn_export.setEnabled(False) - # refresh variable buttons with self.silence_variable_buttons(): for v, btn in self.variable_buttons.items(): @@ -1498,7 +1595,7 @@ def refresh(self, reset_combo: bool = True) -> None: if self.sp: data = self.data - ds_data = self.ds[self.variable] + ds_data = self.ds.psy[self.variable] with self.silence_variable_buttons(): self.variable_buttons[self.variable].setChecked(True) @@ -1508,18 +1605,21 @@ def refresh(self, reset_combo: bool = True) -> None: table.setVerticalHeaderLabels(ds_data.dims) # set time, z, x, y info - for c in 'XYTZ': + for c in "XYTZ": cname = ds_data.psy.get_dim(c) if cname and cname in dims: table.setItem( - dims.index(cname), 0, QtWidgets.QTableWidgetItem(c)) + dims.index(cname), 0, QtWidgets.QTableWidgetItem(c) + ) for i, dim in enumerate(dims): coord = self.ds[dim] - if 'units' in coord.attrs: + if "units" in coord.attrs: table.setItem( - i, 4, QtWidgets.QTableWidgetItem( - str(coord.attrs['units']))) + i, + 4, + QtWidgets.QTableWidgetItem(str(coord.attrs["units"])), + ) try: coord = list(map("{:1.4f}".format, coord.values)) # type: ignore except (ValueError, TypeError): @@ -1531,22 +1631,21 @@ def refresh(self, reset_combo: bool = True) -> None: coord = [t.isoformat() for t in coord] # type: ignore first = coord[0] last = coord[-1] - table.setItem( - i, 1, QtWidgets.QTableWidgetItem(first)) - table.setItem( - i, 3, QtWidgets.QTableWidgetItem(last)) + table.setItem(i, 1, QtWidgets.QTableWidgetItem(first)) + table.setItem(i, 3, QtWidgets.QTableWidgetItem(last)) current = data.psy.idims.get(dim) if current is not None and isinstance(current, int): table.setCellWidget( - i, 2, self.new_dimension_button(dim, coord[current])) + i, 2, self.new_dimension_button(dim, coord[current]) + ) # update animation checkbox dims_to_animate = get_dims_to_iterate(data) - current_dims_to_animate = list(map( - self.combo_dims.itemText, - range(self.combo_dims.count()))) + current_dims_to_animate = list( + map(self.combo_dims.itemText, range(self.combo_dims.count())) + ) if dims_to_animate != current_dims_to_animate: self.combo_dims.clear() self.combo_dims.addItems(dims_to_animate) @@ -1560,16 +1659,20 @@ def refresh(self, reset_combo: bool = True) -> None: if DatasetTree.is_variable(child): plots_item = ds_item.get_plots_item(child) ds_item.refresh_plots_item( - plots_item, child.text(0), self._sp, self.sp) + plots_item, child.text(0), self._sp, self.sp + ) def new_dimension_button( - self, dim: Hashable, label: Any) -> utils.QRightPushButton: + self, dim: Hashable, label: Any + ) -> utils.QRightPushButton: """Generate a new button to increase of decrease a dimension.""" btn = utils.QRightPushButton(label) btn.clicked.connect(self.increase_dim(str(dim))) btn.rightclicked.connect(self.increase_dim(str(dim), -1)) - btn.setToolTip(f"Increase dimension {dim} with left-click, and " - "decrease with right-click.") + btn.setToolTip( + f"Increase dimension {dim} with left-click, and " + "decrease with right-click." + ) return btn def update_project(self, *args, **kwargs) -> None: @@ -1589,12 +1692,16 @@ def increase_dim(self, dim: str, increase: int = 1) -> Callable[[], None]: increase: int The number of steps to increase (or decrease) the given `dim`. """ + def update(): i = self.data.psy.idims[dim] - self.data.psy.update(dims={dim: (i+increase) % self.ds.dims[dim]}) + self.data.psy.update( + dims={dim: (i + increase) % self.ds.dims[dim]} + ) if self.data.psy.plotter is None: self.sp.update(replot=True) self.refresh() + return update @@ -1617,19 +1724,21 @@ class DatasetWidgetPlugin(DatasetWidget, DockMixin): """ #: The title of the widget - title = 'psy-view Dataset viewer' + title = "psy-view Dataset viewer" #: Display the dock widget at the right side of the GUI dock_position = Qt.RightDockWidgetArea def __init__(self, *args, **kwargs): import psyplot.project as psy + super().__init__(*args, **kwargs) psy.Project.oncpchange.connect(self.oncpchange) @property # type: ignore def _sp(self) -> Project: # type: ignore import psyplot.project as psy + return psy.gcp(True) @_sp.setter @@ -1647,7 +1756,6 @@ def sp(self, sp: Optional[Project]): if sp is None or not current: return elif getattr(current, self.plotmethod, []): - if len(current) == 1 and len(sp) == 1: pass # first remove the current arrays @@ -1685,10 +1793,12 @@ def reload(self) -> None: if not all(self._sp.dsnames_map.values()): # we have datasets that only exist in memory, so better ask answer = QtWidgets.QMessageBox.question( - self, "Shall I close this?", + self, + "Shall I close this?", "Reloading the data closes all open plots. Any data in the memory " "is lost and open files are reloaded from disk! " - "Shall I really continue?") + "Shall I really continue?", + ) if answer != QtWidgets.QMessageBox.Yes: return @@ -1722,6 +1832,7 @@ def oncpchange(self, sp: Optional[Project]) -> None: def show_fig(self, sp: Optional[Project]) -> None: """Show the figure of the the current subproject.""" from psyplot_gui.main import mainwindow + super().show_fig(sp) if mainwindow.figures and sp: try: @@ -1738,11 +1849,14 @@ def setup_ds_tree(self) -> None: """ self.ds_tree = tree = DatasetTree() tree.setColumnCount(len(self.ds_attr_columns) + 1) - tree.setHeaderLabels([''] + self.ds_attr_columns) + tree.setHeaderLabels([""] + self.ds_attr_columns) def position_dock(self, main: MainWindow, *args, **kwargs) -> None: height = main.help_explorer.dock.size().height() main.splitDockWidget(main.help_explorer.dock, self.dock, Qt.Vertical) - if hasattr(main, 'resizeDocks'): # qt >= 5.6 - main.resizeDocks([main.help_explorer.dock, self.dock], - [height // 2, height // 2], Qt.Vertical) + if hasattr(main, "resizeDocks"): # qt >= 5.6 + main.resizeDocks( + [main.help_explorer.dock, self.dock], + [height // 2, height // 2], + Qt.Vertical, + ) diff --git a/psy_view/icons/color_settings.png b/psy_view/icons/color_settings.png index b986fca..c5950ac 100644 Binary files a/psy_view/icons/color_settings.png and b/psy_view/icons/color_settings.png differ diff --git a/psy_view/icons/color_settings.png.license b/psy_view/icons/color_settings.png.license new file mode 100644 index 0000000..eaac5c9 --- /dev/null +++ b/psy_view/icons/color_settings.png.license @@ -0,0 +1,4 @@ +SPDX-FileCopyrightText: 2024 Helmholtz-Zentrum hereon GmbH +SPDX-FileCopyrightText: 2024 Fonticons, Inc. (https://fontawesome.com) + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/psy_view/icons/color_settings.svg b/psy_view/icons/color_settings.svg new file mode 100644 index 0000000..376af47 --- /dev/null +++ b/psy_view/icons/color_settings.svg @@ -0,0 +1 @@ + diff --git a/psy_view/icons/color_settings.svg.license b/psy_view/icons/color_settings.svg.license new file mode 100644 index 0000000..23f2891 --- /dev/null +++ b/psy_view/icons/color_settings.svg.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2024 Fonticons, Inc. (https://fontawesome.com) + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/psy_view/icons/proj_settings.png b/psy_view/icons/proj_settings.png index ef5af74..86838e1 100644 Binary files a/psy_view/icons/proj_settings.png and b/psy_view/icons/proj_settings.png differ diff --git a/psy_view/icons/proj_settings.png.license b/psy_view/icons/proj_settings.png.license new file mode 100644 index 0000000..eaac5c9 --- /dev/null +++ b/psy_view/icons/proj_settings.png.license @@ -0,0 +1,4 @@ +SPDX-FileCopyrightText: 2024 Helmholtz-Zentrum hereon GmbH +SPDX-FileCopyrightText: 2024 Fonticons, Inc. (https://fontawesome.com) + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/psy_view/icons/proj_settings.svg b/psy_view/icons/proj_settings.svg new file mode 100644 index 0000000..1502b79 --- /dev/null +++ b/psy_view/icons/proj_settings.svg @@ -0,0 +1 @@ + diff --git a/psy_view/icons/proj_settings.svg.license b/psy_view/icons/proj_settings.svg.license new file mode 100644 index 0000000..23f2891 --- /dev/null +++ b/psy_view/icons/proj_settings.svg.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2024 Fonticons, Inc. (https://fontawesome.com) + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/psy_view/plotmethods.py b/psy_view/plotmethods.py index 97c1eb9..bf63441 100644 --- a/psy_view/plotmethods.py +++ b/psy_view/plotmethods.py @@ -4,72 +4,52 @@ lineplot plotmethods. """ -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only from __future__ import annotations -import os.path as osp +import contextlib +import dataclasses +import textwrap +from enum import Enum +from functools import partial +from itertools import chain, cycle from typing import ( TYPE_CHECKING, - ClassVar, + Any, Callable, - Optional, - Union, - List, - Hashable, + ClassVar, Dict, - Any, - Tuple, + Hashable, Iterator, - TypeVar, + List, + Optional, + Tuple, Type, + TypeVar, + Union, ) -from enum import Enum - -from functools import partial -from itertools import chain, cycle -import contextlib -import textwrap - -import dataclasses +import matplotlib.colors as mcol +import psy_simple.widgets.colors as pswc +import psyplot.data as psyd import xarray as xr from psyplot.utils import unique_everseen +from psyplot_gui.common import get_icon as get_psy_icon +from PyQt5 import QtCore, QtGui, QtWidgets -from PyQt5 import QtWidgets, QtCore, QtGui import psy_view.dialogs as dialogs import psy_view.utils as utils from psy_view.rcsetup import rcParams -from psyplot_gui.common import get_icon as get_psy_icon -import psy_simple.widgets.colors as pswc -import matplotlib.colors as mcol - if TYPE_CHECKING: - from xarray import DataArray, Dataset, Variable - from psyplot.project import PlotterInterface, Project from psyplot.data import InteractiveList from psyplot.plotter import Plotter + from psyplot.project import Project + from xarray import DataArray, Dataset T = TypeVar("T", bound="GridCell") @@ -126,7 +106,7 @@ def from_alias( o: Union[QtWidgets.QWidget, QtWidgets.QLayout], c: Optional[int] = None, cs: int = 1, - s: bool = False + s: bool = False, ) -> T: """Create a :class:`GridCell` from shorter kws. @@ -159,7 +139,7 @@ class PlotMethodWidget(QtWidgets.QWidget): attribute. """ - plotmethod: ClassVar[str] = '' + plotmethod: ClassVar[str] = "" #: trigger a replot of this widget. This can be emitted with the #: :meth:`trigger_replot` method @@ -178,8 +158,8 @@ class PlotMethodWidget(QtWidgets.QWidget): layout: QtWidgets.QGridLayout = None def __init__( - self, get_sp: Callable[[], Optional[Project]], - ds: Optional[Dataset]): + self, get_sp: Callable[[], Optional[Project]], ds: Optional[Dataset] + ): super().__init__() self._get_sp = get_sp @@ -204,7 +184,6 @@ def formatoption_rows(self) -> List[List[GridCell]]: rows.extend(self.get_rows(func)) return rows - def get_rows(self, func: Callable) -> List[List[GridCell]]: """Get the rows of the formatoption widgets. @@ -249,6 +228,7 @@ def setup_widget_grid(self) -> None: layout.addWidget(gc.qobject, i, col, 1, gc.colspan) col += gc.colspan layout.setRowStretch(len(rows), 1) + @property def sp(self) -> Optional[Project]: """Get the subproject of this plotmethod interface.""" @@ -277,11 +257,12 @@ def formatoptions(self) -> List[str]: return list(self.plotter) else: import psyplot.project as psy + return list(getattr(psy.plot, self.plotmethod).plotter_cls()) def get_fmts( - self, var: DataArray, init: bool = False - ) -> Dict[Union[Hashable, str, Any], Any]: + self, var: DataArray, init: bool = False + ) -> Dict[Union[Hashable, str, Any], Any]: """Get the formatoptions for a new plot. Parameters @@ -304,8 +285,8 @@ def get_fmts( return ret def init_dims( - self, var: DataArray - ) -> Dict[Union[Hashable, str, Any], Any]: + self, var: DataArray + ) -> Dict[Union[Hashable, str, Any], Any]: """Get the formatoptions for a new plot. Parameters @@ -332,8 +313,9 @@ def trigger_replot(self) -> None: def trigger_reset(self): """Emit the :attr:`reset` signal to reinitialize the project.""" - self.array_info = self.sp.array_info( - standardize_dims=False)[self.sp[0].psy.arr_name] + self.array_info = self.sp.array_info(standardize_dims=False)[ + self.sp[0].psy.arr_name + ] self.reset.emit(self.plotmethod) def trigger_refresh(self): @@ -341,8 +323,8 @@ def trigger_refresh(self): self.changed.emit(self.plotmethod) def get_slice( - self, x: float, y: float - ) -> Optional[Dict[Hashable, Union[int, slice]]]: + self, x: float, y: float + ) -> Optional[Dict[Hashable, Union[int, slice]]]: """Get the slice for the selected coordinates. This method is called when the user clicks on the coordinates in the @@ -375,8 +357,8 @@ def valid_variables(self, ds: Dataset) -> List[Hashable]: plotmethod = getattr(ds.psy.plot, self.plotmethod) for v in list(ds): init_kws = self.init_dims(ds[v]) # type: ignore - dims = init_kws.get('dims', {}) - decoder = init_kws.get('decoder') + dims = init_kws.get("dims", {}) + decoder = init_kws.get("decoder") if plotmethod.check_data(ds, v, dims, decoder)[0][0]: ret.append(v) return ret @@ -384,6 +366,7 @@ def valid_variables(self, ds: Dataset) -> List[Hashable]: class QHLine(QtWidgets.QFrame): """A horizontal seperation line.""" + def __init__(self): super().__init__() self.setMinimumWidth(1) @@ -391,15 +374,26 @@ def __init__(self): self.setFrameShape(QtWidgets.QFrame.HLine) self.setFrameShadow(QtWidgets.QFrame.Sunken) self.setSizePolicy( - QtWidgets.QSizePolicy.Preferred, - QtWidgets.QSizePolicy.Minimum + QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum ) class MapPlotWidget(PlotMethodWidget): """A widget to control the mapplot plotmethod.""" - plotmethod = 'mapplot' + plotmethod = "mapplot" + + @property + def sp(self) -> Optional[Project]: + sp = super().sp + if sp: + arrays: List[str] = [ + data.psy.arr_name + for data in sp + if not isinstance(data, psyd.InteractiveList) + ] + return sp(arr_name=arrays) + return sp def get_rows(self, func: Callable) -> List[List[GridCell]]: """Get the rows of the formatoption widgets. @@ -443,8 +437,10 @@ def fmt_setup_functions(self) -> List[Callable]: a horizonal (or widget) that is added to the :attr:`layout` vbox. """ return [ - self.setup_color_buttons, self.setup_plot_buttons, - self.setup_projection_buttons, self.setup_labels_button, + self.setup_color_buttons, + self.setup_plot_buttons, + self.setup_projection_buttons, + self.setup_labels_button, self.setup_separation_line, self.setup_dimension_box, ] @@ -452,7 +448,9 @@ def fmt_setup_functions(self) -> List[Callable]: def setup_labels_button(self) -> None: """Add a button to modify the text labels.""" self.btn_labels = utils.add_pushbutton( - "Edit labels", self.edit_labels, "Edit title, colorbar labels, etc." + "Edit labels", + self.edit_labels, + "Edit title, colorbar labels, etc.", ) def setup_plot_buttons(self) -> None: @@ -463,18 +461,25 @@ def setup_plot_buttons(self) -> None: PlotType.contourf, PlotType.contour, PlotType.poly, - None + None, ] self.combo_plot.setEditable(False) - self.combo_plot.addItems([ - "Default", "Filled contours", "Contours", "Gridcell polygons", - "Disable" - ]) + self.combo_plot.addItems( + [ + "Default", + "Filled contours", + "Contours", + "Gridcell polygons", + "Disable", + ] + ) self.combo_plot.currentIndexChanged.connect(self._set_plot_type) self.btn_datagrid = utils.add_pushbutton( - "Gridcell boundaries", self.toggle_datagrid, - "Toggle the visibility of grid cell boundaries") + "Gridcell boundaries", + self.toggle_datagrid, + "Toggle the visibility of grid cell boundaries", + ) self.btn_datagrid.setCheckable(True) return @@ -492,9 +497,11 @@ def setup_color_buttons(self) -> None: self.setup_cmap_menu() self.btn_cmap_settings = utils.add_pushbutton( - utils.get_icon('color_settings'), self.edit_color_settings, + utils.get_icon("color_settings"), + self.edit_color_settings, "Edit color settings", - icon=True) + icon=True, + ) def setup_cmap_menu(self) -> QtWidgets.QMenu: """Set up the menu to change the colormaps.""" @@ -502,11 +509,14 @@ def setup_cmap_menu(self) -> QtWidgets.QMenu: menu.addSeparator() self.select_cmap_action = menu.addAction( - 'More colormaps', self.open_cmap_dialog) + "More colormaps", self.open_cmap_dialog + ) self.color_settings_action = menu.addAction( - QtGui.QIcon(utils.get_icon('color_settings')), 'More options', - self.edit_color_settings) + QtGui.QIcon(utils.get_icon("color_settings")), + "More options", + self.edit_color_settings, + ) return menu @@ -531,15 +541,17 @@ def open_cmap_dialog(self, N: int = 10) -> None: def setup_projection_menu(self) -> QtWidgets.QMenu: """Set up the menu to modify the basemap.""" menu = QtWidgets.QMenu() - for projection in rcParams['projections']: + for projection in rcParams["projections"]: menu.addAction( projection_map.get(projection, projection), partial(self.set_projection, projection), ) menu.addSeparator() self.proj_settings_action = menu.addAction( - QtGui.QIcon(utils.get_icon('proj_settings')), - "Customize basemap...", self.edit_basemap_settings) + QtGui.QIcon(utils.get_icon("proj_settings")), + "Customize basemap...", + self.edit_basemap_settings, + ) return menu def get_projection_label(self, proj: str) -> str: @@ -593,8 +605,10 @@ def setup_projection_buttons(self) -> None: """Set up the buttons to modify the basemap.""" self.btn_proj = utils.add_pushbutton( self.get_projection_label(rcParams["projections"][0]), - self.choose_next_projection, "Change the basemap projection", - toolbutton=True) + self.choose_next_projection, + "Change the basemap projection", + toolbutton=True, + ) self.btn_proj.setMenu(self.setup_projection_menu()) self.btn_proj.setSizePolicy( @@ -603,27 +617,29 @@ def setup_projection_buttons(self) -> None: self.btn_proj.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btn_proj_settings = utils.add_pushbutton( - utils.get_icon('proj_settings'), self.edit_basemap_settings, + utils.get_icon("proj_settings"), + self.edit_basemap_settings, "Edit basemap settings", - icon=True) + icon=True, + ) def setup_dimension_box(self) -> None: """Set up a box to control, what is the x and y-dimension.""" self.dimension_box = QtWidgets.QGridLayout() - self.dimension_box.addWidget(QtWidgets.QLabel('x-Dimension:'), 0, 0) + self.dimension_box.addWidget(QtWidgets.QLabel("x-Dimension:"), 0, 0) self.combo_xdim = QtWidgets.QComboBox() self.dimension_box.addWidget(self.combo_xdim, 0, 1) - self.dimension_box.addWidget(QtWidgets.QLabel('y-Dimension:'), 0, 2) + self.dimension_box.addWidget(QtWidgets.QLabel("y-Dimension:"), 0, 2) self.combo_ydim = QtWidgets.QComboBox() self.dimension_box.addWidget(self.combo_ydim, 0, 3) - self.dimension_box.addWidget(QtWidgets.QLabel('x-Coordinate:'), 1, 0) + self.dimension_box.addWidget(QtWidgets.QLabel("x-Coordinate:"), 1, 0) self.combo_xcoord = QtWidgets.QComboBox() self.dimension_box.addWidget(self.combo_xcoord, 1, 1) - self.dimension_box.addWidget(QtWidgets.QLabel('y-Coordinate:'), 1, 2) + self.dimension_box.addWidget(QtWidgets.QLabel("y-Coordinate:"), 1, 2) self.combo_ycoord = QtWidgets.QComboBox() self.dimension_box.addWidget(self.combo_ycoord, 1, 3) @@ -655,8 +671,8 @@ def set_combo_text(self, combo: QtWidgets.QComboBox, text: str) -> None: combo.setCurrentIndex(items.index(text)) def init_dims( - self, var: DataArray - ) -> Dict[Union[Hashable, str, Any], Any]: + self, var: DataArray + ) -> Dict[Union[Hashable, str, Any], Any]: """Get the formatoptions for a new plot. This method updates the coordinates combo boxes with the @@ -698,20 +714,23 @@ def init_dims( else: ydim = missing[-1] dims[missing[-1]] = slice(None) # keep the last dimension - ret['dims'] = dims - + ret["dims"] = dims if self.combo_xcoord.currentIndex(): xcoord = self.combo_xcoord.currentText() - ret['decoder'] = {'x': {xcoord}} + ret["decoder"] = {"x": {xcoord}} if self.combo_ycoord.currentIndex(): ycoord = self.combo_ycoord.currentText() - ret.setdefault('decoder', {}) - ret['decoder']['y'] = {ycoord} + ret.setdefault("decoder", {}) + ret["decoder"]["y"] = {ycoord} - if (xdim is not None and xdim in var.dims and - ydim is not None and ydim in var.dims): - ret['transpose'] = var.dims.index(xdim) < var.dims.index(ydim) + if ( + xdim is not None + and xdim in var.dims + and ydim is not None + and ydim in var.dims + ): + ret["transpose"] = var.dims.index(xdim) < var.dims.index(ydim) return ret @@ -729,8 +748,9 @@ def valid_variables(self, ds: Dataset) -> List[Hashable]: List of variable names to plot """ valid = super().valid_variables(ds) - if (not any(combo.count() for combo in self.coord_combos) or - not any(combo.currentIndex() for combo in self.coord_combos)): + if not any(combo.count() for combo in self.coord_combos) or not any( + combo.currentIndex() for combo in self.coord_combos + ): return valid if self.combo_xdim.currentIndex(): xdim = self.combo_xdim.currentText() @@ -740,19 +760,21 @@ def valid_variables(self, ds: Dataset) -> List[Hashable]: valid = [v for v in valid if ydim in ds[v].dims] if self.combo_xcoord.currentIndex(): xc_dims = set(ds[self.combo_xcoord.currentText()].dims) - valid = [v for v in valid - if xc_dims.intersection(ds[v].dims)] + valid = [v for v in valid if xc_dims.intersection(ds[v].dims)] if self.combo_ycoord.currentIndex(): yc_dims = set(ds[self.combo_ycoord.currentText()].dims) - valid = [v for v in valid - if yc_dims.intersection(ds[v].dims)] + valid = [v for v in valid if yc_dims.intersection(ds[v].dims)] return valid @property def coord_combos(self) -> List[QtWidgets.QComboBox]: """Get the combo boxes for x- and y-dimension and -coordinates.""" - return [self.combo_xdim, self.combo_ydim, self.combo_xcoord, - self.combo_ycoord] + return [ + self.combo_xdim, + self.combo_ydim, + self.combo_xcoord, + self.combo_ycoord, + ] @contextlib.contextmanager def block_combos(self) -> Iterator[None]: @@ -787,21 +809,22 @@ def set_cmap(self, cmap: str) -> None: The colormap name. """ plotter = self.plotter - if plotter and 'cmap' in plotter: + if plotter and "cmap" in plotter: plotter.update(cmap=cmap) def toggle_datagrid(self) -> None: """Toggle the visibility of the grid cell boundaries.""" if self.plotter: if self.btn_datagrid.isChecked(): - self.plotter.update(datagrid='k-') + self.plotter.update(datagrid="k-") else: self.plotter.update(datagrid=None) def edit_labels(self) -> None: """Open the dialog to edit the text labels in the plot.""" dialogs.LabelDialog.update_project( - self.sp, 'figtitle', 'title', 'clabel') + self.sp, "figtitle", "title", "clabel" + ) def edit_color_settings(self) -> None: """Open the dialog to edit the color settings.""" @@ -810,15 +833,15 @@ def edit_color_settings(self) -> None: if isinstance(self.plotter.cmap.value, str): self.btn_cmap.setText(self.plotter.cmap.value) else: - self.btn_cmap.setText('Custom') + self.btn_cmap.setText("Custom") def choose_next_projection(self) -> None: """Choose the next projection from the rcParams `projection` value.""" select = False - nprojections = len(rcParams['projections']) + nprojections = len(rcParams["projections"]) current = self.get_projection_value(self.btn_proj.text()) - for i, proj in enumerate(cycle(rcParams['projections'])): + for i, proj in enumerate(cycle(rcParams["projections"])): if proj == current: select = True elif select or i == nprojections: @@ -836,7 +859,7 @@ def set_projection(self, proj: str) -> None: """ self.btn_proj.setText(self.get_projection_label(proj)) plotter = self.plotter - if plotter and 'projection' in plotter: + if plotter and "projection" in plotter: plotter.update(projection=proj) def _set_plot_type(self, i: int) -> None: @@ -862,9 +885,8 @@ def edit_basemap_settings(self) -> None: dialogs.BasemapDialog.update_plotter(self.plotter) def get_fmts( - self, var: DataArray, - init: bool = False - ) -> Dict[Union[Hashable, str, Any], Any]: + self, var: DataArray, init: bool = False + ) -> Dict[Union[Hashable, str, Any], Any]: """Get the formatoptions for a new plot. Parameters @@ -883,28 +905,28 @@ def get_fmts( """ fmts: Dict[Union[Hashable, str, Any], Any] = {} - fmts['cmap'] = self.btn_cmap.text() + fmts["cmap"] = self.btn_cmap.text() - if 'projection' in self.formatoptions: - fmts['projection'] = self.get_projection_value( + if "projection" in self.formatoptions: + fmts["projection"] = self.get_projection_value( self.btn_proj.text() ) - if 'time' in var.dims: - fmts['title'] = '%(time)s' + if "time" in var.dims: + fmts["title"] = "%(time)s" - if 'long_name' in var.attrs: - fmts['clabel'] = '%(long_name)s' + if "long_name" in var.attrs: + fmts["clabel"] = "%(long_name)s" else: - fmts['clabel'] = '%(name)s' - if 'units' in var.attrs: - fmts['clabel'] += ' %(units)s' + fmts["clabel"] = "%(name)s" + if "units" in var.attrs: + fmts["clabel"] += " %(units)s" - fmts['plot'] = self.plot_types[self.combo_plot.currentIndex()] - if fmts['plot'] == 'contour': + fmts["plot"] = self.plot_types[self.combo_plot.currentIndex()] + if fmts["plot"] == "contour": # we need to set a global map extend, see # https://github.com/SciTools/cartopy/issues/1673 - fmts['map_extent'] = 'global' + fmts["map_extent"] = "global" if init: fmts.update(self.init_dims(var)) @@ -915,29 +937,37 @@ def refresh(self, ds: Optional[Dataset]) -> None: """Refresh this widget from the given dataset.""" self.setEnabled(bool(self.sp)) - auto = 'Set automatically' + auto = "Set automatically" self.refresh_from_sp() with self.block_combos(): - if ds is None: ds = xr.Dataset() - current_dims = set(map( - self.combo_xdim.itemText, range(1, self.combo_xdim.count()))) + current_dims = set( + map( + self.combo_xdim.itemText, range(1, self.combo_xdim.count()) + ) + ) ds_dims = list( - map(str, (dim for dim, n in ds.dims.items() if n > 1))) + map(str, (dim for dim, n in ds.dims.items() if n > 1)) + ) if current_dims != set(ds_dims): self.combo_xdim.clear() self.combo_ydim.clear() self.combo_xdim.addItems([auto] + ds_dims) self.combo_ydim.addItems([auto] + ds_dims) - current_coords = set(map( - self.combo_xcoord.itemText, range(1, self.combo_xcoord.count()))) + current_coords = set( + map( + self.combo_xcoord.itemText, + range(1, self.combo_xcoord.count()), + ) + ) ds_coords = list( - map(str, (c for c, arr in ds.coords.items() if arr.ndim))) + map(str, (c for c, arr in ds.coords.items() if arr.ndim)) + ) if current_coords != set(ds_coords): self.combo_xcoord.clear() self.combo_ycoord.clear() @@ -947,8 +977,9 @@ def refresh(self, ds: Optional[Dataset]) -> None: enable_combos = not bool(self.sp) if not enable_combos and self.combo_xdim.isEnabled(): - self.reset_combos = [combo.currentIndex() == 0 - for combo in self.coord_combos] + self.reset_combos = [ + combo.currentIndex() == 0 for combo in self.coord_combos + ] elif enable_combos and not self.combo_xdim.isEnabled(): for reset, combo in zip(self.reset_combos, self.coord_combos): if reset: @@ -960,13 +991,13 @@ def refresh(self, ds: Optional[Dataset]) -> None: if not enable_combos: data = self.data - xdim = str(data.psy.get_dim('x')) - ydim = str(data.psy.get_dim('y')) + xdim = str(data.psy.get_dim("x")) + ydim = str(data.psy.get_dim("y")) self.combo_xdim.setCurrentText(xdim) self.combo_ydim.setCurrentText(ydim) - xcoord = data.psy.get_coord('x') + xcoord = data.psy.get_coord("x") xcoord = xcoord.name if xcoord is not None else xdim - ycoord = data.psy.get_coord('y') + ycoord = data.psy.get_coord("y") ycoord = ycoord.name if ycoord is not None else ydim self.combo_xcoord.setCurrentText(xcoord) @@ -981,11 +1012,11 @@ def refresh_from_sp(self) -> None: self.get_projection_label(plotter.projection.value) ) else: - self.btn_proj.setText('Custom') + self.btn_proj.setText("Custom") if isinstance(plotter.cmap.value, str): self.btn_cmap.setText(plotter.cmap.value) else: - self.btn_cmap.setText('Custom') + self.btn_cmap.setText("Custom") def transform(self, x: float, y: float) -> Tuple[float, float]: """Transform coordinates of a point to the plots projection. @@ -1006,13 +1037,16 @@ def transform(self, x: float, y: float) -> Tuple[float, float]: """ import cartopy.crs as ccrs import numpy as np + plotter = self.plotter if not plotter: raise ValueError( "Cannot transform the coordinates as no plot is shown " - "currently!") + "currently!" + ) x, y = plotter.transform.projection.transform_point( - x, y, plotter.ax.projection) + x, y, plotter.ax.projection + ) # shift if necessary if isinstance(plotter.transform.projection, ccrs.PlateCarree): coord = plotter.plot.xcoord @@ -1020,14 +1054,14 @@ def transform(self, x: float, y: float) -> Tuple[float, float]: x -= 360 elif coord.max() <= 180 and x > 180: x -= 360 - if 'rad' in coord.attrs.get('units', '').lower(): + if "rad" in coord.attrs.get("units", "").lower(): x = np.deg2rad(x) y = np.deg2rad(y) return x, y def get_slice( - self, x: float, y: float - ) -> Optional[Dict[Hashable, Union[int, slice]]]: + self, x: float, y: float + ) -> Optional[Dict[Hashable, Union[int, slice]]]: """Get the slice for the selected coordinates. This method is called when the user clicks on the coordinates in the @@ -1042,6 +1076,7 @@ def get_slice( This is reimplemented in the :class:`MapPlotWidget`. """ import numpy as np + data = self.data.psy.base.psy[self.data.name] x, y = self.transform(x, y) plotter = self.plotter @@ -1049,7 +1084,8 @@ def get_slice( if not plotter: raise ValueError( "Cannot transform the coordinates as no plot is shown " - "currently!") + "currently!" + ) fmto = plotter.plot @@ -1061,20 +1097,19 @@ def get_slice( imin = np.nanargmin(dist) if xcoord.ndim == 2: ncols = data.shape[-2] - return dict(zip(data.dims[-2:], - [imin // ncols, imin % ncols])) + return dict(zip(data.dims[-2:], [imin // ncols, imin % ncols])) else: return {data.dims[-1]: imin} else: - ix: int = xcoord.indexes[xcoord.name].get_loc(x, method='nearest') - iy: int = ycoord.indexes[ycoord.name].get_loc(y, method='nearest') + ix: int = xcoord.indexes[xcoord.name].get_loc(x, method="nearest") + iy: int = ycoord.indexes[ycoord.name].get_loc(y, method="nearest") return dict(zip(data.dims[-2:], [iy, ix])) class Plot2DWidget(MapPlotWidget): """A widget to control the plot2d plotmethod.""" - plotmethod = 'plot2d' + plotmethod = "plot2d" @property def fmt_setup_functions(self) -> List[Callable]: @@ -1102,7 +1137,8 @@ def setEnabled(self, b: bool) -> None: def edit_labels(self) -> None: """Open the dialog to edit the text labels in the plot.""" dialogs.LabelDialog.update_project( - self.sp, 'figtitle', 'title', 'clabel', 'xlabel', 'ylabel') + self.sp, "figtitle", "title", "clabel", "xlabel", "ylabel" + ) def transform(self, x: float, y: float) -> Tuple[float, float]: """Reimplemented to not transform the coordinates.""" @@ -1119,7 +1155,7 @@ def refresh_from_sp(self) -> None: class LinePlotWidget(PlotMethodWidget): """A widget to control the lineplot plotmethod.""" - plotmethod = 'lineplot' + plotmethod = "lineplot" @property def fmt_setup_functions(self) -> List[Callable]: @@ -1137,15 +1173,15 @@ def get_rows(self, func: Callable) -> List[List[GridCell]]: """ if func == self.setup_dimension_combo: row = [ - GridCell(QtWidgets.QLabel('x-Dimension:')), - GridCell(self.combo_dims) + GridCell(QtWidgets.QLabel("x-Dimension:")), + GridCell(self.combo_dims), ] elif func == self.setup_line_selection: row = [ - GridCell(QtWidgets.QLabel('Active line:')), + GridCell(QtWidgets.QLabel("Active line:")), GridCell(self.combo_lines), GridCell(self.btn_add), - GridCell(self.btn_del) + GridCell(self.btn_del), ] elif func == self.setup_labels_button: row = [GridCell(self.btn_labels, colspan=4)] @@ -1173,17 +1209,25 @@ def setup_line_selection(self) -> None: self.combo_lines.currentIndexChanged.connect(self.trigger_refresh) self.btn_add = utils.add_pushbutton( - QtGui.QIcon(get_psy_icon('plus')), lambda: self.add_line(), - "Add a line to the plot", icon=True) + QtGui.QIcon(get_psy_icon("plus")), + lambda: self.add_line(), + "Add a line to the plot", + icon=True, + ) self.btn_del = utils.add_pushbutton( - QtGui.QIcon(get_psy_icon('minus')), self.remove_line, - "Add a line to the plot", icon=True) + QtGui.QIcon(get_psy_icon("minus")), + self.remove_line, + "Add a line to the plot", + icon=True, + ) def setup_labels_button(self) -> None: """Add a button to modify the text labels.""" self.btn_labels = utils.add_pushbutton( - "Edit labels", self.edit_labels, - "Edit title, x-label, legendlabels, etc.") + "Edit labels", + self.edit_labels, + "Edit title, x-label, legendlabels, etc.", + ) @property def xdim(self) -> str: @@ -1223,9 +1267,11 @@ def add_line(self, name: Hashable = None, **sl) -> None: xdim = self.xdim if name is None: name, ok = QtWidgets.QInputDialog.getItem( - self, 'New line', 'Select a variable', - [key for key, var in ds.items() - if xdim in var.dims]) + self, + "New line", + "Select a variable", + [key for key, var in ds.items() if xdim in var.dims], + ) if not ok: return arr = ds.psy[name] @@ -1259,12 +1305,14 @@ def item_texts(self) -> List[str]: """Get the labels for the individual lines.""" if not self.sp: return [] - return [f'Line {i}: {arr.psy._short_info()}' - for i, arr in enumerate(self.sp[0])] + return [ + f"Line {i}: {arr.psy._short_info()}" + for i, arr in enumerate(self.sp[0]) + ] def init_dims( - self, var: DataArray - ) -> Dict[Union[Hashable, str, Any], Any]: + self, var: DataArray + ) -> Dict[Union[Hashable, str, Any], Any]: """Get the formatoptions for a new plot. Parameters @@ -1286,16 +1334,16 @@ def init_dims( if self.array_info: arr_names = {} for arrname, d in self.array_info.items(): - if arrname != 'attrs': - dims = d['dims'].copy() + if arrname != "attrs": + dims = d["dims"].copy() if xdim in dims: for dim, sl in dims.items(): if not isinstance(sl, int): dims[dim] = 0 dims[xdim] = slice(None) - dims['name'] = d['name'] + dims["name"] = d["name"] arr_names[arrname] = dims - ret['arr_names'] = arr_names + ret["arr_names"] = arr_names del self.array_info else: if xdim not in var.dims: @@ -1303,7 +1351,8 @@ def init_dims( if xdim is None: raise ValueError( f"Cannot plot variable {var.name} with size smaller than " - "2") + "2" + ) ret[xdim] = slice(None) for d in var.dims: if d != xdim: @@ -1313,7 +1362,8 @@ def init_dims( def edit_labels(self) -> None: """Open the dialog to edit the text labels in the plot.""" dialogs.LabelDialog.update_project( - self.sp, 'figtitle', 'title', 'xlabel', 'ylabel', 'legendlabels') + self.sp, "figtitle", "title", "xlabel", "ylabel", "legendlabels" + ) @contextlib.contextmanager def block_combos(self) -> Iterator[None]: @@ -1363,20 +1413,29 @@ def refresh(self, ds) -> None: if self.sp: with self.block_combos(): self.combo_dims.clear() - all_dims = list(chain.from_iterable( - [[d for i, d in enumerate(a.dims) if a.shape[i] > 1] - for a in arr.psy.iter_base_variables] - for arr in self.sp[0])) + all_dims = list( + chain.from_iterable( + [ + [d for i, d in enumerate(a.dims) if a.shape[i] > 1] + for a in arr.psy.iter_base_variables + ] + for arr in self.sp[0] + ) + ) intersection = set(all_dims[0]) for dims in all_dims[1:]: intersection.intersection_update(dims) new_dims = list( - filter(lambda d: d in intersection, - unique_everseen(chain.from_iterable(all_dims)))) + filter( + lambda d: d in intersection, + unique_everseen(chain.from_iterable(all_dims)), + ) + ) self.combo_dims.addItems(new_dims) self.combo_dims.setCurrentIndex( - new_dims.index(self.data.dims[-1])) + new_dims.index(self.data.dims[-1]) + ) # fill lines combo current = self.combo_lines.currentIndex() @@ -1385,7 +1444,9 @@ def refresh(self, ds) -> None: short_descs = [textwrap.shorten(s, 50) for s in descriptions] self.combo_lines.addItems(short_descs) for i, desc in enumerate(descriptions): - self.combo_lines.setItemData(i, desc, QtCore.Qt.ToolTipRole) + self.combo_lines.setItemData( + i, desc, QtCore.Qt.ToolTipRole + ) if current < len(descriptions): self.combo_lines.setCurrentText(short_descs[current]) else: diff --git a/psy_view/py.typed b/psy_view/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/psy_view/rcsetup.py b/psy_view/rcsetup.py index 61c5152..c48b763 100644 --- a/psy_view/rcsetup.py +++ b/psy_view/rcsetup.py @@ -1,59 +1,46 @@ """Configuration parameters for psy-view.""" -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only from __future__ import annotations -from typing import ( - Dict, - List, - Any, - Optional, -) -from psyplot_gui.config.rcsetup import ( - RcParams, validate_stringlist, psyplot_fname) -from psyplot.config.rcsetup import validate_dict +from typing import Any, Dict, List, Optional +from psyplot.config.rcsetup import validate_dict +from psyplot_gui.config.rcsetup import ( + RcParams, + psyplot_fname, + validate_stringlist, +) defaultParams: Dict[str, List[Any]] = { "projections": [ ["cf", "cyl", "robin", "ortho", "moll", "northpole", "southpole"], - validate_stringlist, "The names of available projections"], + validate_stringlist, + "The names of available projections", + ], "savefig_kws": [ - dict(dpi=250), validate_dict, - "Options that are passed to plt.savefig when exporting images"], + dict(dpi=250), + validate_dict, + "Options that are passed to plt.savefig when exporting images", + ], "animations.export_kws": [ - dict(writer="ffmpeg"), validate_dict, - "Options that are passed to FuncAnimation.save"], - } + dict(writer="ffmpeg"), + validate_dict, + "Options that are passed to FuncAnimation.save", + ], +} class PsyViewRcParams(RcParams): """RcParams for the psyplot-gui package.""" HEADER: str = RcParams.HEADER.replace( - 'psyplotrc.yml', 'psyviewrc.yml').replace( - 'PSYVIEWRC', 'psyviewrc.yml') + "psyplotrc.yml", "psyviewrc.yml" + ).replace("PSYVIEWRC", "psyviewrc.yml") def load_from_file(self, fname: Optional[str] = None): """ @@ -71,8 +58,9 @@ def load_from_file(self, fname: Optional[str] = None): See Also -------- dump_to_file, psyplot_fname""" - fname = fname or psyplot_fname(env_key='PSYVIEWRC', - fname='psyviewrc.yml') + fname = fname or psyplot_fname( + env_key="PSYVIEWRC", fname="psyviewrc.yml" + ) if fname: super().load_from_file(fname) diff --git a/psy_view/utils.py b/psy_view/utils.py index 9d71bcc..3214fc4 100644 --- a/psy_view/utils.py +++ b/psy_view/utils.py @@ -1,49 +1,35 @@ """Utility functions for psy-view.""" -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only from __future__ import annotations -import os.path as osp -from typing import Callable, Optional, Union, List, cast, TYPE_CHECKING +import os.path as osp +from typing import TYPE_CHECKING, Callable, List, Optional, Union, cast -from PyQt5 import QtWidgets, QtCore, QtGui +from PyQt5 import QtCore, QtGui, QtWidgets if TYPE_CHECKING: from PyQt5.QtCore import QEvent # pylint: disable=no-name-in-module -def get_icon(name: str, ending: str = '.png') -> str: - return osp.join(osp.dirname(__file__), 'icons', name + ending) +def get_icon(name: str, ending: str = ".png") -> str: + return osp.join(osp.dirname(__file__), "icons", name + ending) def add_pushbutton( - label: str, - connections: Optional[Union[List[Callable], Callable]] = None, - tooltip: Optional[str] = None, - layout: Optional[QtWidgets.QLayout] = None, - icon: bool = False, toolbutton: bool = False, *args, **kwargs - ) -> Union[QtWidgets.QPushButton, QtWidgets.QToolButton]: + label: str, + connections: Optional[Union[List[Callable], Callable]] = None, + tooltip: Optional[str] = None, + layout: Optional[QtWidgets.QLayout] = None, + icon: bool = False, + toolbutton: bool = False, + *args, + **kwargs, +) -> Union[QtWidgets.QPushButton, QtWidgets.QToolButton]: if icon or toolbutton: btn = QtWidgets.QToolButton(*args, **kwargs) if icon: diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..6c69e27 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,166 @@ +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +# +# SPDX-License-Identifier: CC0-1.0 + +[build-system] +build-backend = 'setuptools.build_meta' +requires = ['setuptools >= 61.0', 'versioneer[toml]'] + +[project] +name = "psy-view" +dynamic = ["version"] +description = "ncview-like interface to psyplot" + +readme = "README.md" +keywords = [ + "visualization", + + "psyplot", + + "netcdf", + + "raster", + + "cartopy", + + "earth-sciences", + + "pyqt", + + "qt", + + "ipython", + + "jupyter", + + "qtconsole", + + "ncview", + ] + +authors = [ + { name = 'Philipp S. Sommer', email = 'philipp.sommer@hereon.de' }, +] +maintainers = [ + { name = 'Philipp S. Sommer', email = 'philipp.sommer@hereon.de' }, +] +license = { text = 'LGPL-3.0-only' } + +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)", + "Topic :: Scientific/Engineering :: Visualization", + "Topic :: Scientific/Engineering :: GIS", + "Topic :: Scientific/Engineering", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Typing :: Typed", +] + +requires-python = '>= 3.9' +dependencies = [ + "psyplot", + # add your dependencies here + "netCDF4", + "psyplot-gui>1.3.0", + "psy-maps>1.3.0", +] + +[project.urls] +Homepage = 'https://codebase.helmholtz.cloud/psyplot/psy-view' +Documentation = "https://psyplot.github.io/psy-view" +Source = "https://codebase.helmholtz.cloud/psyplot/psy-view" +Tracker = "https://codebase.helmholtz.cloud/psyplot/psy-view/issues/" + + + +[project.scripts] +psy-view = "psy_view:main" + + +[project.entry-points."psyplot_gui"] +psy-view = "psy_view.ds_widget:DatasetWidgetPlugin" + +[project.optional-dependencies] +testsite = [ + "tox", + "isort==5.12.0", + "black==23.1.0", + "blackdoc==0.3.8", + "flake8==6.0.0", + "pre-commit", + "mypy", + "pytest-cov", + "reuse", + "cffconvert", + "types-PyYAML", + "types-docutils", + "dask", + "pytest-qt", +] +docs = [ + "autodocsumm", + "sphinx-rtd-theme", + "hereon-netcdf-sphinxext", + "sphinx-design", + "dask", + "sphinx-argparse", +] +dev = [ + "psy-view[testsite]", + "psy-view[docs]", + "PyYAML", +] + + +[tool.mypy] +ignore_missing_imports = true + +[tool.setuptools] +zip-safe = false +license-files = ["LICENSES/*"] + +[tool.setuptools.package-data] +psy_view = [ + "py.typed", + "psy_view/icons/*.png", + "psy_view/icons/*.png.license", +] + +[tool.setuptools.packages.find] +namespaces = false +exclude = [ + 'docs', + 'tests*', + 'examples' +] + +[tool.pytest.ini_options] +addopts = '-v' + +[tool.versioneer] +VCS = 'git' +style = 'pep440' +versionfile_source = 'psy_view/_version.py' +versionfile_build = 'psy_view/_version.py' +tag_prefix = 'v' +parentdir_prefix = 'psy-view-' + +[tool.isort] +profile = "black" +line_length = 79 +src_paths = ["psy_view"] +float_to_top = true +known_first_party = "psy_view" + +[tool.black] +line-length = 79 +target-version = ['py39'] + +[tool.coverage.run] +omit = ["psy_view/_version.py"] diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index effce11..0000000 --- a/setup.cfg +++ /dev/null @@ -1,7 +0,0 @@ -[versioneer] -VCS = git -style = pep440 -versionfile_source = psy_view/_version.py -versionfile_build = psy_view/_version.py -tag_prefix = v -parentdir_prefix = psy-view- diff --git a/setup.py b/setup.py index ea6379f..06c91e2 100644 --- a/setup.py +++ b/setup.py @@ -1,125 +1,12 @@ -"""Setup script for the psy-view package.""" - -# Disclaimer -# ---------- -# -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . - -import os -import os.path as osp -from setuptools import setup, find_packages -from setuptools.command.test import test as TestCommand -import sys +# SPDX-License-Identifier: CC0-1.0 +"""Setup script for the psy-view package.""" import versioneer +from setuptools import setup - -class PyTest(TestCommand): - user_options = [('pytest-args=', 'a', "Arguments to pass to pytest")] - - def initialize_options(self): - TestCommand.initialize_options(self) - self.pytest_args = '' - - def run_tests(self): - import shlex - # import here, cause outside the eggs aren't loaded - import pytest - errno = pytest.main(shlex.split(self.pytest_args)) - sys.exit(errno) - - -def readme(): - with open('README.rst') as f: - return f.read().replace( - 'docs/_static/screenshot.png', - 'https://raw.githubusercontent.com/psyplot/psy-view/master/' - 'docs/_static/screenshot.png') - - -version = versioneer.get_version() - -dependencies = [ - 'psyplot-gui>=1.3.0', - 'psy-maps>=1.3.0', - 'netCDF4', -] - -# Test for PyQt5 dependency. During a conda build, this is handled by the -# meta.yaml so we can skip this dependency -if not os.getenv('CONDA_BUILD'): - # The package might nevertheless be installed, just registered with a - # different name - try: - import PyQt5 - except ImportError: - dependencies.append('pyqt5!=5.12') - dependencies.append('PyQtWebEngine') - dependencies.append('pyqt5-sip') - - -cmdclass = versioneer.get_cmdclass({'test': PyTest}) - - -setup(name='psy-view', - version=version, - description='ncview-like interface to psyplot', - long_description=readme(), - long_description_content_type="text/x-rst", - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Science/Research', - 'Topic :: Scientific/Engineering :: Visualization', - 'Topic :: Scientific/Engineering :: GIS', - 'Topic :: Scientific/Engineering', - 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Operating System :: OS Independent', - ], - keywords=( - 'visualization netcdf raster cartopy earth-sciences pyqt qt ' - 'ipython jupyter qtconsole ncview' - ), - url='https://github.com/psyplot/psy-view', - author='Philipp S. Sommer', - author_email='psyplot@hereon.de', - license="LGPL-3.0-only", - packages=find_packages(exclude=['docs', 'tests*', 'examples']), - install_requires=dependencies, - package_data={'psy_view': [ - osp.join('psy_view', 'icons', '*.png'), - ]}, - include_package_data=True, - tests_require=['pytest', 'pytest-qt'], - cmdclass=cmdclass, - entry_points={ - 'console_scripts': ['psy-view=psy_view:main'], - 'psyplot_gui': ['psy-view=psy_view.ds_widget:DatasetWidgetPlugin'], - }, - project_urls={ - 'Documentation': 'https://psyplot.github.io/psy-view', - 'Source': 'https://github.com/psyplot/psy-viewi', - 'Tracker': 'https://github.com/psyplot/psy-view/issues', - }, - zip_safe=False) +setup( + version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), +) diff --git a/tests/conftest.py b/tests/conftest.py index 1d1897a..ca0944c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,31 +1,15 @@ """pytest configuration file for psy-view.""" -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only import os.path as osp -import pytest -import psyplot_gui.compat.qtcompat +# import psyplot_gui.compat to make sure, qt settings are set +import psyplot_gui.compat.qtcompat # noqa: F401 +import pytest _test_dir = osp.dirname(__file__) @@ -35,8 +19,14 @@ def test_dir() -> str: return _test_dir -@pytest.fixture(params=["regular-test.nc", "regional-icon-test.nc", - "rotated-pole-test.nc", "icon-test.nc"]) +@pytest.fixture( + params=[ + "regular-test.nc", + "regional-icon-test.nc", + "rotated-pole-test.nc", + "icon-test.nc", + ] +) def test_file(test_dir, request): return osp.join(test_dir, request.param) @@ -44,18 +34,21 @@ def test_file(test_dir, request): @pytest.fixture def test_ds(test_file): import psyplot.data as psyd + with psyd.open_dataset(test_file) as ds: yield ds @pytest.fixture def ds_widget(qtbot, test_ds): - import psyplot.project as psy import matplotlib.pyplot as plt + import psyplot.project as psy + from psy_view.ds_widget import DatasetWidget + w = DatasetWidget(test_ds) qtbot.addWidget(w) yield w w._sp = None - psy.close('all') - plt.close('all') + psy.close("all") + plt.close("all") diff --git a/tests/icon-test.nc.license b/tests/icon-test.nc.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/tests/icon-test.nc.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/tests/pytest.ini b/tests/pytest.ini index 3becfac..c2c952e 100644 --- a/tests/pytest.ini +++ b/tests/pytest.ini @@ -1,3 +1,6 @@ +; SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +; +; SPDX-License-Identifier: CC-BY-4.0 + [pytest] qt_api=pyqt5 - diff --git a/tests/regional-icon-test.nc.license b/tests/regional-icon-test.nc.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/tests/regional-icon-test.nc.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/tests/regular-test.nc.license b/tests/regular-test.nc.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/tests/regular-test.nc.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/tests/rotated-pole-test.nc.license b/tests/rotated-pole-test.nc.license new file mode 100644 index 0000000..919c9c1 --- /dev/null +++ b/tests/rotated-pole-test.nc.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH + +SPDX-License-Identifier: CC0-1.0 diff --git a/tests/test_dialogs.py b/tests/test_dialogs.py index b688cf1..5cd9d5a 100644 --- a/tests/test_dialogs.py +++ b/tests/test_dialogs.py @@ -1,33 +1,16 @@ """Test the formatoption dialogs.""" -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only import pytest @pytest.fixture def test_project(test_ds): - sp = test_ds.psy.plot.mapplot(name='t2m') + sp = test_ds.psy.plot.mapplot(name="t2m") yield sp sp.close() @@ -35,6 +18,7 @@ def test_project(test_ds): @pytest.fixture def cmap_dialog(qtbot, test_project): from psy_view.dialogs import CmapDialog + dialog = CmapDialog(test_project) qtbot.addWidget(dialog) return dialog @@ -50,7 +34,7 @@ def test_colorbar_preview_valid_bounds(cmap_dialog): def test_colorbar_preview_valid_cmap(cmap_dialog): """Test whether the update to a new cmap setting works""" - cmap = 'Blues' + cmap = "Blues" cmap_dialog.cmap_widget.editor.set_obj(cmap) assert cmap_dialog.cbar_preview.cbar.cmap.name == cmap @@ -69,7 +53,7 @@ def test_colorbar_preview_invalid_bounds(cmap_dialog): bounds = list(cmap_dialog.cbar_preview.cbar.norm.boundaries) # set invalid bounds - cmap_dialog.bounds_widget.editor.text = '[1, 2, 3' + cmap_dialog.bounds_widget.editor.text = "[1, 2, 3" assert list(cmap_dialog.cbar_preview.cbar.norm.boundaries) == bounds @@ -79,7 +63,7 @@ def test_colorbar_preview_invalid_cmap(cmap_dialog): cmap = cmap_dialog.cbar_preview.cbar.cmap.name # set invalid cmap - cmap_dialog.cmap_widget.editor.text = 'Blue' + cmap_dialog.cmap_widget.editor.text = "Blue" assert cmap_dialog.cbar_preview.cbar.cmap.name == cmap @@ -89,7 +73,7 @@ def test_colorbar_preview_invalid_ticks(cmap_dialog): ticks = list(cmap_dialog.cbar_preview.cbar.get_ticks()) # set invalid ticks - cmap_dialog.cticks_widget.editor.text = '[1, 2, 3' + cmap_dialog.cticks_widget.editor.text = "[1, 2, 3" assert list(cmap_dialog.cbar_preview.cbar.get_ticks()) == ticks @@ -98,6 +82,6 @@ def test_cmap_dialog_fmts(cmap_dialog): """Test the updating of formatoptions""" assert not cmap_dialog.fmts - cmap_dialog.bounds_widget.editor.set_obj('minmax') + cmap_dialog.bounds_widget.editor.set_obj("minmax") - assert cmap_dialog.fmts == {'bounds': 'minmax'} \ No newline at end of file + assert cmap_dialog.fmts == {"bounds": "minmax"} diff --git a/tests/test_ds_widget.py b/tests/test_ds_widget.py index 25f3c11..77a264a 100644 --- a/tests/test_ds_widget.py +++ b/tests/test_ds_widget.py @@ -1,33 +1,17 @@ """Test the main functionality of the psy-view package, namely the widget.""" -# Disclaimer -# ---------- +# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht +# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH # -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . +# SPDX-License-Identifier: LGPL-3.0-only import os.path as osp -import sys import shutil -from PyQt5.QtCore import Qt -from PyQt5 import QtWidgets +import sys + import pytest +from PyQt5 import QtWidgets +from PyQt5.QtCore import Qt def test_variables(ds_widget, test_ds): @@ -39,19 +23,19 @@ def test_variables(ds_widget, test_ds): def test_mapplot(qtbot, ds_widget): """Test plotting and closing with mapplot""" - ds_widget.plotmethod = 'mapplot' - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + ds_widget.plotmethod = "mapplot" + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert ds_widget.sp - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert not ds_widget.sp -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d']) -@pytest.mark.parametrize('i', list(range(5))) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d"]) +@pytest.mark.parametrize("i", list(range(5))) def test_change_plot_type(qtbot, ds_widget, plotmethod, i): """Test plotting and closing with mapplot""" ds_widget.plotmethod = plotmethod - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert ds_widget.sp pm_widget = ds_widget.plotmethod_widget pm_widget.combo_plot.setCurrentIndex(i) @@ -60,39 +44,39 @@ def test_change_plot_type(qtbot, ds_widget, plotmethod, i): assert ds_widget.sp.plotters[0].plot.value == plot_type -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d']) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d"]) def test_variable_switch(qtbot, ds_widget, plotmethod): """Test switching of variables""" ds_widget.plotmethod = plotmethod - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert len(ds_widget.sp) == 1 - assert ds_widget.data.name == 't2m' - qtbot.mouseClick(ds_widget.variable_buttons['v'], Qt.LeftButton) + assert ds_widget.data.name == "t2m" + qtbot.mouseClick(ds_widget.variable_buttons["v"], Qt.LeftButton) assert len(ds_widget.sp) == 1 - assert ds_widget.data.name == 'v' - qtbot.mouseClick(ds_widget.variable_buttons['v_2d'], Qt.LeftButton) + assert ds_widget.data.name == "v" + qtbot.mouseClick(ds_widget.variable_buttons["v_2d"], Qt.LeftButton) assert len(ds_widget.sp) == 1 - assert ds_widget.data.name == 'v_2d' - qtbot.mouseClick(ds_widget.variable_buttons['v'], Qt.LeftButton) + assert ds_widget.data.name == "v_2d" + qtbot.mouseClick(ds_widget.variable_buttons["v"], Qt.LeftButton) assert len(ds_widget.sp) == 1 - assert ds_widget.data.name == 'v' - qtbot.mouseClick(ds_widget.variable_buttons['v'], Qt.LeftButton) + assert ds_widget.data.name == "v" + qtbot.mouseClick(ds_widget.variable_buttons["v"], Qt.LeftButton) assert not ds_widget.sp def test_plot2d(qtbot, ds_widget): """Test plotting and closing with plot2d""" - ds_widget.plotmethod = 'plot2d' - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + ds_widget.plotmethod = "plot2d" + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert ds_widget.sp - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert not ds_widget.sp def test_plot2d_dim_switch(qtbot, ds_widget, test_ds, test_file): - arr = test_ds['t2m'] + arr = test_ds["t2m"] - ds_widget.plotmethod = 'plot2d' + ds_widget.plotmethod = "plot2d" pm_widget = ds_widget.plotmethod_widget @@ -104,9 +88,9 @@ def test_plot2d_dim_switch(qtbot, ds_widget, test_ds, test_file): fmts = pm_widget.init_dims(arr) - assert fmts['transpose'] + assert fmts["transpose"] - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert not pm_widget.combo_xdim.isEnabled() @@ -114,19 +98,19 @@ def test_plot2d_dim_switch(qtbot, ds_widget, test_ds, test_file): assert ds_widget.plotter.plot_data.dims == arr.dims[:2] -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d']) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d"]) def test_plot2d_coord(qtbot, ds_widget, test_ds, test_file, plotmethod): - arr = test_ds.psy['t2m'] + arr = test_ds.psy["t2m"] if osp.basename(test_file) != "rotated-pole-test.nc": return pytest.skip("Testing rotated coords only") ydim, xdim = arr.dims[-2:] - test_ds[xdim].attrs.pop('axis', None) - test_ds[ydim].attrs.pop('axis', None) + test_ds[xdim].attrs.pop("axis", None) + test_ds[ydim].attrs.pop("axis", None) - assert 'coordinates' in arr.encoding + assert "coordinates" in arr.encoding ds_widget.plotmethod = plotmethod @@ -135,15 +119,15 @@ def test_plot2d_coord(qtbot, ds_widget, test_ds, test_file, plotmethod): assert pm_widget.combo_xcoord.isEnabled() # make the plot with default setting - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert not pm_widget.combo_xcoord.isEnabled() - assert pm_widget.data.psy.get_coord('x').name != xdim - assert pm_widget.data.psy.get_coord('y').name != ydim + assert pm_widget.data.psy.get_coord("x").name != xdim + assert pm_widget.data.psy.get_coord("y").name != ydim # remove the plot - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert pm_widget.combo_xcoord.isEnabled() @@ -152,72 +136,72 @@ def test_plot2d_coord(qtbot, ds_widget, test_ds, test_file, plotmethod): pm_widget.combo_ycoord.setCurrentText(ydim) # make the plot with the changed settings - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert not pm_widget.combo_xcoord.isEnabled() - assert pm_widget.data.psy.get_coord('x').name == xdim - assert pm_widget.data.psy.get_coord('y').name == ydim + assert pm_widget.data.psy.get_coord("x").name == xdim + assert pm_widget.data.psy.get_coord("y").name == ydim def test_lineplot(qtbot, ds_widget): """Test plotting and closing with lineplot""" - ds_widget.plotmethod = 'lineplot' - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + ds_widget.plotmethod = "lineplot" + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert ds_widget.sp - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert not ds_widget.sp def test_lineplot_switch(qtbot, ds_widget): """Test switching of variables""" - ds_widget.plotmethod = 'lineplot' - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + ds_widget.plotmethod = "lineplot" + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert len(ds_widget.sp) == 1 - assert ds_widget.data.name == 't2m' - qtbot.mouseClick(ds_widget.variable_buttons['v'], Qt.LeftButton) + assert ds_widget.data.name == "t2m" + qtbot.mouseClick(ds_widget.variable_buttons["v"], Qt.LeftButton) assert len(ds_widget.sp) == 1 - assert ds_widget.data.name == 'v' - qtbot.mouseClick(ds_widget.variable_buttons['v'], Qt.LeftButton) + assert ds_widget.data.name == "v" + qtbot.mouseClick(ds_widget.variable_buttons["v"], Qt.LeftButton) assert not ds_widget.sp -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d']) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d"]) def test_cmap(qtbot, ds_widget, plotmethod): ds_widget.plotmethod = plotmethod - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) cmap = ds_widget.plotter.cmap.value assert ds_widget.plotter.plot.mappable.get_cmap().name == cmap ds_widget.plotmethod_widget.btn_cmap.menu().actions()[5].trigger() assert ds_widget.plotter.cmap.value != cmap assert ds_widget.plotter.plot.mappable.get_cmap().name != cmap - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) def test_add_and_remove_line(qtbot, ds_widget, monkeypatch): "Test adding and removing lines" - ds_widget.plotmethod = 'lineplot' + ds_widget.plotmethod = "lineplot" monkeypatch.setattr( - QtWidgets.QInputDialog, "getItem", - lambda *args: ('t2m', True)) + QtWidgets.QInputDialog, "getItem", lambda *args: ("t2m", True) + ) - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert ds_widget.sp assert len(ds_widget.sp[0]) == 1 qtbot.mouseClick(ds_widget.plotmethod_widget.btn_add, Qt.LeftButton) assert len(ds_widget.sp[0]) == 2 qtbot.mouseClick(ds_widget.plotmethod_widget.btn_del, Qt.LeftButton) assert len(ds_widget.sp[0]) == 1 - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert not ds_widget.sp -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d', 'lineplot']) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d", "lineplot"]) def test_btn_step(qtbot, ds_widget, plotmethod): """Test clicking the next time button""" ds_widget.plotmethod = plotmethod - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) dim = ds_widget.combo_dims.currentText() assert dim assert ds_widget.data.psy.idims[dim] == 0 @@ -230,11 +214,12 @@ def test_btn_step(qtbot, ds_widget, plotmethod): qtbot.mouseClick(ds_widget.btn_prev, Qt.LeftButton) assert ds_widget.data.psy.idims[dim] == 0 -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d', 'lineplot']) + +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d", "lineplot"]) def test_dimension_button(qtbot, ds_widget, plotmethod): """Test clicking on a button in the dimension table""" ds_widget.plotmethod = plotmethod - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) btn = ds_widget.dimension_table.cellWidget(1, 2) @@ -251,8 +236,8 @@ def test_dimension_button(qtbot, ds_widget, plotmethod): assert ds_widget.data.psy.idims[dim] == 0 -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d', 'lineplot']) -@pytest.mark.parametrize('direction', ['forward', 'backward']) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d", "lineplot"]) +@pytest.mark.parametrize("direction", ["forward", "backward"]) def test_animate(qtbot, ds_widget, plotmethod, direction): """Test clicking the next time button""" @@ -266,17 +251,16 @@ def animation_finished(): else: return True - ds_widget.plotmethod = plotmethod ds_widget.sl_interval.setValue(10) - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) dim = ds_widget.combo_dims.currentText() assert dim steps = set(range(ds_widget.ds.dims[dim])) - btn = getattr(ds_widget, 'btn_animate_' + direction) + btn = getattr(ds_widget, "btn_animate_" + direction) assert not ds_widget._animating @@ -301,46 +285,47 @@ def animation_finished(): def test_enable_disable_variables(test_ds, qtbot): - from psy_view.ds_widget import DatasetWidget import numpy as np - test_ds['line'] = ('xtest', np.zeros(7)) - test_ds['xtest'] = ('xtest', np.arange(7)) + + from psy_view.ds_widget import DatasetWidget + + test_ds["line"] = ("xtest", np.zeros(7)) + test_ds["xtest"] = ("xtest", np.arange(7)) ds_widget = DatasetWidget(test_ds) qtbot.addWidget(ds_widget) - assert ds_widget.variable_buttons['t2m'].isEnabled() - assert not ds_widget.variable_buttons['line'].isEnabled() + assert ds_widget.variable_buttons["t2m"].isEnabled() + assert not ds_widget.variable_buttons["line"].isEnabled() - ds_widget.plotmethod = 'lineplot' + ds_widget.plotmethod = "lineplot" - assert ds_widget.variable_buttons['t2m'].isEnabled() - assert ds_widget.variable_buttons['line'].isEnabled() + assert ds_widget.variable_buttons["t2m"].isEnabled() + assert ds_widget.variable_buttons["line"].isEnabled() - ds_widget.plotmethod = 'plot2d' + ds_widget.plotmethod = "plot2d" - assert ds_widget.variable_buttons['t2m'].isEnabled() - assert not ds_widget.variable_buttons['line'].isEnabled() + assert ds_widget.variable_buttons["t2m"].isEnabled() + assert not ds_widget.variable_buttons["line"].isEnabled() -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d', 'lineplot']) -def test_open_and_close_plots( - ds_widget, qtbot, monkeypatch, plotmethod): +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d", "lineplot"]) +def test_open_and_close_plots(ds_widget, qtbot, monkeypatch, plotmethod): """Create multiple plots and export them all""" ds_widget.plotmethod = plotmethod monkeypatch.setattr( - QtWidgets.QInputDialog, "getItem", - lambda *args: ('t2m', True)) + QtWidgets.QInputDialog, "getItem", lambda *args: ("t2m", True) + ) qtbot.mouseClick(ds_widget.btn_add, Qt.LeftButton) assert ds_widget.sp assert len(ds_widget.sp) == 1 - assert ds_widget.variable_buttons['t2m'].isChecked() + assert ds_widget.variable_buttons["t2m"].isChecked() monkeypatch.setattr( - QtWidgets.QInputDialog, "getItem", - lambda *args: ('u', True)) + QtWidgets.QInputDialog, "getItem", lambda *args: ("u", True) + ) # create a second plot qtbot.mouseClick(ds_widget.btn_add, Qt.LeftButton) @@ -350,42 +335,43 @@ def test_open_and_close_plots( assert len(ds_widget._sp) == 2 assert ds_widget.combo_array.count() == 2 assert ds_widget.combo_array.currentIndex() == 1 - assert ds_widget.variable_buttons['u'].isChecked() + assert ds_widget.variable_buttons["u"].isChecked() # switch to the first variable ds_widget.combo_array.setCurrentIndex(0) assert len(ds_widget.sp) == 1 assert len(ds_widget._sp) == 2 - assert ds_widget.data.name == 't2m' - assert ds_widget.variable_buttons['t2m'].isChecked() + assert ds_widget.data.name == "t2m" + assert ds_widget.variable_buttons["t2m"].isChecked() # close the plot qtbot.mouseClick(ds_widget.btn_del, Qt.LeftButton) assert len(ds_widget.sp) == 1 assert len(ds_widget._sp) == 1 - assert ds_widget.data.name == 'u' - assert ds_widget.variable_buttons['u'].isChecked() + assert ds_widget.data.name == "u" + assert ds_widget.variable_buttons["u"].isChecked() # close the second plot qtbot.mouseClick(ds_widget.btn_del, Qt.LeftButton) assert not bool(ds_widget.sp) assert not bool(ds_widget._sp) - assert not any(btn.isChecked() for name, btn in - ds_widget.variable_buttons.items()) + assert not any( + btn.isChecked() for name, btn in ds_widget.variable_buttons.items() + ) -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d', 'lineplot']) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d", "lineplot"]) def test_multi_export(ds_widget, qtbot, monkeypatch, tmpdir, plotmethod): """Create multiple plots and export them all""" ds_widget.plotmethod = plotmethod - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert ds_widget.sp assert len(ds_widget.sp) == 1 monkeypatch.setattr( - QtWidgets.QInputDialog, "getItem", - lambda *args: ('u', True)) + QtWidgets.QInputDialog, "getItem", lambda *args: ("u", True) + ) # create a second plot qtbot.mouseClick(ds_widget.btn_add, Qt.LeftButton) @@ -399,16 +385,20 @@ def test_multi_export(ds_widget, qtbot, monkeypatch, tmpdir, plotmethod): # export the plots monkeypatch.setattr( - QtWidgets.QFileDialog, "getSaveFileName", - lambda *args: (osp.join(tmpdir, "test.pdf"), True)) + QtWidgets.QFileDialog, + "getSaveFileName", + lambda *args: (osp.join(tmpdir, "test.pdf"), True), + ) ds_widget.export_all_images() # Test if warning is triggered when exporting only one image monkeypatch.setattr( - QtWidgets.QFileDialog, "getSaveFileName", - lambda *args: (osp.join(tmpdir, "test.png"), True)) + QtWidgets.QFileDialog, + "getSaveFileName", + lambda *args: (osp.join(tmpdir, "test.png"), True), + ) question_asked = [] @@ -416,10 +406,7 @@ def dont_save(*args): question_asked.append(True) return QtWidgets.QMessageBox.No - monkeypatch.setattr( - QtWidgets.QMessageBox, "question", dont_save) - - + monkeypatch.setattr(QtWidgets.QMessageBox, "question", dont_save) ds_widget.export_all_images() @@ -428,14 +415,14 @@ def dont_save(*args): assert not osp.exists(osp.join(tmpdir, "test.png")) -@pytest.mark.parametrize('plotmethod', ['mapplot', 'plot2d', 'lineplot']) +@pytest.mark.parametrize("plotmethod", ["mapplot", "plot2d", "lineplot"]) def test_export_animation(qtbot, ds_widget, plotmethod, tmpdir, monkeypatch): """Test clicking the next time button""" from psy_view.rcsetup import rcParams ds_widget.plotmethod = plotmethod ds_widget.sl_interval.setValue(10) - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) dim = ds_widget.combo_dims.currentText() assert dim @@ -443,11 +430,13 @@ def test_export_animation(qtbot, ds_widget, plotmethod, tmpdir, monkeypatch): assert not ds_widget._animating monkeypatch.setattr( - QtWidgets.QFileDialog, "getSaveFileName", - lambda *args: (osp.join(tmpdir, "test.gif"), True)) + QtWidgets.QFileDialog, + "getSaveFileName", + lambda *args: (osp.join(tmpdir, "test.gif"), True), + ) with rcParams.catch(): - rcParams['animations.export_kws'] = {'writer': 'pillow'} + rcParams["animations.export_kws"] = {"writer": "pillow"} ds_widget.export_animation() @@ -460,6 +449,7 @@ def test_export_animation(qtbot, ds_widget, plotmethod, tmpdir, monkeypatch): def test_reload(qtbot, test_dir, tmp_path) -> None: """Test the reload button.""" import psyplot.project as psy + from psy_view.ds_widget import DatasetWidget f1, f2 = "regular-test.nc", "regional-icon-test.nc" @@ -467,9 +457,10 @@ def test_reload(qtbot, test_dir, tmp_path) -> None: ds_widget = DatasetWidget(psy.open_dataset(str(tmp_path / f1))) qtbot.addWidget(ds_widget) - qtbot.mouseClick(ds_widget.variable_buttons['t2m'], Qt.LeftButton) + qtbot.mouseClick(ds_widget.variable_buttons["t2m"], Qt.LeftButton) assert ds_widget.ds_tree.topLevelItemCount() == 1 + assert ds_widget.ds is not None assert ds_widget.ds["t2m"].ndim == 4 # now copy the icon file to the same destination and reload everything @@ -477,5 +468,6 @@ def test_reload(qtbot, test_dir, tmp_path) -> None: ds_widget.reload() assert ds_widget.ds_tree.topLevelItemCount() == 1 + assert ds_widget.ds is not None assert ds_widget.ds["t2m"].ndim == 3 assert len(psy.gcp(True)) == 1 diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..2fd78de --- /dev/null +++ b/tox.ini @@ -0,0 +1,24 @@ +; SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH +; +; SPDX-License-Identifier: CC0-1.0 + +[tox] + +[testenv] +extras = + testsite + +commands = + ; mypy psy_view + isort --check psy_view + black --line-length 79 --check psy_view + blackdoc --check psy_view + flake8 psy_view + pytest -v --cov=psy_view -x + reuse lint + cffconvert --validate + +[pytest] +DJANGO_SETTINGS_MODULE = testproject.settings +python_files = tests.py test_*.py *_tests.py +norecursedirs = .* build dist *.egg venv docs diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 0e4398e..0000000 --- a/versioneer.py +++ /dev/null @@ -1,1847 +0,0 @@ - -# Version: 0.18 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/warner/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other langauges) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - -### Unicode version strings - -While Versioneer works (and is continually tested) with both Python 2 and -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. -Newer releases probably generate unicode version strings on py2. It's not -clear that this is wrong, but it may be surprising for applications when then -write these strings to a network connection or include them in bytes-oriented -APIs like cryptographic checksums. - -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates -this question. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -""" - -# Disclaimer -# ---------- -# -# Copyright (C) 2021 Helmholtz-Zentrum Hereon -# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht -# -# This file is part of psy-view and is released under the GNU LGPL-3.O license. -# See COPYING and COPYING.LESSER in the root of the repository for full -# licensing details. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3.0 as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU LGPL-3.0 license for more details. -# -# You should have received a copy of the GNU LGPL-3.0 license -# along with this program. If not, see . -# -# This file is originally released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) - -from __future__ import print_function -try: - import configparser -except ImportError: - import ConfigParser as configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: - parser.readfp(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode - - -LONG_VERSION_PY['git'] = ''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(manifest_in, versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: - pass - if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.18) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except EnvironmentError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.distutils_buildexe import py2exe as _py2exe # py3 - except ImportError: - from py2exe.build_exe import py2exe as _py2exe # py2 - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -INIT_PY_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - - -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1)