diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index e9fcd53..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -lib/windspharm/_version.py export-subst diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7de7c4b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# See https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/keeping-your-actions-up-to-date-with-dependabot + +version: 2 +updates: + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "bot" diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml new file mode 100644 index 0000000..e6f4d59 --- /dev/null +++ b/.github/workflows/deploy-docs.yml @@ -0,0 +1,50 @@ + +name: Documentation + +on: + pull_request: + push: + branches: + - main + release: + types: + - published + +jobs: + build-docs: + runs-on: ubuntu-latest + + steps: + - name: checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Micromamba + uses: mamba-org/setup-micromamba@v2 + with: + environment-name: TEST + init-shell: bash + create-args: >- + python=3 pip pyspharm iris xarray sphinx sphinx-issues --channel conda-forge + + - name: Install windspharm + shell: bash -l {0} + run: | + python -m pip install -e . --no-deps --force-reinstall + + - name: Build documentation + shell: bash -l {0} + run: | + set -e + micromamba activate TEST + pushd docs + make clean html linkcheck + popd + + - name: Deploy + if: success() && github.event_name == 'release' + uses: peaceiris/actions-gh-pages@v4 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: docs/_build/html diff --git a/.github/workflows/pypi.yml b/.github/workflows/pypi.yml new file mode 100644 index 0000000..a280701 --- /dev/null +++ b/.github/workflows/pypi.yml @@ -0,0 +1,65 @@ +name: Publish to PyPI + +on: + pull_request: + push: + branches: + - main + release: + types: + - published + +defaults: + run: + shell: bash + +jobs: + build_wheels: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Get tags + run: git fetch --depth=1 origin +refs/tags/*:refs/tags/* + + - name: Setup Micromamba Python + uses: mamba-org/setup-micromamba@v2 + with: + environment-name: PYPI + init-shell: bash + create-args: >- + python + pip + pytest + numpy + pyspharm + --channel conda-forge + + - name: Install build tools + shell: bash -l {0} + run: | + python -m pip install --upgrade build check-manifest twine + + - name: Build binary wheel + shell: bash -l {0} + run: | + python -m build --sdist --wheel . --outdir dist + + - name: Check manifest + shell: bash -l {0} + run: | + ls dist + check-manifest --verbose + + - name: Test wheels + shell: bash -l {0} + run: | + cd dist && python -m pip install *.whl + python -m twine check * + + - name: Publish a Python distribution to PyPI + if: success() && github.event_name == 'release' + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.PYPI_PASSWORD }} diff --git a/.github/workflows/tests-standard.yml b/.github/workflows/tests-standard.yml new file mode 100644 index 0000000..c8fc57d --- /dev/null +++ b/.github/workflows/tests-standard.yml @@ -0,0 +1,37 @@ +name: Standard Tests + +on: + pull_request: + push: + branches: [main] + +jobs: + run: + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: ["3.10", "3.11", "3.12", "3.13"] + os: [ubuntu-latest, macos-latest] + fail-fast: false + + steps: + - uses: actions/checkout@v4 + + - name: Setup Micromamba Python ${{ matrix.python-version }} + uses: mamba-org/setup-micromamba@v2 + with: + environment-name: TEST + init-shell: bash + create-args: >- + python=${{ matrix.python-version }} pip pytest numpy pyspharm --channel conda-forge + + + - name: Install windspharm + shell: bash -l {0} + run: | + python -m pip install -e . --no-deps --force-reinstall + + - name: Tests + shell: bash -l {0} + run: | + python -m pytest -vrsx windspharm/tests diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..d95315a --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,36 @@ +name: Full Tests + +on: + pull_request: + push: + branches: [main] + +jobs: + run: + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: ["3.10", "3.11", "3.12", "3.13"] + os: [ubuntu-latest, macos-latest] + fail-fast: false + + steps: + - uses: actions/checkout@v4 + + - name: Setup Micromamba Python ${{ matrix.python-version }} + uses: mamba-org/setup-micromamba@v2 + with: + environment-name: TEST + init-shell: bash + create-args: >- + python=${{ matrix.python-version }} pip pytest numpy pyspharm iris xarray --channel conda-forge + + - name: Install windspharm + shell: bash -l {0} + run: | + python -m pip install -e . --no-deps --force-reinstall + + - name: Tests + shell: bash -l {0} + run: | + python -m pytest -vrsx windspharm/tests diff --git a/.gitignore b/.gitignore index 206108b..758a30b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ # Created by https://www.gitignore.io/api/vim,code,emacs,python +windspharm/_version.py + ### Code ### # Visual Studio Code - https://code.visualstudio.com/ .settings/ @@ -193,4 +195,4 @@ tags [._]*.un~ -# End of https://www.gitignore.io/api/vim,code,emacs,python \ No newline at end of file +# End of https://www.gitignore.io/api/vim,code,emacs,python diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..e87f758 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,10 @@ +repos: +- repo: https://github.com/tox-dev/pyproject-fmt + rev: v2.5.0 + hooks: + - id: pyproject-fmt + +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.7.3 + hooks: + - id: ruff \ No newline at end of file diff --git a/.stickler.yml b/.stickler.yml deleted file mode 100644 index b514297..0000000 --- a/.stickler.yml +++ /dev/null @@ -1,2 +0,0 @@ -linters: - flake8: diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7cb7ede..0000000 --- a/.travis.yml +++ /dev/null @@ -1,85 +0,0 @@ -language: python - -env: - global: - # Doctr deploy key for ajdawson/windspharm - - secure: "gRWSAM7JnHeIFx6QldIPvQf9XBWzm9lLjjGYvmCez6MDTGxtlEhF5yvNmX9m/f/WtoqLcw+/w7L198GUT8FUwZZ2wsHPhwePJalqdbIatN3QW2q0KHHj36Ob9UZDf9I7ni4XtPZsmm8eSx/f818PJktgGLbmKipNfWyRwkr7tXY=" - - UVCDAT_ANONYMOUS_LOG=no - - PACKAGES_DEFAULT="setuptools pytest numpy pyspharm" - - PACKAGES_EXTRA="cdms2 genutil iris xarray" - -matrix: - include: - - python: 2.7 - env: - - SUITE_TYPE=test_standard - - python: 2.7 - env: - - SUITE_TYPE=test_extras - - python: 3.6 - env: - - SUITE_TYPE=test_standard - - python: 3.6 - env: - - SUITE_TYPE=test_extras - - python: 3.6 - env: - - SUITE_TYPE=deploy - -sudo: false - -before_install: - - wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh - - bash miniconda.sh -b -p $HOME/miniconda - - export PATH="$HOME/miniconda/bin:$PATH" - - hash -r - - conda config --set always_yes yes --set changeps1 no - - conda config --add channels conda-forge - - conda update conda - - conda info -a - -install: - - conda create -n test python=$TRAVIS_PYTHON_VERSION - - source activate test - - if [[ $SUITE_TYPE = test_standard ]]; then - conda install $PACKAGES_DEFAULT; - elif [[ $SUITE_TYPE = test_extras ]]; then - conda install $PACKAGES_DEFAULT $PACKAGES_EXTRA; - else - conda install $PACKAGES_DEFAULT $PACKAGES_EXTRA sphinx doctr; - fi - - python setup.py install - -script: - # Fail on error to avoid building documentation when the tests don't pass - - set -e - - # Run the test suite - - pytest -vrsx - - # Deploy the documentation. By default doctr only works on the master - # branch. We also want to deploy when building a tag, which requires - # post-processing to update the "latest" symlink. - - if [[ $SUITE_TYPE = "deploy" ]]; then - cd docs && make html && cd ..; - doctr -V; - if [[ -n "$TRAVIS_TAG" ]]; then - doctr deploy --build-tags --command './update_links.py && git add latest' "${TRAVIS_TAG%.*}"; - else - doctr deploy dev; - fi; - fi - -deploy: - provider: pypi - user: ajdawson - password: - secure: "kPR7n+oFtdOi1SoEsg0hDu9bmgBwyNDELhIBs+FqmStszF+N3WVME35n4skrb6L1/NtjmACnV3BZZkJTCALGX7IX4tO08SCyS4IlPPOOGukgQ54/5hTYpxU4q2dON7AVFQ/VEe56mxPd5shR+sxkdLJ6tZRzQuc5eN9/Uu2p1Mk=" - upload_docs: no - on: - repo: ajdawson/windspharm - tags: true - condition: '$SUITE_TYPE == "deploy"' - -notifications: - email: false diff --git a/MANIFEST.in b/MANIFEST.in index dbf4336..1f4886d 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,15 @@ +includ pyproject.toml include README.md include license.txt -include versioneer.py -include lib/windspharm/_version.py + +graft windspharm + +recursive-include examples *.py +recursive-include windspharm *.nc + +prune .github +prune *.egg-info +prune docs + +exclude *.yaml +exclude windspharm/_version.py diff --git a/README.md b/README.md index 098fdb6..b3df0be 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ windspharm - spherical harmonic vector wind analysis in Python ============================================================== -[![Build Status](https://api.travis-ci.org/repositories/ajdawson/windspharm.svg?branch=master)](https://travis-ci.org/ajdawson/windspharm) [![DOI (paper)](https://img.shields.io/badge/DOI%20%28paper%29-10.5334%2Fjors.129-blue.svg)](http://doi.org/10.5334/jors.129) [![DOI (latest release)](https://zenodo.org/badge/20448/ajdawson/windspharm.svg)](https://zenodo.org/badge/latestdoi/20448/ajdawson/windspharm) +[![DOI (paper)](https://img.shields.io/badge/DOI%20%28paper%29-10.5334%2Fjors.129-blue.svg)](http://doi.org/10.5334/jors.129) [![DOI (latest release)](https://zenodo.org/badge/4715033.svg)](https://zenodo.org/records/1401190) Overview -------- @@ -17,9 +17,7 @@ windspharm provides a replacement for the windfield package from CDAT. Requirements ------------ -`windspharm` only requires [`numpy`](http://numpy.org) and [`pyspharm`](https://github.com/jswhit/pyspharm) (version 1.0.8 or higher), but for full functionality (meta-data interfaces) one or more of [`iris`](http://scitools.org.uk/iris/), [`xarray`](http://xarray.pydata.org) or the `cdms2` module (from [UV-CDAT](http://uvcdat.llnl.gov) is required. -The setuptools package is required for installation. -windspharm runs on Python 2 and 3. +`windspharm` only requires [`numpy`](http://numpy.org) and [`pyspharm`](https://github.com/jswhit/pyspharm) (version 1.0.9 or higher), but for full functionality (meta-data interfaces) one or both of [`iris`](http://scitools.org.uk/iris/) and/or [`xarray`](http://xarray.pydata.org) are required. Documentation @@ -39,8 +37,8 @@ You can additionally cite the [Zenodo DOI](https://zenodo.org/badge/latestdoi/20 Frequently asked questions -------------------------- -* **Do I need UV-CDAT/iris/xarray to use windspharm?** - No. All the computation code uses numpy only. The iris, xarray and cdms2 modules are only required for the meta-data preserving interfaces. +* **Do I need iris/xarray to use windspharm?** + No. All the computation code uses numpy only. The iris and/or xarray modules are only required for the meta-data preserving interfaces. * **Is windspharm a drop in replacement for windfield?** No. Because windspharm was written from scratch the naming conventions for methods are different. Some new methods have been added compared to windfield, and some @@ -54,7 +52,9 @@ The easiest way to install is via [conda](http://conda.pydata.org): conda install -c conda-forge windspharm -You can also install from the source distribution. -Download the archive, unpack it, then enter the source directory and use: +You can also install with pip:: - python setup.py install + python -m pip install windspharm + +> [!CAUTION] +> Make sure you already have pyspharm dependency installed, as it may fail to install if pip tries to do it. diff --git a/docs/api/index.rst b/docs/api/index.rst index 2efda51..9dfab87 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -10,7 +10,6 @@ Full documentation :maxdepth: 1 windspharm.standard - windspharm.cdms windspharm.iris windspharm.xarray windspharm.tools diff --git a/docs/api/windspharm.cdms.rst b/docs/api/windspharm.cdms.rst deleted file mode 100644 index fc441c5..0000000 --- a/docs/api/windspharm.cdms.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. default-role:: py:obj - - -`windspharm.cdms` -================= - -.. currentmodule:: windspharm.cdms - -.. automodule:: windspharm.cdms - :members: VectorWind diff --git a/docs/changelog.rst b/docs/changelog.rst index b2a4b3d..d89771d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -3,6 +3,14 @@ Changelog Source code downloads for released versions can be downloaded from `Github `_. +v2.0 +---- + +:Release: v2.0.0 + +The v2.0.0 release removes the cdms interface. The cdms2 package is no longer maintained and therefore support has been dropped. + + v1.7 ---- @@ -13,7 +21,7 @@ The v1.7.0 release makes further progress on the road to more modern tooling and * Support for using Legendre functions computed on-the-fly or stored, implemented by `@rcomer `_ [:issue:`97`, :pr:`98`]. * The source code directories have been reorganised, the ``lib/windspharm`` directory has been moved to ``windspharm/`` (``lib/`` is removed) and the ``doc/`` directory has been renamed ``docs/`` [:pr:`105`]. -* The package version is now controlled by `versioneer `_. +* The package version is now controlled by `versioneer `_. In addition, this is the first release where documentation and PyPI packages will be built automatically as part of the continuous integration system. @@ -27,7 +35,7 @@ v1.6 This release has no major user-facing changes, its main purpose is to modernise the test suite and fix problems with NumPy compatibility, although the modifications to the test suite may have knock-on effects for package maintainers. * Fixes for NumPy compatibility [:issue:`89`, :pr:`90`]. -* Switch from `nose` to `pytest `_ for the test suite [:pr:`91`, :pr:`94`]. +* Switch from `nose` to `pytest `_ for the test suite [:pr:`91`, :pr:`94`]. v1.5 @@ -50,7 +58,7 @@ v1.4 :Release: v1.4.0 :Date: 1 March 2016 -* Added an `xarray `_ interface allowing use of `windspharm` with `xarray.DataArray` objects. +* Added an `xarray `_ interface allowing use of `windspharm` with `xarray.DataArray` objects. * Fixed a bug in the identification of Gaussian grids in the iris interface. * Fixed a bug where the `truncate` method would not work on inverted latitude grids in the iris interface. diff --git a/docs/conf.py b/docs/conf.py index c895ab4..6c4e7c3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -30,10 +30,12 @@ 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', - 'sphinx.ext.extlinks', 'matplotlib.sphinxext.plot_directive', + 'sphinx_issues' ] +issues_github_path = "ajdawson/windspharm" + # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -62,7 +64,7 @@ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +language = "en" # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: @@ -95,13 +97,6 @@ #modindex_common_prefix = [] -# -- extlinks configuration ---------------------------------------------------- - -# Allow e.g. :issue:`42` and :pr:`42` roles: -extlinks = {'issue': ('https://github.com/ajdawson/windspharm/issues/%s', '#'), - 'pr': ('https://github.com/ajdawson/windspharm/pull/%s', '#')} - - # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for @@ -186,9 +181,9 @@ # Options for intersphinx. intersphinx_mapping = { - 'iris': ('http://scitools.org.uk/iris/docs/latest', None), - 'numpy': ('http://docs.scipy.org/doc/numpy', None), - 'xarray': ('http://xarray.pydata.org/en/stable', None) + 'iris': ('https://scitools-iris.readthedocs.io/en/latest', None), + 'numpy': ('https://numpy.org/doc/stable', None), + 'xarray': ('https://docs.xarray.dev/en/stable', None) } diff --git a/docs/devguide/gitwash/branch_dropdown.png b/docs/devguide/gitwash/branch_dropdown.png deleted file mode 100644 index 1bb7a57..0000000 Binary files a/docs/devguide/gitwash/branch_dropdown.png and /dev/null differ diff --git a/docs/devguide/gitwash/configure_git.rst b/docs/devguide/gitwash/configure_git.rst deleted file mode 100644 index f8a005f..0000000 --- a/docs/devguide/gitwash/configure_git.rst +++ /dev/null @@ -1,158 +0,0 @@ -.. _configure-git: - -=============== - Configure git -=============== - -.. _git-config-basic: - -Overview -======== - -Your personal git configurations are saved in the ``.gitconfig`` file in -your home directory. - -Here is an example ``.gitconfig`` file:: - - [user] - name = Your Name - email = you@yourdomain.example.com - - [alias] - ci = commit -a - co = checkout - st = status - stat = status - br = branch - wdiff = diff --color-words - - [core] - editor = vim - - [merge] - summary = true - -You can edit this file directly or you can use the ``git config --global`` -command:: - - git config --global user.name "Your Name" - git config --global user.email you@yourdomain.example.com - git config --global alias.ci "commit -a" - git config --global alias.co checkout - git config --global alias.st "status -a" - git config --global alias.stat "status -a" - git config --global alias.br branch - git config --global alias.wdiff "diff --color-words" - git config --global core.editor vim - git config --global merge.summary true - -To set up on another computer, you can copy your ``~/.gitconfig`` file, -or run the commands above. - -In detail -========= - -user.name and user.email ------------------------- - -It is good practice to tell git_ who you are, for labeling any changes -you make to the code. The simplest way to do this is from the command -line:: - - git config --global user.name "Your Name" - git config --global user.email you@yourdomain.example.com - -This will write the settings into your git configuration file, which -should now contain a user section with your name and email:: - - [user] - name = Your Name - email = you@yourdomain.example.com - -Of course you'll need to replace ``Your Name`` and ``you@yourdomain.example.com`` -with your actual name and email address. - -Aliases -------- - -You might well benefit from some aliases to common commands. - -For example, you might well want to be able to shorten ``git checkout`` -to ``git co``. Or you may want to alias ``git diff --color-words`` -(which gives a nicely formatted output of the diff) to ``git wdiff`` - -The following ``git config --global`` commands:: - - git config --global alias.ci "commit -a" - git config --global alias.co checkout - git config --global alias.st "status -a" - git config --global alias.stat "status -a" - git config --global alias.br branch - git config --global alias.wdiff "diff --color-words" - -will create an ``alias`` section in your ``.gitconfig`` file with contents -like this:: - - [alias] - ci = commit -a - co = checkout - st = status -a - stat = status -a - br = branch - wdiff = diff --color-words - -Editor ------- - -You may also want to make sure that your editor of choice is used :: - - git config --global core.editor vim - -Merging -------- - -To enforce summaries when doing merges (``~/.gitconfig`` file again):: - - [merge] - log = true - -Or from the command line:: - - git config --global merge.log true - -.. _fancy-log: - -Fancy log output ----------------- - -This is a very nice alias to get a fancy log output; it should go in the -``alias`` section of your ``.gitconfig`` file:: - - lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)[%an]%Creset' --abbrev-commit --date=relative - -You use the alias with:: - - git lg - -and it gives graph / text output something like this (but with color!):: - - * 6d8e1ee - (HEAD, origin/my-fancy-feature, my-fancy-feature) NF - a fancy file (45 minutes ago) [Matthew Brett] - * d304a73 - (origin/placeholder, placeholder) Merge pull request #48 from hhuuggoo/master (2 weeks ago) [Jonathan Terhorst] - |\ - | * 4aff2a8 - fixed bug 35, and added a test in test_bugfixes (2 weeks ago) [Hugo] - |/ - * a7ff2e5 - Added notes on discussion/proposal made during Data Array Summit. (2 weeks ago) [Corran Webster] - * 68f6752 - Initial implimentation of AxisIndexer - uses 'index_by' which needs to be changed to a call on an Axes object - this is all very sketchy right now. (2 weeks ago) [Corr - * 376adbd - Merge pull request #46 from terhorst/master (2 weeks ago) [Jonathan Terhorst] - |\ - | * b605216 - updated joshu example to current api (3 weeks ago) [Jonathan Terhorst] - | * 2e991e8 - add testing for outer ufunc (3 weeks ago) [Jonathan Terhorst] - | * 7beda5a - prevent axis from throwing an exception if testing equality with non-axis object (3 weeks ago) [Jonathan Terhorst] - | * 65af65e - convert unit testing code to assertions (3 weeks ago) [Jonathan Terhorst] - | * 956fbab - Merge remote-tracking branch 'upstream/master' (3 weeks ago) [Jonathan Terhorst] - | |\ - | |/ - -Thanks to Yury V. Zaytsev for posting it. - -.. include:: links.inc diff --git a/docs/devguide/gitwash/development_workflow.rst b/docs/devguide/gitwash/development_workflow.rst deleted file mode 100644 index eabebd6..0000000 --- a/docs/devguide/gitwash/development_workflow.rst +++ /dev/null @@ -1,414 +0,0 @@ -.. _development-workflow: - -#################### -Development workflow -#################### - -You already have your own forked copy of the `windspharm`_ repository, by -following :ref:`forking`. You have :ref:`set-up-fork`. You have configured -git by following :ref:`configure-git`. Now you are ready for some real work. - -Workflow summary -================ - -In what follows we'll refer to the upstream windspharm ``master`` branch, as -"trunk". - -* Don't use your ``master`` branch for anything. Consider deleting it. -* When you are starting a new set of changes, fetch any changes from trunk, - and start a new *feature branch* from that. -* Make a new branch for each separable set of changes |emdash| "one task, one - branch" (`ipython git workflow`_). -* Name your branch for the purpose of the changes - e.g. - ``bugfix-for-issue-14`` or ``refactor-database-code``. -* If you can possibly avoid it, avoid merging trunk or any other branches into - your feature branch while you are working. -* If you do find yourself merging from trunk, consider :ref:`rebase-on-trunk` -* Ask for code review! - -This way of working helps to keep work well organized, with readable history. -This in turn makes it easier for project maintainers (that might be you) to see -what you've done, and why you did it. - -See `linux git workflow`_ and `ipython git workflow`_ for some explanation. - -Consider deleting your master branch -==================================== - -It may sound strange, but deleting your own ``master`` branch can help reduce -confusion about which branch you are on. See `deleting master on github`_ for -details. - -.. _update-mirror-trunk: - -Update the mirror of trunk -========================== - -First make sure you have done :ref:`linking-to-upstream`. - -From time to time you should fetch the upstream (trunk) changes from github:: - - git fetch upstream - -This will pull down any commits you don't have, and set the remote branches to -point to the right commit. For example, 'trunk' is the branch referred to by -(remote/branchname) ``upstream/master`` - and if there have been commits since -you last checked, ``upstream/master`` will change after you do the fetch. - -.. _make-feature-branch: - -Make a new feature branch -========================= - -When you are ready to make some changes to the code, you should start a new -branch. Branches that are for a collection of related edits are often called -'feature branches'. - -Making an new branch for each set of related changes will make it easier for -someone reviewing your branch to see what you are doing. - -Choose an informative name for the branch to remind yourself and the rest of us -what the changes in the branch are for. For example ``add-ability-to-fly``, or -``buxfix-for-issue-42``. - -:: - - # Update the mirror of trunk - git fetch upstream - # Make new feature branch starting at current trunk - git branch my-new-feature upstream/master - git checkout my-new-feature - -Generally, you will want to keep your feature branches on your public github_ -fork of `windspharm`_. To do this, you `git push`_ this new branch up to your -github repo. Generally (if you followed the instructions in these pages, and by -default), git will have a link to your github repo, called ``origin``. You push -up to your own repo on github with:: - - git push origin my-new-feature - -In git >= 1.7 you can ensure that the link is correctly set by using the -``--set-upstream`` option:: - - git push --set-upstream origin my-new-feature - -From now on git will know that ``my-new-feature`` is related to the -``my-new-feature`` branch in the github repo. - -.. _edit-flow: - -The editing workflow -==================== - -Overview --------- - -:: - - # hack hack - git add my_new_file - git commit -am 'NF - some message' - git push - -In more detail --------------- - -#. Make some changes -#. See which files have changed with ``git status`` (see `git status`_). - You'll see a listing like this one:: - - # On branch ny-new-feature - # Changed but not updated: - # (use "git add ..." to update what will be committed) - # (use "git checkout -- ..." to discard changes in working directory) - # - # modified: README - # - # Untracked files: - # (use "git add ..." to include in what will be committed) - # - # INSTALL - no changes added to commit (use "git add" and/or "git commit -a") - -#. Check what the actual changes are with ``git diff`` (`git diff`_). -#. Add any new files to version control ``git add new_file_name`` (see - `git add`_). -#. To commit all modified files into the local copy of your repo,, do - ``git commit -am 'A commit message'``. Note the ``-am`` options to - ``commit``. The ``m`` flag just signals that you're going to type a - message on the command line. The ``a`` flag |emdash| you can just take on - faith |emdash| or see `why the -a flag?`_ |emdash| and the helpful use-case - description in the `tangled working copy problem`_. The `git commit`_ manual - page might also be useful. -#. To push the changes up to your forked repo on github, do a ``git - push`` (see `git push`_). - -Ask for your changes to be reviewed or merged -============================================= - -When you are ready to ask for someone to review your code and consider a merge: - -#. Go to the URL of your forked repo, say - ``http://github.com/your-user-name/windspharm``. -#. Use the 'Switch Branches' dropdown menu near the top left of the page to - select the branch with your changes: - - .. image:: branch_dropdown.png - -#. Click on the 'Pull request' button: - - .. image:: pull_button.png - - Enter a title for the set of changes, and some explanation of what you've - done. Say if there is anything you'd like particular attention for - like a - complicated change or some code you are not happy with. - - If you don't think your request is ready to be merged, just say so in your - pull request message. This is still a good way of getting some preliminary - code review. - -Some other things you might want to do -====================================== - -Delete a branch on github -------------------------- - -:: - - git checkout master - # delete branch locally - git branch -D my-unwanted-branch - # delete branch on github - git push origin :my-unwanted-branch - -(Note the colon ``:`` before ``test-branch``. See also: -http://github.com/guides/remove-a-remote-branch - -Several people sharing a single repository ------------------------------------------- - -If you want to work on some stuff with other people, where you are all -committing into the same repository, or even the same branch, then just -share it via github. - -First fork windspharm into your account, as from :ref:`forking`. - -Then, go to your forked repository github page, say -``http://github.com/your-user-name/windspharm`` - -Click on the 'Admin' button, and add anyone else to the repo as a -collaborator: - - .. image:: pull_button.png - -Now all those people can do:: - - git clone git@githhub.com:your-user-name/windspharm.git - -Remember that links starting with ``git@`` use the ssh protocol and are -read-write; links starting with ``git://`` are read-only. - -Your collaborators can then commit directly into that repo with the -usual:: - - git commit -am 'ENH - much better code' - git push origin master # pushes directly into your repo - -Explore your repository ------------------------ - -To see a graphical representation of the repository branches and -commits:: - - gitk --all - -To see a linear list of commits for this branch:: - - git log - -You can also look at the `network graph visualizer`_ for your github -repo. - -Finally the :ref:`fancy-log` ``lg`` alias will give you a reasonable text-based -graph of the repository. - -.. _rebase-on-trunk: - -Rebasing on trunk ------------------ - -Let's say you thought of some work you'd like to do. You -:ref:`update-mirror-trunk` and :ref:`make-feature-branch` called -``cool-feature``. At this stage trunk is at some commit, let's call it E. Now -you make some new commits on your ``cool-feature`` branch, let's call them A, B, -C. Maybe your changes take a while, or you come back to them after a while. In -the meantime, trunk has progressed from commit E to commit (say) G:: - - A---B---C cool-feature - / - D---E---F---G trunk - -At this stage you consider merging trunk into your feature branch, and you -remember that this here page sternly advises you not to do that, because the -history will get messy. Most of the time you can just ask for a review, and not -worry that trunk has got a little ahead. But sometimes, the changes in trunk -might affect your changes, and you need to harmonize them. In this situation -you may prefer to do a rebase. - -rebase takes your changes (A, B, C) and replays them as if they had been made to -the current state of ``trunk``. In other words, in this case, it takes the -changes represented by A, B, C and replays them on top of G. After the rebase, -your history will look like this:: - - A'--B'--C' cool-feature - / - D---E---F---G trunk - -See `rebase without tears`_ for more detail. - -To do a rebase on trunk:: - - # Update the mirror of trunk - git fetch upstream - # go to the feature branch - git checkout cool-feature - # make a backup in case you mess up - git branch tmp cool-feature - # rebase cool-feature onto trunk - git rebase --onto upstream/master upstream/master cool-feature - -In this situation, where you are already on branch ``cool-feature``, the last -command can be written more succinctly as:: - - git rebase upstream/master - -When all looks good you can delete your backup branch:: - - git branch -D tmp - -If it doesn't look good you may need to have a look at -:ref:`recovering-from-mess-up`. - -If you have made changes to files that have also changed in trunk, this may -generate merge conflicts that you need to resolve - see the `git rebase`_ man -page for some instructions at the end of the "Description" section. There is -some related help on merging in the git user manual - see `resolving a merge`_. - -.. _recovering-from-mess-up: - -Recovering from mess-ups ------------------------- - -Sometimes, you mess up merges or rebases. Luckily, in git it is -relatively straightforward to recover from such mistakes. - -If you mess up during a rebase:: - - git rebase --abort - -If you notice you messed up after the rebase:: - - # reset branch back to the saved point - git reset --hard tmp - -If you forgot to make a backup branch:: - - # look at the reflog of the branch - git reflog show cool-feature - - 8630830 cool-feature@{0}: commit: BUG: io: close file handles immediately - 278dd2a cool-feature@{1}: rebase finished: refs/heads/my-feature-branch onto 11ee694744f2552d - 26aa21a cool-feature@{2}: commit: BUG: lib: make seek_gzip_factory not leak gzip obj - ... - - # reset the branch to where it was before the botched rebase - git reset --hard cool-feature@{2} - -.. _rewriting-commit-history: - -Rewriting commit history ------------------------- - -.. note:: - - Do this only for your own feature branches. - -There's an embarrassing typo in a commit you made? Or perhaps the you -made several false starts you would like the posterity not to see. - -This can be done via *interactive rebasing*. - -Suppose that the commit history looks like this:: - - git log --oneline - eadc391 Fix some remaining bugs - a815645 Modify it so that it works - 2dec1ac Fix a few bugs + disable - 13d7934 First implementation - 6ad92e5 * masked is now an instance of a new object, MaskedConstant - 29001ed Add pre-nep for a copule of structured_array_extensions. - ... - -and ``6ad92e5`` is the last commit in the ``cool-feature`` branch. Suppose we -want to make the following changes: - -* Rewrite the commit message for ``13d7934`` to something more sensible. -* Combine the commits ``2dec1ac``, ``a815645``, ``eadc391`` into a single one. - -We do as follows:: - - # make a backup of the current state - git branch tmp HEAD - # interactive rebase - git rebase -i 6ad92e5 - -This will open an editor with the following text in it:: - - pick 13d7934 First implementation - pick 2dec1ac Fix a few bugs + disable - pick a815645 Modify it so that it works - pick eadc391 Fix some remaining bugs - - # Rebase 6ad92e5..eadc391 onto 6ad92e5 - # - # Commands: - # p, pick = use commit - # r, reword = use commit, but edit the commit message - # e, edit = use commit, but stop for amending - # s, squash = use commit, but meld into previous commit - # f, fixup = like "squash", but discard this commit's log message - # - # If you remove a line here THAT COMMIT WILL BE LOST. - # However, if you remove everything, the rebase will be aborted. - # - -To achieve what we want, we will make the following changes to it:: - - r 13d7934 First implementation - pick 2dec1ac Fix a few bugs + disable - f a815645 Modify it so that it works - f eadc391 Fix some remaining bugs - -This means that (i) we want to edit the commit message for -``13d7934``, and (ii) collapse the last three commits into one. Now we -save and quit the editor. - -Git will then immediately bring up an editor for editing the commit -message. After revising it, we get the output:: - - [detached HEAD 721fc64] FOO: First implementation - 2 files changed, 199 insertions(+), 66 deletions(-) - [detached HEAD 0f22701] Fix a few bugs + disable - 1 files changed, 79 insertions(+), 61 deletions(-) - Successfully rebased and updated refs/heads/my-feature-branch. - -and the history looks now like this:: - - 0f22701 Fix a few bugs + disable - 721fc64 ENH: Sophisticated feature - 6ad92e5 * masked is now an instance of a new object, MaskedConstant - -If it went wrong, recovery is again possible as explained :ref:`above -`. - -.. include:: links.inc diff --git a/docs/devguide/gitwash/following_latest.rst b/docs/devguide/gitwash/following_latest.rst deleted file mode 100644 index c3f1580..0000000 --- a/docs/devguide/gitwash/following_latest.rst +++ /dev/null @@ -1,36 +0,0 @@ -.. _following-latest: - -============================= - Following the latest source -============================= - -These are the instructions if you just want to follow the latest -*windspharm* source, but you don't need to do any development for now. - -The steps are: - -* :ref:`install-git` -* get local copy of the `windspharm github`_ git repository -* update local copy from time to time - -Get the local copy of the code -============================== - -From the command line:: - - git clone git://github.com/ajdawson/windspharm.git - -You now have a copy of the code tree in the new ``windspharm`` directory. - -Updating the code -================= - -From time to time you may want to pull down the latest code. Do this with:: - - cd windspharm - git pull - -The tree in ``windspharm`` will now have the latest changes from the initial -repository. - -.. include:: links.inc diff --git a/docs/devguide/gitwash/forking_button.png b/docs/devguide/gitwash/forking_button.png deleted file mode 100644 index d0e0413..0000000 Binary files a/docs/devguide/gitwash/forking_button.png and /dev/null differ diff --git a/docs/devguide/gitwash/forking_hell.rst b/docs/devguide/gitwash/forking_hell.rst deleted file mode 100644 index 5c1ab91..0000000 --- a/docs/devguide/gitwash/forking_hell.rst +++ /dev/null @@ -1,32 +0,0 @@ -.. _forking: - -====================================================== -Making your own copy (fork) of windspharm -====================================================== - -You need to do this only once. The instructions here are very similar -to the instructions at http://help.github.com/forking/ |emdash| please see -that page for more detail. We're repeating some of it here just to give the -specifics for the `windspharm`_ project, and to suggest some default names. - -Set up and configure a github account -===================================== - -If you don't have a github account, go to the github page, and make one. - -You then need to configure your account to allow write access |emdash| see -the ``Generating SSH keys`` help on `github help`_. - -Create your own forked copy of `windspharm`_ -====================================================== - -#. Log into your github account. -#. Go to the `windspharm`_ github home at `windspharm github`_. -#. Click on the *fork* button: - - .. image:: forking_button.png - - Now, after a short pause and some 'Hardcore forking action', you - should find yourself at the home page for your own forked copy of `windspharm`_. - -.. include:: links.inc diff --git a/docs/devguide/gitwash/git_development.rst b/docs/devguide/gitwash/git_development.rst deleted file mode 100644 index c5b910d..0000000 --- a/docs/devguide/gitwash/git_development.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. _git-development: - -===================== - Git for development -===================== - -Contents: - -.. toctree:: - :maxdepth: 2 - - forking_hell - set_up_fork - configure_git - development_workflow - maintainer_workflow diff --git a/docs/devguide/gitwash/git_install.rst b/docs/devguide/gitwash/git_install.rst deleted file mode 100644 index 3be5149..0000000 --- a/docs/devguide/gitwash/git_install.rst +++ /dev/null @@ -1,26 +0,0 @@ -.. _install-git: - -============= - Install git -============= - -Overview -======== - -================ ============= -Debian / Ubuntu ``sudo apt-get install git`` -Fedora ``sudo yum install git`` -Windows Download and install msysGit_ -OS X Use the git-osx-installer_ -================ ============= - -In detail -========= - -See the git page for the most recent information. - -Have a look at the github install help pages available from `github help`_ - -There are good instructions here: http://book.git-scm.com/2_installing_git.html - -.. include:: links.inc diff --git a/docs/devguide/gitwash/git_intro.rst b/docs/devguide/gitwash/git_intro.rst deleted file mode 100644 index 7db64b4..0000000 --- a/docs/devguide/gitwash/git_intro.rst +++ /dev/null @@ -1,18 +0,0 @@ -============== - Introduction -============== - -These pages describe a git_ and github_ workflow for the `windspharm`_ -project. - -There are several different workflows here, for different ways of -working with *windspharm*. - -This is not a comprehensive git reference, it's just a workflow for our -own project. It's tailored to the github hosting service. You may well -find better or quicker ways of getting stuff done with git, but these -should get you started. - -For general resources for learning git, see :ref:`git-resources`. - -.. include:: links.inc diff --git a/docs/devguide/gitwash/git_links.inc b/docs/devguide/gitwash/git_links.inc deleted file mode 100644 index 82a72dd..0000000 --- a/docs/devguide/gitwash/git_links.inc +++ /dev/null @@ -1,61 +0,0 @@ -.. This (-*- rst -*-) format file contains commonly used link targets - and name substitutions. It may be included in many files, - therefore it should only contain link targets and name - substitutions. Try grepping for "^\.\. _" to find plausible - candidates for this list. - -.. NOTE: reST targets are - __not_case_sensitive__, so only one target definition is needed for - nipy, NIPY, Nipy, etc... - -.. git stuff -.. _git: http://git-scm.com/ -.. _github: http://github.com -.. _github help: http://help.github.com -.. _msysgit: http://code.google.com/p/msysgit/downloads/list -.. _git-osx-installer: http://code.google.com/p/git-osx-installer/downloads/list -.. _subversion: http://subversion.tigris.org/ -.. _git cheat sheet: http://github.com/guides/git-cheat-sheet -.. _pro git book: http://progit.org/ -.. _git svn crash course: http://git-scm.com/course/svn.html -.. _learn.github: http://learn.github.com/ -.. _network graph visualizer: http://github.com/blog/39-say-hello-to-the-network-graph-visualizer -.. _git user manual: http://schacon.github.com/git/user-manual.html -.. _git tutorial: http://schacon.github.com/git/gittutorial.html -.. _git community book: http://book.git-scm.com/ -.. _git ready: http://www.gitready.com/ -.. _git casts: http://www.gitcasts.com/ -.. _Fernando's git page: http://www.fperez.org/py4science/git.html -.. _git magic: http://www-cs-students.stanford.edu/~blynn/gitmagic/index.html -.. _git concepts: http://www.eecs.harvard.edu/~cduan/technical/git/ -.. _git clone: http://schacon.github.com/git/git-clone.html -.. _git checkout: http://schacon.github.com/git/git-checkout.html -.. _git commit: http://schacon.github.com/git/git-commit.html -.. _git push: http://schacon.github.com/git/git-push.html -.. _git pull: http://schacon.github.com/git/git-pull.html -.. _git add: http://schacon.github.com/git/git-add.html -.. _git status: http://schacon.github.com/git/git-status.html -.. _git diff: http://schacon.github.com/git/git-diff.html -.. _git log: http://schacon.github.com/git/git-log.html -.. _git branch: http://schacon.github.com/git/git-branch.html -.. _git remote: http://schacon.github.com/git/git-remote.html -.. _git rebase: http://schacon.github.com/git/git-rebase.html -.. _git config: http://schacon.github.com/git/git-config.html -.. _why the -a flag?: http://www.gitready.com/beginner/2009/01/18/the-staging-area.html -.. _git staging area: http://www.gitready.com/beginner/2009/01/18/the-staging-area.html -.. _tangled working copy problem: http://tomayko.com/writings/the-thing-about-git -.. _git management: http://kerneltrap.org/Linux/Git_Management -.. _linux git workflow: http://www.mail-archive.com/dri-devel@lists.sourceforge.net/msg39091.html -.. _git parable: http://tom.preston-werner.com/2009/05/19/the-git-parable.html -.. _git foundation: http://matthew-brett.github.com/pydagogue/foundation.html -.. _deleting master on github: http://matthew-brett.github.com/pydagogue/gh_delete_master.html -.. _rebase without tears: http://matthew-brett.github.com/pydagogue/rebase_without_tears.html -.. _resolving a merge: http://schacon.github.com/git/user-manual.html#resolving-a-merge -.. _ipython git workflow: http://mail.scipy.org/pipermail/ipython-dev/2010-October/006746.html - -.. other stuff -.. _python: http://www.python.org - -.. |emdash| unicode:: U+02014 - -.. vim: ft=rst diff --git a/docs/devguide/gitwash/git_resources.rst b/docs/devguide/gitwash/git_resources.rst deleted file mode 100644 index d18b0ef..0000000 --- a/docs/devguide/gitwash/git_resources.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. _git-resources: - -============= -git resources -============= - -Tutorials and summaries -======================= - -* `github help`_ has an excellent series of how-to guides. -* `learn.github`_ has an excellent series of tutorials -* The `pro git book`_ is a good in-depth book on git. -* A `git cheat sheet`_ is a page giving summaries of common commands. -* The `git user manual`_ -* The `git tutorial`_ -* The `git community book`_ -* `git ready`_ |emdash| a nice series of tutorials -* `git casts`_ |emdash| video snippets giving git how-tos. -* `git magic`_ |emdash| extended introduction with intermediate detail -* The `git parable`_ is an easy read explaining the concepts behind git. -* `git foundation`_ expands on the `git parable`_. -* Fernando Perez' git page |emdash| `Fernando's git page`_ |emdash| many - links and tips -* A good but technical page on `git concepts`_ -* `git svn crash course`_: git for those of us used to subversion_ - -Advanced git workflow -===================== - -There are many ways of working with git; here are some posts on the -rules of thumb that other projects have come up with: - -* Linus Torvalds on `git management`_ -* Linus Torvalds on `linux git workflow`_ . Summary; use the git tools - to make the history of your edits as clean as possible; merge from - upstream edits as little as possible in branches where you are doing - active development. - -Manual pages online -=================== - -You can get these on your own machine with (e.g) ``git help push`` or -(same thing) ``git push --help``, but, for convenience, here are the -online manual pages for some common commands: - -* `git add`_ -* `git branch`_ -* `git checkout`_ -* `git clone`_ -* `git commit`_ -* `git config`_ -* `git diff`_ -* `git log`_ -* `git pull`_ -* `git push`_ -* `git remote`_ -* `git status`_ - -.. include:: links.inc diff --git a/docs/devguide/gitwash/index.rst b/docs/devguide/gitwash/index.rst deleted file mode 100644 index 8bbc0f4..0000000 --- a/docs/devguide/gitwash/index.rst +++ /dev/null @@ -1,15 +0,0 @@ -.. _using-git: - -Working with *windspharm* source code -================================================ - -Contents: - -.. toctree:: - :maxdepth: 2 - - git_intro - git_install - following_latest - git_development - git_resources diff --git a/docs/devguide/gitwash/known_projects.inc b/docs/devguide/gitwash/known_projects.inc deleted file mode 100644 index 1761d97..0000000 --- a/docs/devguide/gitwash/known_projects.inc +++ /dev/null @@ -1,41 +0,0 @@ -.. Known projects - -.. PROJECTNAME placeholders -.. _PROJECTNAME: http://nipy.org -.. _`PROJECTNAME github`: https://github.com/nipy -.. _`PROJECTNAME mailing list`: https://mail.python.org/mailman/listinfo/neuroimaging - -.. numpy -.. _numpy: http://www.numpy.org -.. _`numpy github`: https://github.com/numpy/numpy -.. _`numpy mailing list`: http://mail.scipy.org/mailman/listinfo/numpy-discussion - -.. scipy -.. _scipy: https://www.scipy.org -.. _`scipy github`: https://github.com/scipy/scipy -.. _`scipy mailing list`: http://mail.scipy.org/mailman/listinfo/scipy-dev - -.. nipy -.. _nipy: http://nipy.org/nipy -.. _`nipy github`: https://github.com/nipy/nipy -.. _`nipy mailing list`: https://mail.python.org/mailman/listinfo/neuroimaging - -.. ipython -.. _ipython: https://ipython.org -.. _`ipython github`: https://github.com/ipython/ipython -.. _`ipython mailing list`: http://mail.scipy.org/mailman/listinfo/IPython-dev - -.. dipy -.. _dipy: http://nipy.org/dipy -.. _`dipy github`: https://github.com/Garyfallidis/dipy -.. _`dipy mailing list`: https://mail.python.org/mailman/listinfo/neuroimaging - -.. nibabel -.. _nibabel: http://nipy.org/nibabel -.. _`nibabel github`: https://github.com/nipy/nibabel -.. _`nibabel mailing list`: https://mail.python.org/mailman/listinfo/neuroimaging - -.. marsbar -.. _marsbar: http://marsbar.sourceforge.net -.. _`marsbar github`: https://github.com/matthew-brett/marsbar -.. _`MarsBaR mailing list`: https://lists.sourceforge.net/lists/listinfo/marsbar-users diff --git a/docs/devguide/gitwash/links.inc b/docs/devguide/gitwash/links.inc deleted file mode 100644 index 20f4dcf..0000000 --- a/docs/devguide/gitwash/links.inc +++ /dev/null @@ -1,4 +0,0 @@ -.. compiling links file -.. include:: known_projects.inc -.. include:: this_project.inc -.. include:: git_links.inc diff --git a/docs/devguide/gitwash/maintainer_workflow.rst b/docs/devguide/gitwash/maintainer_workflow.rst deleted file mode 100644 index 345824d..0000000 --- a/docs/devguide/gitwash/maintainer_workflow.rst +++ /dev/null @@ -1,96 +0,0 @@ -.. _maintainer-workflow: - -################### -Maintainer workflow -################### - -This page is for maintainers |emdash| those of us who merge our own or other -peoples' changes into the upstream repository. - -Being as how you're a maintainer, you are completely on top of the basic stuff -in :ref:`development-workflow`. - -The instructions in :ref:`linking-to-upstream` add a remote that has read-only -access to the upstream repo. Being a maintainer, you've got read-write access. - -It's good to have your upstream remote have a scary name, to remind you that -it's a read-write remote:: - - git remote add upstream-rw git@github.com:ajdawson/windspharm.git - git fetch upstream-rw - -******************* -Integrating changes -******************* - -Let's say you have some changes that need to go into trunk -(``upstream-rw/master``). - -The changes are in some branch that you are currently on. For example, you are -looking at someone's changes like this:: - - git remote add someone git://github.com/someone/windspharm.git - git fetch someone - git branch cool-feature --track someone/cool-feature - git checkout cool-feature - -So now you are on the branch with the changes to be incorporated upstream. The -rest of this section assumes you are on this branch. - -A few commits -============= - -If there are only a few commits, consider rebasing to upstream:: - - # Fetch upstream changes - git fetch upstream-rw - # rebase - git rebase upstream-rw/master - -Remember that, if you do a rebase, and push that, you'll have to close any -github pull requests manually, because github will not be able to detect the -changes have already been merged. - -A long series of commits -======================== - -If there are a longer series of related commits, consider a merge instead:: - - git fetch upstream-rw - git merge --no-ff upstream-rw/master - -The merge will be detected by github, and should close any related pull requests -automatically. - -Note the ``--no-ff`` above. This forces git to make a merge commit, rather than -doing a fast-forward, so that these set of commits branch off trunk then rejoin -the main history with a merge, rather than appearing to have been made directly -on top of trunk. - -Check the history -================= - -Now, in either case, you should check that the history is sensible and you have -the right commits:: - - git log --oneline --graph - git log -p upstream-rw/master.. - -The first line above just shows the history in a compact way, with a text -representation of the history graph. The second line shows the log of commits -excluding those that can be reached from trunk (``upstream-rw/master``), and -including those that can be reached from current HEAD (implied with the ``..`` -at the end). So, it shows the commits unique to this branch compared to trunk. -The ``-p`` option shows the diff for these commits in patch form. - -Push to trunk -============= - -:: - - git push upstream-rw my-new-feature:master - -This pushes the ``my-new-feature`` branch in this repository to the ``master`` -branch in the ``upstream-rw`` repository. - -.. include:: links.inc diff --git a/docs/devguide/gitwash/pull_button.png b/docs/devguide/gitwash/pull_button.png deleted file mode 100644 index e503168..0000000 Binary files a/docs/devguide/gitwash/pull_button.png and /dev/null differ diff --git a/docs/devguide/gitwash/set_up_fork.rst b/docs/devguide/gitwash/set_up_fork.rst deleted file mode 100644 index 23877ea..0000000 --- a/docs/devguide/gitwash/set_up_fork.rst +++ /dev/null @@ -1,67 +0,0 @@ -.. _set-up-fork: - -================== - Set up your fork -================== - -First you follow the instructions for :ref:`forking`. - -Overview -======== - -:: - - git clone git@github.com:your-user-name/windspharm.git - cd windspharm - git remote add upstream git://github.com/ajdawson/windspharm.git - -In detail -========= - -Clone your fork ---------------- - -#. Clone your fork to the local computer with ``git clone - git@github.com:your-user-name/windspharm.git`` -#. Investigate. Change directory to your new repo: ``cd windspharm``. Then - ``git branch -a`` to show you all branches. You'll get something - like:: - - * master - remotes/origin/master - - This tells you that you are currently on the ``master`` branch, and - that you also have a ``remote`` connection to ``origin/master``. - What remote repository is ``remote/origin``? Try ``git remote -v`` to - see the URLs for the remote. They will point to your github fork. - - Now you want to connect to the upstream `windspharm github`_ repository, so - you can merge in changes from trunk. - -.. _linking-to-upstream: - -Linking your repository to the upstream repo --------------------------------------------- - -:: - - cd windspharm - git remote add upstream git://github.com/ajdawson/windspharm.git - -``upstream`` here is just the arbitrary name we're using to refer to the -main `windspharm`_ repository at `windspharm github`_. - -Note that we've used ``git://`` for the URL rather than ``git@``. The -``git://`` URL is read only. This means we that we can't accidentally -(or deliberately) write to the upstream repo, and we are only going to -use it to merge into our own code. - -Just for your own satisfaction, show yourself that you now have a new -'remote', with ``git remote -v show``, giving you something like:: - - upstream git://github.com/ajdawson/windspharm.git (fetch) - upstream git://github.com/ajdawson/windspharm.git (push) - origin git@github.com:your-user-name/windspharm.git (fetch) - origin git@github.com:your-user-name/windspharm.git (push) - -.. include:: links.inc diff --git a/docs/devguide/gitwash/this_project.inc b/docs/devguide/gitwash/this_project.inc deleted file mode 100644 index 5617ba5..0000000 --- a/docs/devguide/gitwash/this_project.inc +++ /dev/null @@ -1,3 +0,0 @@ -.. windspharm -.. _`windspharm`: http://ajdawson.github.io/windspharm -.. _`windspharm github`: http://github.com/ajdawson/windspharm diff --git a/docs/devguide/gitwash_dumper.py b/docs/devguide/gitwash_dumper.py deleted file mode 100644 index ad431ff..0000000 --- a/docs/devguide/gitwash_dumper.py +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env python -''' Checkout gitwash repo into directory and do search replace on name ''' - -from __future__ import (absolute_import, division, print_function) - -import os -from os.path import join as pjoin -import shutil -import sys -import re -import glob -import fnmatch -import tempfile -from subprocess import call -from optparse import OptionParser - -verbose = False - - -def clone_repo(url, branch): - cwd = os.getcwd() - tmpdir = tempfile.mkdtemp() - try: - cmd = 'git clone %s %s' % (url, tmpdir) - call(cmd, shell=True) - os.chdir(tmpdir) - cmd = 'git checkout %s' % branch - call(cmd, shell=True) - except: - shutil.rmtree(tmpdir) - raise - finally: - os.chdir(cwd) - return tmpdir - - -def cp_files(in_path, globs, out_path): - try: - os.makedirs(out_path) - except OSError: - pass - out_fnames = [] - for in_glob in globs: - in_glob_path = pjoin(in_path, in_glob) - for in_fname in glob.glob(in_glob_path): - out_fname = in_fname.replace(in_path, out_path) - pth, _ = os.path.split(out_fname) - if not os.path.isdir(pth): - os.makedirs(pth) - shutil.copyfile(in_fname, out_fname) - out_fnames.append(out_fname) - return out_fnames - - -def filename_search_replace(sr_pairs, filename, backup=False): - ''' Search and replace for expressions in files - - ''' - with open(filename, 'rt') as in_fh: - in_txt = in_fh.read(-1) - out_txt = in_txt[:] - for in_exp, out_exp in sr_pairs: - in_exp = re.compile(in_exp) - out_txt = in_exp.sub(out_exp, out_txt) - if in_txt == out_txt: - return False - with open(filename, 'wt') as out_fh: - out_fh.write(out_txt) - if backup: - with open(filename + '.bak', 'wt') as bak_fh: - bak_fh.write(in_txt) - return True - - -def copy_replace(replace_pairs, - repo_path, - out_path, - cp_globs=('*',), - rep_globs=('*',), - renames = ()): - out_fnames = cp_files(repo_path, cp_globs, out_path) - renames = [(re.compile(in_exp), out_exp) for in_exp, out_exp in renames] - fnames = [] - for rep_glob in rep_globs: - fnames += fnmatch.filter(out_fnames, rep_glob) - if verbose: - print('\n'.join(fnames)) - for fname in fnames: - filename_search_replace(replace_pairs, fname, False) - for in_exp, out_exp in renames: - new_fname, n = in_exp.subn(out_exp, fname) - if n: - os.rename(fname, new_fname) - break - - -def make_link_targets(proj_name, - user_name, - repo_name, - known_link_fname, - out_link_fname, - url=None, - ml_url=None): - """ Check and make link targets - - If url is None or ml_url is None, check if there are links present for these - in `known_link_fname`. If not, raise error. The check is: - - Look for a target `proj_name`. - Look for a target `proj_name` + ' mailing list' - - Also, look for a target `proj_name` + 'github'. If this exists, don't write - this target into the new file below. - - If we are writing any of the url, ml_url, or github address, then write new - file with these links, of form: - - .. _`proj_name` - .. _`proj_name`: url - .. _`proj_name` mailing list: url - """ - with open(known_link_fname, 'rt') as link_fh: - link_contents = link_fh.readlines() - have_url = not url is None - have_ml_url = not ml_url is None - have_gh_url = None - for line in link_contents: - if not have_url: - match = re.match(r'..\s+_`%s`:\s+' % proj_name, line) - if match: - have_url = True - if not have_ml_url: - match = re.match(r'..\s+_`%s mailing list`:\s+' % proj_name, line) - if match: - have_ml_url = True - if not have_gh_url: - match = re.match(r'..\s+_`%s github`:\s+' % proj_name, line) - if match: - have_gh_url = True - if not have_url or not have_ml_url: - raise RuntimeError('Need command line or known project ' - 'and / or mailing list URLs') - lines = [] - if not url is None: - lines.append('.. _`%s`: %s\n' % (proj_name, url)) - if not have_gh_url: - gh_url = 'http://github.com/%s/%s\n' % (user_name, repo_name) - lines.append('.. _`%s github`: %s\n' % (proj_name, gh_url)) - if not ml_url is None: - lines.append('.. _`%s mailing list`: %s\n' % (proj_name, ml_url)) - if len(lines) == 0: - # Nothing to do - return - # A neat little header line - lines = ['.. %s\n' % proj_name] + lines - with open(out_link_fname, 'wt') as out_links: - out_links.writelines(lines) - - -USAGE = ''' - -If not set with options, the repository name is the same as the - -If not set with options, the main github user is the same as the -repository name.''' - - -GITWASH_CENTRAL = 'git://github.com/matthew-brett/gitwash.git' -GITWASH_BRANCH = 'master' - - -def main(): - parser = OptionParser() - parser.set_usage(parser.get_usage().strip() + USAGE) - parser.add_option("--repo-name", dest="repo_name", - help="repository name - e.g. nitime", - metavar="REPO_NAME") - parser.add_option("--github-user", dest="main_gh_user", - help="github username for main repo - e.g fperez", - metavar="MAIN_GH_USER") - parser.add_option("--gitwash-url", dest="gitwash_url", - help="URL to gitwash repository - default %s" - % GITWASH_CENTRAL, - default=GITWASH_CENTRAL, - metavar="GITWASH_URL") - parser.add_option("--gitwash-branch", dest="gitwash_branch", - help="branch in gitwash repository - default %s" - % GITWASH_BRANCH, - default=GITWASH_BRANCH, - metavar="GITWASH_BRANCH") - parser.add_option("--source-suffix", dest="source_suffix", - help="suffix of ReST source files - default '.rst'", - default='.rst', - metavar="SOURCE_SUFFIX") - parser.add_option("--project-url", dest="project_url", - help="URL for project web pages", - default=None, - metavar="PROJECT_URL") - parser.add_option("--project-ml-url", dest="project_ml_url", - help="URL for project mailing list", - default=None, - metavar="PROJECT_ML_URL") - (options, args) = parser.parse_args() - if len(args) < 2: - parser.print_help() - sys.exit() - out_path, project_name = args - if options.repo_name is None: - options.repo_name = project_name - if options.main_gh_user is None: - options.main_gh_user = options.repo_name - repo_path = clone_repo(options.gitwash_url, options.gitwash_branch) - try: - copy_replace((('PROJECTNAME', project_name), - ('REPONAME', options.repo_name), - ('MAIN_GH_USER', options.main_gh_user)), - repo_path, - out_path, - cp_globs=(pjoin('gitwash', '*'),), - rep_globs=('*.rst',), - renames=(('\.rst$', options.source_suffix),)) - make_link_targets(project_name, - options.main_gh_user, - options.repo_name, - pjoin(out_path, 'gitwash', 'known_projects.inc'), - pjoin(out_path, 'gitwash', 'this_project.inc'), - options.project_url, - options.project_ml_url) - finally: - shutil.rmtree(repo_path) - - -if __name__ == '__main__': - main() diff --git a/docs/devguide/gitwash_wrapper.sh b/docs/devguide/gitwash_wrapper.sh deleted file mode 100755 index 2bb9412..0000000 --- a/docs/devguide/gitwash_wrapper.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/bash -# -# Run gitwash_dumper.py and edit the output to remove the email patching -# page which is not relevant to this project. -# - -set -u -set -e - -readonly PROJECT_NAME="windspharm" -readonly REPO_NAME="windspharm" -readonly GITHUB_USER="ajdawson" -readonly PROJECT_URL="http://ajdawson.github.io/windspharm" -readonly OUTPUT_DIRECTORY="./" -readonly GITWASH_DUMPER="./gitwash_dumper.py" - -# Use the gitwash script to refresh the documentation. -python "$GITWASH_DUMPER" "$OUTPUT_DIRECTORY" "$PROJECT_NAME" \ - --repo-name="$REPO_NAME" \ - --github-user="$GITHUB_USER" \ - --project-url="$PROJECT_URL" \ - --project-ml-url="NONE" - -# Remove the patching section of the gitwash guide. -rm -f "${OUTPUT_DIRECTORY}/gitwash/patching.rst" -sed -i '/patching/d' "${OUTPUT_DIRECTORY}/gitwash/index.rst" - -# Remove references to the project mailing list in the gitwash guide. -sed -i '/mailing list/d' "${OUTPUT_DIRECTORY}/gitwash/this_project.inc" -sed -i '/mailing list/d' "${OUTPUT_DIRECTORY}/gitwash/development_workflow.rst" - -# Remove all trailing whitespace and trailing blank lines from the downloaded -# gitwash guide restructured text sources: -sed -i 's/[[:space:]]*$//' "${OUTPUT_DIRECTORY}"/gitwash/*.{rst,inc} -sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' "${OUTPUT_DIRECTORY}"/gitwash/*.{rst,inc} diff --git a/docs/devguide/index.rst b/docs/devguide/index.rst index 77f2126..78ea172 100644 --- a/docs/devguide/index.rst +++ b/docs/devguide/index.rst @@ -6,5 +6,4 @@ This guide is for those who want to contribute to the development of `windspharm .. toctree:: :maxdepth: 2 - gitwash/index testing diff --git a/docs/devguide/testing.rst b/docs/devguide/testing.rst index bc2d52f..2408554 100644 --- a/docs/devguide/testing.rst +++ b/docs/devguide/testing.rst @@ -2,19 +2,19 @@ Running the test suite ====================== The package comes with a comprehensive set of tests to make sure it is working correctly. -The tests can be run against an installed version of `eofs` or against the current source tree. +The tests can be run against an installed version of `windspharm` or against the current source tree. Testing against the source tree is handy during development when quick iteration is required, but for most other cases testing against the installed version is more suitable. Running the test suite requires pytest_ to be installed. The test suite will function as long as the minimum dependencies for the package are installed, but some tests will be skipped if they require optional dependencies that are not present. -To run the full test suite you need to have the optional dependencies `cdms2` (from UV-CDAT_), iris_, and xarray_ installed. +To run the full test suite you need to have the optional dependencies iris_, and xarray_ installed. Testing against the current source tree --------------------------------------- Testing the current source is straightforward, from the source directory run:: - pytest + python -m pytest This will perform verbose testing of the current source tree and print a summary at the end. @@ -25,20 +25,18 @@ Testing an installed version First you need to install `windspharm` into your current Python environment:: cd windspharm/ - python setup.py install + python -m pip install . Then create a directory somewhere else without any Python code in it and run ``pytest`` from there giving the package name ``windspharm``:: mkdir $HOME/windspharm-test-dir && cd $HOME/windspharm-test-dir - pytest --pyargs windspharm + python -m pytest --pyargs windspharm This will run the tests on the version of `windspharm` you just installed. This also applies when `windspharm` has been installed by another method (e.g., pip or conda). -.. _pytest: https://docs.pytest.org +.. _pytest: https://docs.pytest.org/en/stable/ -.. _UV-CDAT: http://uv-cdat.llnl.gov +.. _iris: https://scitools-iris.readthedocs.io/en/stable -.. _iris: http://scitools.org.uk/iris - -.. _xarray: http://xarray.pydata.org +.. _xarray: https://xarray.dev diff --git a/docs/examples/cdms_examples_index.rst b/docs/examples/cdms_examples_index.rst deleted file mode 100644 index 2de16ac..0000000 --- a/docs/examples/cdms_examples_index.rst +++ /dev/null @@ -1,8 +0,0 @@ -cdms interface examples -======================= - -.. toctree:: - :maxdepth: 1 - - sfvp_cdms - rws_cdms diff --git a/docs/examples/index.rst b/docs/examples/index.rst index 1353b83..8d34662 100644 --- a/docs/examples/index.rst +++ b/docs/examples/index.rst @@ -6,7 +6,6 @@ Examples :maxdepth: 2 standard_examples_index - cdms_examples_index iris_examples_index xarray_examples_index diff --git a/docs/examples/rws_cdms.rst b/docs/examples/rws_cdms.rst deleted file mode 100644 index 18b84b7..0000000 --- a/docs/examples/rws_cdms.rst +++ /dev/null @@ -1,7 +0,0 @@ -Rossby wave source -================== - - -.. plot:: example_code/cdms/rws_example.py - -.. literalinclude:: ../example_code/cdms/rws_example.py diff --git a/docs/examples/sfvp_cdms.rst b/docs/examples/sfvp_cdms.rst deleted file mode 100644 index c2fbf99..0000000 --- a/docs/examples/sfvp_cdms.rst +++ /dev/null @@ -1,7 +0,0 @@ -Streamfunction and velocity potential -===================================== - - -.. plot:: example_code/cdms/sfvp_example.py - -.. literalinclude:: ../example_code/cdms/sfvp_example.py diff --git a/docs/index.rst b/docs/index.rst index 38de5e0..2346f68 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -55,25 +55,18 @@ You can also check out the source code for the development version from the `git Requirements ------------ -This package requires as a minimum that you have numpy_ and pyspharm_ available, and requires setuptools_ for installation. +This package requires as a minimum that you have numpy_ and pyspharm_ available. The `windspharm.iris` interface can only be used if the `iris` package is available (see the iris_ documentation). -The `windspharm.cdms` interface can only be used if the `cdms2` module is available. This module is distributed as part of the UVCDAT_ project. The `windspharm.xarray` interface can only be used if the `xarray` package is available (see the xarray_ documentation). -.. warning:: - - It is strongly recommended to use pyspharm 1.0.8 or later. - There is a bug in versions prior to 1.0.7 that causes incorrect fields to be returned when there is more than one input field, and a small bug in version 1.0.7 that causes problems with fields with a singleton time dimension. - - Getting Started --------------- The `windspharm` package provides several interfaces for performing computations. The :ref:`standard ` interface is designed to work with `numpy` arrays. On top of this are layers desinged to work with more advanced data structures that also contain metadata. -Currently there is support for :ref:`iris cubes `, :ref:`xarray DataArrays `, and :ref:`cdms2 variables `. +Currently there is support for :ref:`iris cubes ` and :ref:`xarray DataArrays `. Regardless of which interface you use, the basic usage is the same. All computation is handled by a `VectorWind` instance initialized with global vector wind components. Method calls are then used to return quantities of interest. @@ -101,7 +94,7 @@ Citation -------- If you use windspharm in published research, please cite it by referencing the `peer-reviewed paper `_. -You can additionally cite the `Zenodo DOI `_ if you need to cite a particular version (but please also cite the paper, it helps me justify my time working on this and similar projects). +You can additionally cite the `Zenodo DOI `_ if you need to cite a particular version (but please also cite the paper, it helps me justify my time working on this and similar projects). Developing and Contributing @@ -113,22 +106,16 @@ Bug reports and feature requests can be filed using the Github issues_ system. If you would like to contribute code or documentation please see the :doc:`devguide/index`. -.. _UVCDAT: http://uvcdat.llnl.gov/ - -.. _iris: http://scitools.org.uk/iris - -.. _xarray: http://xarray.pydata.org - -.. _numpy: http://numpy.scipy.org +.. _iris: https://scitools-iris.readthedocs.io/en/stable -.. _pyspharm: https://code.google.com/p/pyspharm +.. _xarray: https://xarray.dev -.. _setuptools: https://pypi.python.org/pypi/setuptools +.. _numpy: https://numpy.org -.. _issues: http://github.com/ajdawson/windspharm/issues?state=open +.. _pyspharm: https://github.com/jswhit/pyspharm -.. _windspharm: http://ajdawson.github.com/windspharm +.. _issues: https://github.com/ajdawson/windspharm/issues -.. _conda: http://conda.pydata.org/docs/ +.. _windspharm: https://ajdawson.github.io/windspharm -.. _binstar: https://binstar.org +.. _conda: https://github.com/conda-forge/miniforge diff --git a/docs/userguide/interfaces.rst b/docs/userguide/interfaces.rst index 74a338b..0e06fc0 100644 --- a/docs/userguide/interfaces.rst +++ b/docs/userguide/interfaces.rst @@ -13,7 +13,6 @@ Interface Description ========= ======================================== iris Data contained in an `iris` cube. xarray Data contained in an `xarray.DataArray`. -cdms Data stored in a `cdms2` variable. standard Other data, stored in a `numpy.ndarray`. ========= ======================================== @@ -34,18 +33,9 @@ xarray interface The xarray interface works with `~xarray.DataArray` objects. The coordinate metadata of `~xarray.DataArray` is interpreted by the `windspharm.xarray.VectorWind` interface, and the outputs of the `windspharm.xarray.VectorWind` methods are contained in `~xarray.DataArray` objects allowing their use with othe tools from the `xarray` package. -.. _cdms-interface: - -cdms interface --------------- - -The `windspharm.cdms.VectorWind` interface works with `cdms2` variables, which are the core data container used by UVCDAT_. A `cdms2` variable has meta-data associated with it, including dimensions, which are understood by the `windspharm.cdms.VectorWind` interface. The outputs of `windspharm.cdms.VectorWind` methods are `cdms2` variables with meta-data, which can be written straight to a netCDF file using `cdms2`, or used with other parts of the UVCDAT_ framework. - .. _standard-interface: standard interface ------------------ The standard interface works with `numpy` arrays, which makes the standard interface the general purpose interface. Any data that can be stored in a `numpy.ndarray` can be analysed with the `windspharm.standard.VectorWind` interface. - -.. _UVCDAT: http://uvcdat.llnl.gov diff --git a/docs/userguide/usage.rst b/docs/userguide/usage.rst index 31e914b..bdc0189 100644 --- a/docs/userguide/usage.rst +++ b/docs/userguide/usage.rst @@ -17,14 +17,10 @@ the iris interface:: from windspharm.iris import VectorWind -the xarray interface:: +and the xarray interface:: from windspharm.xarray import VectorWind -and the cdms interface:: - - from windspharm.cdms import VectorWind - Creating a **VectorWind** object -------------------------------- diff --git a/examples/cdms/rws_example.py b/examples/cdms/rws_example.py deleted file mode 100644 index 0f7ab56..0000000 --- a/examples/cdms/rws_example.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Compute Rossby wave source from the long-term mean flow. - -This example uses the cdms interface. - -Additional requirements for this example: - -* cdms2 (http://uvcdat.llnl.gov/) -* matplotlib (http://matplotlib.org/) -* cartopy (http://scitools.org.uk/cartopy/) - -""" -import cartopy.crs as ccrs -import cdms2 -import matplotlib as mpl -import matplotlib.pyplot as plt - -from windspharm.cdms import VectorWind -from windspharm.examples import example_data_path - -mpl.rcParams['mathtext.default'] = 'regular' - - -# Read zonal and meridional wind components from file using the cdms2 module -# from CDAT. The components are in separate files. -ncu = cdms2.open(example_data_path('uwnd_mean.nc'), 'r') -uwnd = ncu('uwnd') -ncu.close() -ncv = cdms2.open(example_data_path('vwnd_mean.nc'), 'r') -vwnd = ncv('vwnd') -ncv.close() - -# Create a VectorWind instance to handle the computations. -w = VectorWind(uwnd, vwnd) - -# Compute components of rossby wave source: absolute vorticity, divergence, -# irrotational (divergent) wind components, gradients of absolute vorticity. -eta = w.absolutevorticity() -div = w.divergence() -uchi, vchi = w.irrotationalcomponent() -etax, etay = w.gradient(eta) - -# Combine the components to form the Rossby wave source term. -S = -eta * div - (uchi * etax + vchi * etay) - -# Pick out the field for December and add a cyclic point (the cyclic point is -# for plotting purposes). -S_dec = S(time=slice(11, 12), longitude=(0, 360), squeeze=True) - -# Plot Rossby wave source. -lons, lats = S_dec.getLongitude()[:], S_dec.getLatitude()[:] -ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180)) -clevs = [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30] -fill = ax.contourf(lons, lats, S_dec.asma() * 1e11, clevs, - transform=ccrs.PlateCarree(), cmap=plt.cm.RdBu_r, - extend='both') -ax.coastlines() -ax.gridlines() -plt.colorbar(fill, orientation='horizontal') -plt.title('Rossby Wave Source ($10^{-11}$s$^{-1}$)', fontsize=16) -plt.show() diff --git a/examples/cdms/sfvp_example.py b/examples/cdms/sfvp_example.py deleted file mode 100644 index f2ed128..0000000 --- a/examples/cdms/sfvp_example.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -Compute streamfunction and velocity potential from the long-term-mean -flow. - -This example uses the cdms interface. - -Additional requirements for this example: - -* cdms2 (http://uvcdat.llnl.gov/) -* matplotlib (http://matplotlib.org/) -* cartopy (http://scitools.org.uk/cartopy/) - -""" -import cartopy.crs as ccrs -import cdms2 -import matplotlib as mpl -import matplotlib.pyplot as plt - -from windspharm.cdms import VectorWind -from windspharm.examples import example_data_path - -mpl.rcParams['mathtext.default'] = 'regular' - - -# Read zonal and meridional wind components from file using the cdms2 module -# from CDAT. The components are in separate files. -ncu = cdms2.open(example_data_path('uwnd_mean.nc'), 'r') -uwnd = ncu('uwnd') -ncu.close() -ncv = cdms2.open(example_data_path('vwnd_mean.nc'), 'r') -vwnd = ncv('vwnd') -ncv.close() - -# Create a VectorWind instance to handle the computation of streamfunction and -# velocity potential. -w = VectorWind(uwnd, vwnd) - -# Compute the streamfunction and velocity potential. -sf, vp = w.sfvp() - -# Pick out the field for December and add a cyclic point (the cyclic point is -# for plotting purposes). -sf_dec = sf(time=slice(11, 12), longitude=(0, 360), squeeze=True) -vp_dec = vp(time=slice(11, 12), longitude=(0, 360), squeeze=True) - -# Plot streamfunction. -ax1 = plt.axes(projection=ccrs.PlateCarree(central_longitude=180)) -lons, lats = sf_dec.getLongitude()[:], sf_dec.getLatitude()[:] -clevs = [-120, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 120] -fill_sf = ax1.contourf(lons, lats, sf_dec.asma() * 1e-06, clevs, - transform=ccrs.PlateCarree(), cmap=plt.cm.RdBu_r, - extend='both') -ax1.coastlines() -ax1.gridlines() -plt.colorbar(fill_sf, orientation='horizontal') -plt.title('Streamfunction ($10^6$m$^2$s$^{-1}$)', fontsize=16) - -# Plot velocity potential. -plt.figure() -ax2 = plt.axes(projection=ccrs.PlateCarree(central_longitude=180)) -clevs = [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10] -fill_vp = ax2.contourf(lons, lats, vp_dec.asma() * 1e-06, clevs, - transform=ccrs.PlateCarree(), cmap=plt.cm.RdBu_r, - extend='both') -ax2.coastlines() -ax2.gridlines() -plt.colorbar(fill_vp, orientation='horizontal') -plt.title('Velocity Potential ($10^6$m$^2$s$^{-1}$)', fontsize=16) -plt.show() diff --git a/examples/standard/rws_example.py b/examples/standard/rws_example.py index 6537266..dec8e81 100644 --- a/examples/standard/rws_example.py +++ b/examples/standard/rws_example.py @@ -23,9 +23,8 @@ mpl.rcParams['mathtext.default'] = 'regular' -# Read zonal and meridional wind components from file using the cdms2 module -# from CDAT. The components are defined on pressure levels and are in separate -# files. +# Read zonal and meridional wind component, the components are defined on +# pressure levels and are in separate files. ncu = Dataset(example_data_path('uwnd_mean.nc'), 'r') uwnd = ncu.variables['uwnd'][:] lons = ncu.variables['longitude'][:] diff --git a/github_deploy_key_ajdawson_windspharm.enc b/github_deploy_key_ajdawson_windspharm.enc deleted file mode 100644 index 4730831..0000000 --- a/github_deploy_key_ajdawson_windspharm.enc +++ /dev/null @@ -1 +0,0 @@ -gAAAAABbcc9yfy9nMfnnDAs8SVev1hKLQY1yyF1RFbRDrXlE6n90k6xv6CLazayLaSRvoA22LXrsfOe_X-3FaKxrjaF4Y1Wng8IKsa83eLU6lXU3Oy9joo_IoIFzsZ_y5PoZos-AO5htTRjFybiLnpEuvqq0pTGHB4cbtVI9jrLT0PyZFuoDjawwVm2DsheFxMc-gA0gdsM83ngjCFPfj2zWH3qzBD7HwV-jCCBH0msSWPbqsvnx06X0SaCBIsVEzFAfac3rO9ir1VQ5kHHAc-0a-I_8LemB4XF7_8KjIaWsjYj_RTtKUAmMTUur6L6GXTLtKHgWprPsFbZfXJJnGOBvl4DXDmpOiMBRe3dtVZkCLtu-eOOR0ubxehW3o5KmnIvP4rNHY9eCDChujHp-JhWrYoR_NcCcnOxaxR6QzfWCDkYPogEy5K4U7GeY5nY7Yf3d1aPtaOQAHQ8T8aptKCP2zHPLcsZdVnWE_VF63NoNq-USpv5BexnhqkWV_4OpAB3ZVOPiwLMYdVB8OF-LpNoCpCv1knmJ32dK796irbfoyfoKjaTYGQp5qAAaD091JwfsFxqV3lulF3tN-elh40DY7s2Jd8hOjjf61LBctRF2FWmVIrjN3Wp_SxkoyNlQ4n1OrqGh_J9-KHGAeTDfVyHj2prtjFeKXJm97tGWXr1mCqgwbz4O8f5KAyZswWdQxf60SJ7XeebzIvCh9DQiSPf1ke7G7bJ0BJWhReg9dfuaJY6CGXoCSN82jOe5DWKomHHX6h9C1n-8VedbmHnLv_xQtb1-a2MIjDLe7erFF7L9kCunmkE8pc2uIQHXbkUY7YOgfUJejQiTCTnmc65Djs8FmuQ_aAVg4k9bjDndYRo4z3rmOkLLPdRYw6gXI8w7Kp6ia35ddmmkq1PdwCJrXgtQxf5uwT4zJkzmqOgPZDzuquSNuZd0zUZ2ZoKsVqW9h7dOo7YHqo8qnDAtsQlQ5bJC6p-FGL4arRUkyj6za0SwGOnZ46mCIPsKNw1VrsN_DHK4GLIdAumFTsw4X3Rh4UAnqAte1wfG1fSaMdyKQpCoKnZ0LrBtfULKcGK8cx0rCfL0SV8bKovBgvsP2OPIxq0X1ptZKPTyd8noBsZhahmJfpcKKXWxWzPBIWqSZUZskEHtzzAymP-DJs65B2zmUxnISjZtTmOejRAdXMsop59y-Aa5uF9RCBM0NhKo8oDvh0xjwuLtqlu70HAVFYAmMfkZ1V-Eq4U4eXsRgNk6ywVrfsTAwLKnnQhDO8HqUUs-ROlG-NleGkACKoEVhkpkFLIlaIF847WWKAwxRelkZGw2p6eWDvBOcGudcywF5nWJ4dWYpRADgKosmizviEHTqdmo7QWr4rMqw7mNF-4aZDbD5eOEqpE8YsxlnPgstl2hsUHuE1sSQnuHHExHxJ1L_BImweHzVSqK3iW1N9TzP_BCcA6Cvufmi_Dj0ndTNDVWKAWJY8qf_DINUC3i26v1cbf45rFVL_FS4g_58M8BnhT82hNPK16-WnObC3ld0xjwkC2tQnWmHErzUjS1IKoQ_s5eCaQW_TqWc0vHw3YZKqkhOdjxac9dguAiEwK5aFaH9OnRUHSHkl4yxVOXg6Qw4aTb9nydj5MxdVU3TXEtWD_S4M9p1CA40IO9dBC29tHiZeZoNhSU3P6NmMv5zEIdfiTAKv-qV5CGMgZ6rPG6N2joqKT4Wdz8EujpfNumYbYT4DAHdxSETilK35VfS9xI0Yt_Q7AY0P7eIW13BVJ6jhjaHt6y5mzSJySq4Zw7DIf0r0MzkHZu_FpyUSXPl69QJriAqo1yqiYGcwk1iU_FHO4RLtOxkLWKh4aR_4GRkLoamPTvQRK7Gb4b2jGeEUT0u0sj_jb_vtGhBtewCcE3pBbvVfmCygnYEfxxExbndw1qKJ_ndhayhBT4VYP0qfHHZc2UVpxmOTr9FYtjCIMNDrjBZx7AZpB7r86c982vEnBe8VIg5HLWSAP6I8oEz0Qk64Ds7fXZjs39EIVBy-AlmkvAYP--Vt98iY_ou1iwSdwR-zt0nsKfEe9YZM1av_EZC57oqkP7FhB1E_A2sqPjke3wM4HVa0MJ1SL9teODyBlK43ZMGvj_gVlLS_v74EUUwWSKY2IkxU4h4UtSzmDurcKQZcgy42PuPtAOfBFVOpYTVGi2mIh_d8dY8YMiiLa2ip6sE5dawEhPXp6W3Tx5HSGrGakBulwRcFuwSlcwf9TlNMGPPLaYISnK7ofEWgi-TVNJWSPabUYwE8g8QF-aTggMbUSGXdW6W-e2zqo14U2vXMSKTWmbD_1-3DEC4WPTXZV2D_fXRD7qzsn2IkagV8sZ0vLmyNg3TKIdofKIHywNt1fr9frxZ-T_tO1hg__HwutmHZWMlqZ0UhTQXQ0tkBCrIsqdvUqCCSWxQFhXqXZ9KMThamwqkpL7DOOj7hxUYsZFUQmgF2hNZb2N32tvMQEAanJ3gA2AXtmC_O1psOoZvz_YaztlISJ_bdGRcr7Ueh5OPwZPQu6I2ZOSLBd8B_HO55u6HQZEuOU9_iXm7l2Il8PrKqdLpl4oa_4zo9Jfutux3mnN_DwJKpPo9XZAvLEHu6emU3hMiDha4-1vIWxJf1eGmS-wP_yCyKk-tpiZhA65Ql-T9lQ4Ka86yAn2Kn0Xnxy2zrQ6-jRB4kx6sAl1vlPAhCIFl1LFHIuDUguYMnW3o7vnQ2O8CGpg2IwOS8T8Ou05YTc9VDOSXwhXQaf5mojGSXr86ddgy6lmRbyjbXsjOwp0j0kOIFjqTF7sXfzPcHOjiXbbznZFj-LGpKIr1lSB3nQvljWVbSnYjCExBctfPLDoxKaLg1lHz7sNWn7JbFtg1fUrMi3ZvFH4i21SN8I-A65cH9DEnWJPu1URAZCcKQcC1qQQxhc9HyqS3a2B5mi6a-65LglOD__BhNcncSf-eJZp0ltz_19dS8_Eb2GkByKiBaiQSSaye3Wl0ANzbVG3OWC_CfiBzEMuzDFJkly05Ayc-0t-5SdTcwtAyQj4QqO_Idr278Bd_620O_kndwarHrGcu9lbjGKdO9GQ6BtXQSrI-lY9XfJazPTdjsMfcFTVyVbjfy10dZZHtJFETt_9BvQrUqdYZIuQvS7VFWQLQEBDXOnustY2yrWsxt4ZO_LPdQmcqUMjdxy16DAV4EZwsxTB2es4EA8tBSjjzPTU0SDu_aHB7Ip2e7GwJcHO-RSuL2qHnfF4L7awtFTDUFEMIrKZsj5hjWOlcU9R4j_z8D4k018VsbSClu9w8v0ig_QL_nHpADHT2z92qvtRw1CUhBvm4gNh-L4L9lRZBiwxsMHu6DbgETSQiKVfqPSvki8aeeYgvm8rjscFHgOckBVTV1vg96fRTLOYacPPJBxDbIu-FUvSaLcdm6SPvTpGH1wjSfQwUXV_6eWqNMLiEHJ4mNq677hnwKntHJJqd293ctV3OJP4yfzAT2A0emuw8Nv2GL-n5tXjtJ6uWogk7gKmTH0odX5wljLsI_ltiFS2GXRlDvujt5hP7ttoL1FC4K7EJTc8LjUCApWUrgQjV4BwxpYLVnh2Wbolnc6tmXmlGKukTDfu0OpiqT3LLuNnK8pQoOEUkNOeGkiYlS6tyh22MwFXnIXgoMkqvzkiDgCjcbJ9f8LUsgP7OiESov-3KsuLZJ_c4-tFP94BISMr4YREsXkYmtUjlEmHBPlqEkYlyHvW7DKj4x83M6qgPPvpK77ZVplo1JOlMMgP2nh3hOytjY3A0rj6pfJV0SnF-W-IrEij5qTWvLJs_npNd3n_w7rcfy47Q712LgouY0-HPR9M3YUpvDwZNaJn3E11NMnLSzqTuX3YOgyJm0RfOnfhwHHF165tujYy5p5n23tIcYsCd1FUEZJK3VD0oOUyimoCf5ZEWlMy9uMKxPNF_3ihQ5OSMOpHjL_vnnxexB40cfDpIr2AHe-sxS58nCHetHVC3bSiRHduytLUejuidwo33qHnRlrjY4oJlI-3b4Z5CMWIgTqb0ks0_XYI5aWLfDWgq5DdNOtQnMj53CRRQX8kYwdAquVLKhso5fy5-XbAAM8vAER3IwMIjCi9g1qpZkYm3M9cnWy-Ia3BOIt-CHhJ9kZzTi2TA2fLVJGv19BdOLyjjUJ37IO8dcU31WhNShEnaFNoy6pLUu0yaAmZPykDUzpx3-bAhjl1mQ0uggq24UI7z3LULq5z8JT_JzcDuB_-IHCN-ck5x4g2JjFcHp-84d7lxiXgDiGKX6Bk5eWalOV9i7blOlvtCale9DIIiL0vVz6cBHj_mjPIUKyaQk8ZnxrMmL3l9jyKm3-avi4XzKzl40ryOs1bGMmI2c3p-NIbFW4PLMImwKISFSUog8YA9eURIq7TMbxTW2UTr2K69iG631t_HhjI7Nf1WwV2ObkN099_TX3pUGMXLyiEpge0i8l9gaufNg== \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..8bbdb96 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,74 @@ +[build-system] +build-backend = "setuptools.build_meta" +requires = [ + "setuptools>=42", + "setuptools-scm", + "wheel", +] + +[project] +name = "windspharm" +description = "vector wind analysis in spherical coordinates" +license = { text = "MIT" } +authors = [ + { name = "Andrew Dawson", email = "ajdatm@gmail.com" }, +] +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +dynamic = [ + "readme", + "version", +] +dependencies = [ + "numpy", + "pyspharm>=1.0.9", +] +optional-dependencies.iris = [ + "scitools-iris", +] +optional-dependencies.xarray = [ + "xarray", +] +urls.documentation = "https://ajdawson.github.io/windspharm" +urls.homepage = "https://github.com/ajdawson/windspharm" +urls.repository = "https://github.com/ajdawson/windspharm" + +[tool.setuptools] +license-files = [ "license.txt" ] +include-package-data = true +[tool.setuptools.package-data] +"windspharm.examples" = [ + "example_data/*", +] +"windspharm.tests" = [ + "data/regular/*.npy", + "data/gaussian/*.npy", +] +[tool.setuptools.dynamic] +readme = { file = "README.md", content-type = "text/markdown" } + +[tool.setuptools_scm] +write_to = "windspharm/_version.py" +write_to_template = "__version__ = '{version}'" +tag_regex = "^(?Pv)?(?P[^\\+]+)(?P.*)?$" + +[tool.ruff] +lint.select = [ + "E", # pycodecstyle +] +lint.per-file-ignores."docs/conf.py" = [ + "E401", + "E402", +] + +[tool.pytest.ini_options] +addopts = "-vrsx" +testpaths = "windspharm" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 6a7cca9..0000000 --- a/setup.cfg +++ /dev/null @@ -1,19 +0,0 @@ -[tool:pytest] -addopts = -vrsx -testpaths = windspharm - -[flake8] -exclude = \ - setup.py, \ - windspharm/__init__.py, \ - doc/conf.py, \ - doc/sphinxext/plot_directive.py, \ - doc/devguide/gitwash_dumper.py - -[versioneer] -VCS = git -style = pep440 -versionfile_source = windspharm/_version.py -versionfile_build = windspharm/_version.py -tag_prefix = v -parentdir_prefix = windspharm \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 51fdec6..0000000 --- a/setup.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Build and install the windspharm package.""" -# Copyright (c) 2012-2018 Andrew Dawson -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -import os.path - -from setuptools import setup -import versioneer - -packages = ['windspharm', - 'windspharm.examples', - 'windspharm.tests'] - -package_data = { - 'windspharm.examples': ['example_data/*'], - 'windspharm.tests': ['data/regular/*.npy', 'data/gaussian/*.npy']} - -with open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r') as f: - long_description = f.read() - -setup(name='windspharm', - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - description='vector wind analysis in spherical coordinates', - author='Andrew Dawson', - author_email='dawson@atm.ox.ac.uk', - url='http://ajdawson.github.com/windspharm/', - long_description=long_description, - long_description_content_type='text/markdown', - packages=packages, - package_data=package_data, - install_requires=['numpy', 'pyspharm >= 1.0.8'],) diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 64fea1c..0000000 --- a/versioneer.py +++ /dev/null @@ -1,1822 +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/ . - -""" - -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(): - """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 = {} - - # 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) diff --git a/windspharm/__init__.py b/windspharm/__init__.py index 2e97a1a..7a45186 100644 --- a/windspharm/__init__.py +++ b/windspharm/__init__.py @@ -23,22 +23,15 @@ from . import standard from . import tools -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions - +try: + from ._version import __version__ +except ImportError: + __version__ = "unknown" # List to define the behaviour of imports of the form: # from windspharm import * __all__ = [] -try: - from . import cdms - __all__.append('cdms') - metadata = cdms -except ImportError: - pass - try: from . import iris __all__.append('iris') diff --git a/windspharm/_version.py b/windspharm/_version.py deleted file mode 100644 index e32bf05..0000000 --- a/windspharm/_version.py +++ /dev/null @@ -1,520 +0,0 @@ - -# 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 = "$Format:%d$" - git_full = "$Format:%H$" - git_date = "$Format:%ci$" - 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 = "pep440" - cfg.tag_prefix = "v" - cfg.parentdir_prefix = "windspharm" - cfg.versionfile_source = "lib/windspharm/_version.py" - 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} diff --git a/windspharm/cdms.py b/windspharm/cdms.py deleted file mode 100644 index 24419b9..0000000 --- a/windspharm/cdms.py +++ /dev/null @@ -1,792 +0,0 @@ -"""Spherical harmonic vector wind computations (`cdms2` interface).""" -# Copyright (c) 2012-2018 Andrew Dawson -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -from __future__ import absolute_import - -import cdms2 - -from . import standard -from ._common import inspect_gridtype, to3d - - -class VectorWind(object): - """Vector wind computations (`cdms2` interface).""" - - def __init__(self, u, v, rsphere=6.3712e6, legfunc='stored'): - """Initialize a VectorWind instance. - - **Arguments:** - - *u*, *v* - Zonal and meridional components of the vector wind - respectively. Both components should be `cdms2` - variables. The components must have the same shape and - contain no missing values. - - **Optional argument:** - - *rsphere* - The radius in metres of the sphere used in the spherical - harmonic computations. Default is 6371200 m, the approximate - mean spherical Earth radius. - - *legfunc* - 'stored' (default) or 'computed'. If 'stored', associated legendre - functions are precomputed and stored when the class instance is - created. This uses O(nlat**3) memory, but speeds up the spectral - transforms. If 'computed', associated legendre functions are - computed on the fly when transforms are requested. This uses - O(nlat**2) memory, but slows down the spectral transforms a bit. - - **Example:** - - Initialize a `VectorWind` instance with zonal and meridional - components of the vector wind:: - - from windspharm.cdms import VectorWind - w = VectorWind(u, v) - - """ - # Ensure the input are cdms2 variables. - if not (cdms2.isVariable(u) and cdms2.isVariable(v)): - raise TypeError('u and v must be cdms2 variables') - # Check that both u and v have dimensions in the same order and that - # there are latitude and longitude dimensions present. - uorder = u.getOrder() - vorder = v.getOrder() - if uorder != vorder: - raise ValueError('u and v must have the same dimension order') - for order in (uorder, vorder): - if 'x' not in order or 'y' not in order: - raise ValueError('a latitude-longitude grid is required') - self.order = uorder - # Assess how to re-order the inputs to be compatible with the - # computation API. - apiorder = 'yx' + ''.join([a for a in order if a not in 'xy']) - # Order the dimensions correctly. - u = u.reorder(apiorder) - v = v.reorder(apiorder) - # Do a region selection on the inputs to ensure the latitude dimension - # is north-to-south. - u = u(latitude=(90, -90)) - v = v(latitude=(90, -90)) - # Determine the grid type, - lon = u.getLongitude() - lat = u.getLatitude() - if lon is None or lat is None: - raise ValueError('a latitude-longitude grid is required') - gridtype = inspect_gridtype(lat[:]) - # Store the shape and axes when data is in the API order. - self.ishape = u.shape - self.axes = u.getAxisList() - # Re-shape to 3-dimensional (compatible with API) - u = to3d(u) - v = to3d(v) - # Instantiate a VectorWind object to do the computations. - self.api = standard.VectorWind(u, v, gridtype=gridtype, - rsphere=rsphere, legfunc=legfunc) - - def _metadata(self, var, **attributes): - """Re-shape and re-order raw results, and add meta-data.""" - if 'id' not in attributes.keys(): - raise ValueError('meta-data construction requires id') - var = cdms2.createVariable(var.reshape(self.ishape), axes=self.axes) - var = var.reorder(self.order) - for attribute, value in attributes.items(): - setattr(var, attribute, value) - return var - - def u(self): - """Zonal component of vector wind. - - **Returns:** - - *u* - The zonal component of the wind. - - **Example:** - - Get the zonal component of the vector wind:: - - u = w.u() - - """ - u = self.api.u - u = self._metadata(u, - id='u', - standard_name='eastward_wind', - units='m s**-1', - long_name='eastward component of wind') - return u - - def v(self): - """Meridional component of vector wind. - - **Returns:** - - *v* - The meridional component of the wind. - - **Example:** - - Get the meridional component of the vector wind:: - - v = w.v() - - """ - v = self.api.v - v = self._metadata(v, - id='v', - standard_name='northward_wind', - units='m s**-1', - long_name='northward component of wind') - return v - - def magnitude(self): - """Wind speed (magnitude of vector wind). - - **Returns:** - - *speed* - The wind speed. - - **Example:** - - Get the magnitude of the vector wind:: - - spd = w.magnitude() - - """ - m = self.api.magnitude() - m = self._metadata(m, - id='mag', - standard_name='wind_speed', - units='m s**-1', - long_name='wind speed') - return m - - def vrtdiv(self, truncation=None): - """Relative vorticity and horizontal divergence. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *vrt*, *div* - The relative vorticity and divergence respectively. - - **See also:** - - `~VectorWind.vorticity`, `~VectorWind.divergence`. - - **Examples:** - - Compute the relative vorticity and divergence:: - - vrt, div = w.vrtdiv() - - Compute the relative vorticity and divergence and apply spectral - truncation at triangular T13:: - - vrtT13, divT13 = w.vrtdiv(truncation=13) - - """ - vrt, div = self.api.vrtdiv(truncation=truncation) - vrt = self._metadata(vrt, - id='vrt', - units='s**-1', - standard_name='atmosphere_relative_vorticity', - long_name='relative vorticity') - div = self._metadata(div, - id='div', - units='s**-1', - standard_name='divergence_of_wind', - long_name='horizontal divergence') - return vrt, div - - def vorticity(self, truncation=None): - """Relative vorticity. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *vrt* - The relative vorticity. - - **See also:** - - `~VectorWind.vrtdiv`, `~VectorWind.absolutevorticity`. - - **Examples:** - - Compute the relative vorticity:: - - vrt = w.vorticity() - - Compute the relative vorticity and apply spectral truncation at - triangular T13:: - - vrtT13 = w.vorticity(truncation=13) - - """ - vrt = self.api.vorticity(truncation=truncation) - vrt = self._metadata(vrt, - id='vrt', - units='s**-1', - standard_name='atmosphere_relative_vorticity', - long_name='relative vorticity') - return vrt - - def divergence(self, truncation=None): - """Horizontal divergence. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *div* - The divergence. - - **See also:** - - `~VectorWind.vrtdiv`. - - **Examples:** - - Compute the divergence:: - - div = w.divergence() - - Compute the divergence and apply spectral truncation at - triangular T13:: - - divT13 = w.divergence(truncation=13) - - """ - div = self.api.divergence(truncation=truncation) - div = self._metadata(div, - id='div', - units='s**-1', - standard_name='divergence_of_wind', - long_name='horizontal divergence') - return div - - def planetaryvorticity(self, omega=None): - """Planetary vorticity (Coriolis parameter). - - **Optional argument:** - - *omega* - Earth's angular velocity. The default value if not specified - is 7.292x10**-5 s**-1. - - **Returns:** - - *pvorticity* - The planetary vorticity. - - **See also:** - - `~VectorWind.absolutevorticity`. - - **Example:** - - Compute planetary vorticity using default values:: - - pvrt = w.planetaryvorticity() - - Override the default value for Earth's angular velocity:: - - pvrt = w.planetaryvorticity(omega=7.2921150) - - """ - f = self.api.planetaryvorticity(omega=omega) - f = self._metadata( - f, - id='f', - units='s**-1', - standard_name='coriolis_parameter', - long_name='planetary vorticity (coriolis parameter)') - return f - - def absolutevorticity(self, omega=None, truncation=None): - """Absolute vorticity (sum of relative and planetary vorticity). - - **Optional arguments:** - - *omega* - Earth's angular velocity. The default value if not specified - is 7.292x10**-5 s**-1. - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *avorticity* - The absolute (relative + planetary) vorticity. - - **See also:** - - `~VectorWind.vorticity`, `~VectorWind.planetaryvorticity`. - - **Examples:** - - Compute absolute vorticity:: - - avrt = w.absolutevorticity() - - Compute absolute vorticity and apply spectral truncation at - triangular T13, also override the default value for Earth's - angular velocity:: - - avrt = w.absolutevorticity(omega=7.2921150, truncation=13) - - """ - avrt = self.api.absolutevorticity(omega=omega, truncation=truncation) - avrt = self._metadata(avrt, - id='absvrt', - units='s**-1', - standard_name='atmosphere_absolute_vorticity', - long_name='absolute vorticity') - return avrt - - def sfvp(self, truncation=None): - """Streamfunction and velocity potential. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *sf*, *vp* - The streamfunction and velocity potential respectively. - - **See also:** - - `~VectorWind.streamfunction`, `~VectorWind.velocitypotential`. - - **Examples:** - - Compute streamfunction and velocity potential:: - - sf, vp = w.sfvp() - - Compute streamfunction and velocity potential and apply spectral - truncation at triangular T13:: - - sfT13, vpT13 = w.sfvp(truncation=13) - - """ - sf, vp = self.api.sfvp(truncation=truncation) - sf = self._metadata( - sf, - id='psi', - units='m**2 s**-1', - standard_name='atmosphere_horizontal_streamfunction', - long_name='streamfunction') - vp = self._metadata( - vp, - id='chi', - units='m**2 s**-1', - standard_name='atmosphere_horizontal_velocity_potential', - long_name='velocity potential') - return sf, vp - - def streamfunction(self, truncation=None): - """Streamfunction. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *sf* - The streamfunction. - - **See also:** - - `~VectorWind.sfvp`. - - **Examples:** - - Compute streamfunction:: - - sf = w.streamfunction() - - Compute streamfunction and apply spectral truncation at - triangular T13:: - - sfT13 = w.streamfunction(truncation=13) - - """ - sf = self.api.streamfunction(truncation=truncation) - sf = self._metadata( - sf, - id='psi', - units='m**2 s**-1', - standard_name='atmosphere_horizontal_streamfunction', - long_name='streamfunction') - return sf - - def velocitypotential(self, truncation=None): - """Velocity potential. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *vp* - The velocity potential. - - **See also:** - - `~VectorWind.sfvp`. - - **Examples:** - - Compute velocity potential:: - - vp = w.velocity potential() - - Compute velocity potential and apply spectral truncation at - triangular T13:: - - vpT13 = w.velocity potential(truncation=13) - - """ - vp = self.api.velocitypotential(truncation=truncation) - vp = self._metadata( - vp, - id='chi', - units='m**2 s**-1', - standard_name='atmosphere_horizontal_velocity_potential', - long_name='velocity potential') - return vp - - def helmholtz(self, truncation=None): - """Irrotational and non-divergent components of the vector wind. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *uchi*, *vchi*, *upsi*, *vpsi* - Zonal and meridional components of irrotational and - non-divergent wind components respectively. - - **See also:** - - `~VectorWind.irrotationalcomponent`, - `~VectorWind.nondivergentcomponent`. - - **Examples:** - - Compute the irrotational and non-divergent components of the - vector wind:: - - uchi, vchi, upsi, vpsi = w.helmholtz() - - Compute the irrotational and non-divergent components of the - vector wind and apply spectral truncation at triangular T13:: - - uchiT13, vchiT13, upsiT13, vpsiT13 = w.helmholtz(truncation=13) - - """ - uchi, vchi, upsi, vpsi = self.api.helmholtz(truncation=truncation) - uchi = self._metadata(uchi, - id='uchi', - units='m s**-1', - long_name='irrotational_eastward_wind') - vchi = self._metadata(vchi, - id='vchi', - units='m s**-1', - long_name='irrotational_northward_wind') - upsi = self._metadata(upsi, - id='upsi', - units='m s**-1', - long_name='non_divergent_eastward_wind') - vpsi = self._metadata(vpsi, - id='vpsi', - units='m s**-1', - long_name='non_divergent_northward_wind') - return uchi, vchi, upsi, vpsi - - def irrotationalcomponent(self, truncation=None): - """Irrotational (divergent) component of the vector wind. - - .. note:: - - If both the irrotational and non-divergent components are - required then `~VectorWind.helmholtz` should be used instead. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *uchi*, *vchi* - The zonal and meridional components of the irrotational wind - respectively. - - **See also:** - - `~VectorWind.helmholtz`. - - **Examples:** - - Compute the irrotational component of the vector wind:: - - uchi, vchi = w.irrotationalcomponent() - - Compute the irrotational component of the vector wind and apply - spectral truncation at triangular T13:: - - uchiT13, vchiT13 = w.irrotationalcomponent(truncation=13) - - """ - uchi, vchi = self.api.irrotationalcomponent(truncation=truncation) - uchi = self._metadata(uchi, - id='uchi', - units='m s**-1', - long_name='irrotational_eastward_wind') - vchi = self._metadata(vchi, - id='vchi', - units='m s**-1', - long_name='irrotational_northward_wind') - return uchi, vchi - - def nondivergentcomponent(self, truncation=None): - """Non-divergent (rotational) component of the vector wind. - - .. note:: - - If both the non-divergent and irrotational components are - required then `~VectorWind.helmholtz` should be used instead. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *upsi*, *vpsi* - The zonal and meridional components of the non-divergent - wind respectively. - - **See also:** - - `~VectorWind.helmholtz`. - - **Examples:** - - Compute the non-divergent component of the vector wind:: - - upsi, vpsi = w.nondivergentcomponent() - - Compute the non-divergent component of the vector wind and apply - spectral truncation at triangular T13:: - - upsiT13, vpsiT13 = w.nondivergentcomponent(truncation=13) - - """ - upsi, vpsi = self.api.nondivergentcomponent(truncation=truncation) - upsi = self._metadata(upsi, - id='upsi', - units='m s**-1', - long_name='non_divergent_eastward_wind') - vpsi = self._metadata(vpsi, - id='vpsi', - units='m s**-1', - long_name='non_divergent_northward_wind') - return upsi, vpsi - - def gradient(self, chi, truncation=None): - """Computes the vector gradient of a scalar field on the sphere. - - **Argument:** - - *chi* - A scalar field. It must be a `cdms2` variable with the same - latitude and longitude dimensions as the vector wind - components that initialized the `VectorWind` instance. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. - - **Returns:** - - *uchi*, *vchi* - The zonal and meridional components of the vector gradient - respectively. - - **Examples:** - - Compute the vector gradient of absolute vorticity:: - - avrt = w.absolutevorticity() - avrt_zonal, avrt_meridional = w.gradient(avrt) - - Compute the vector gradient of absolute vorticity and apply - spectral truncation at triangular T13:: - - avrt = w.absolutevorticity() - avrt_zonalT13, avrt_meridionalT13 = w.gradient(avrt, truncation=13) - - """ - # Check that the input is a cdms2 variable. - if not cdms2.isVariable(chi): - raise TypeError('scalar field must be a cdms2 variable') - name = chi.id - order = chi.getOrder() - if 'x' not in order or 'y' not in order: - raise ValueError('a latitude-longitude grid is required') - # Assess how to re-order the inputs to be compatible with the - # computation API. - apiorder = 'yx' + ''.join([a for a in order if a not in 'xy']) - chi = chi.reorder(apiorder) - # Do a region selection on the input to ensure the latitude dimension - # is north-to-south. - chi = chi(latitude=(90, -90)) - # Record the shape and axes in the API order. - ishape = chi.shape - axes = chi.getAxisList() - # Re-order to the API order. - chi = to3d(chi) - # Compute the gradient function. - uchi, vchi = self.api.gradient(chi, truncation=truncation) - uchi = uchi.reshape(ishape) - vchi = vchi.reshape(ishape) - # Add meta-data and ensure the shape and order of dimensions - # is the same as input. - uchi = cdms2.createVariable(uchi, axes=axes) - vchi = cdms2.createVariable(vchi, axes=axes) - uchi = uchi.reorder(order) - vchi = vchi.reorder(order) - uchi.id = '{0:s}_zonal'.format(name) - vchi.id = '{0:s}_meridional'.format(name) - uchi.long_name = 'zonal_gradient_of_{0:s}'.format(name) - vchi.long_name = 'meridional_gradient_of_{0:s}'.format(name) - return uchi, vchi - - def truncate(self, field, truncation=None): - """Apply spectral truncation to a scalar field. - - This is useful to represent other fields in a way consistent - with the output of other `VectorWind` methods. - - **Argument:** - - *field* - A scalar field. It must be a `cdms2` variable with the same - latitude and longitude dimensions as the vector wind - components that initialized the `VectorWind` instance. - - **Optional argument:** - - *truncation* - Truncation limit (triangular truncation) for the spherical - harmonic computation. If not specified it will default to - *nlats - 1* where *nlats* is the number of latitudes. - - **Returns:** - - *truncated_field* - The field with spectral truncation applied. - - **Examples:** - - Truncate a scalar field to the computational resolution of the - `VectorWind` instance:: - - scalar_field_truncated = w.truncate(scalar_field) - - Truncate a scalar field to T21:: - - scalar_field_T21 = w.truncate(scalar_field, truncation=21) - - """ - # Check that the input is a cdms2 variable. - if not cdms2.isVariable(field): - raise TypeError('scalar field must be a cdms2 variable') - name = field.id - order = field.getOrder() - if 'x' not in order or 'y' not in order: - raise ValueError('a latitude-longitude grid is required') - # Assess how to re-order the inputs to be compatible with the - # computation API. - apiorder = 'yx' + ''.join([a for a in order if a not in 'xy']) - # Clone the field, this one will be used for the output, and reorder - # its axes to be compatible with the computation API. - field = field.clone() - field = field.reorder(apiorder) - # Do a region selection on the input to ensure the latitude dimension - # is north-to-south. - field = field(latitude=(90, -90)) - # Record the shape and axes in the API order. - ishape = field.shape - # Extract the data from the field in the correct shape for the API. - fielddata = to3d(field.asma()) - # Apply the truncation. - fieldtrunc = self.api.truncate(fielddata, truncation=truncation) - # Set the data values of the field to the re-shaped truncated values. - field[:] = fieldtrunc.reshape(ishape) - # Put the field back in its original order. - field = field.reorder(order) - # Set the variable id to indicate the truncation. - tnumber = truncation or fieldtrunc.shape[0] - 1 - field.id = '{}_T{}'.format(name, tnumber) - return field diff --git a/windspharm/tests/__init__.py b/windspharm/tests/__init__.py index 6ad7fdb..ea7b5a5 100644 --- a/windspharm/tests/__init__.py +++ b/windspharm/tests/__init__.py @@ -28,10 +28,6 @@ # Create a mapping from interface name to VectorWind class. solvers = {'standard': windspharm.standard.VectorWind} -try: - solvers['cdms'] = windspharm.cdms.VectorWind -except AttributeError: - pass try: solvers['iris'] = windspharm.iris.VectorWind except AttributeError: diff --git a/windspharm/tests/reference.py b/windspharm/tests/reference.py index 31da24b..9961963 100644 --- a/windspharm/tests/reference.py +++ b/windspharm/tests/reference.py @@ -44,21 +44,6 @@ def __read_reference_solutions(gridtype): return exact -def _wrap_cdms(reference, lats, lons): - try: - import cdms2 - except ImportError: - raise ValueError("cannot use container 'cdms' without cdms2") - londim = cdms2.createAxis(lons, id='longitude') - londim.designateLongitude() - latdim = cdms2.createAxis(lats, id='latitude') - latdim.designateLatitude() - for name in reference.keys(): - reference[name] = cdms2.createVariable(reference[name], - axes=[latdim, londim], - id=name) - - def _wrap_iris(reference, lats, lons): try: from iris.cube import Cube @@ -100,9 +85,7 @@ def _wrap_xarray(reference, lats, lons): def _get_wrapper(container_type): - if container_type == 'cdms': - return _wrap_cdms - elif container_type == 'iris': + if container_type == 'iris': return _wrap_iris elif container_type == 'xarray': return _wrap_xarray @@ -113,7 +96,7 @@ def _get_wrapper(container_type): def reference_solutions(container_type, gridtype): """Generate reference solutions in the required container.""" container_type = container_type.lower() - if container_type not in ('standard', 'iris', 'cdms', 'xarray'): + if container_type not in ('standard', 'iris', 'xarray'): raise ValueError("unknown container type: " "'{!s}'".format(container_type)) reference = __read_reference_solutions(gridtype) diff --git a/windspharm/tests/test_error_handling.py b/windspharm/tests/test_error_handling.py index f464401..1c73539 100644 --- a/windspharm/tests/test_error_handling.py +++ b/windspharm/tests/test_error_handling.py @@ -140,97 +140,6 @@ def test_gradient_invalid_shape(self): vw.gradient(solution['chi'][:-1]) -# ---------------------------------------------------------------------------- -# Tests for the cdms interface - - -class TestCDMSErrorHandlers(ErrorHandlersTest): - """cdms interface error handler tests.""" - interface = 'cdms' - gridtype = 'regular' - - def test_non_variable_input(self): - # input not a cdms2 variable should raise an error - solution = reference_solutions('standard', self.gridtype) - with pytest.raises(TypeError): - solvers[self.interface](solution['uwnd'], solution['vwnd']) - - def test_different_shape_components(self): - # inputs not the same shape should raise an error - solution = reference_solutions(self.interface, self.gridtype) - with pytest.raises(ValueError): - solvers[self.interface](solution['uwnd'], - solution['vwnd'].reorder('xy')) - - def test_unknown_grid(self): - # inputs where a lat-lon grid cannot be identified should raise an - # error - solution = reference_solutions(self.interface, self.gridtype) - lat = solution['vwnd'].getLatitude() - delattr(lat, 'axis') - lat.id = 'unknown' - with pytest.raises(ValueError): - solvers[self.interface](solution['uwnd'], solution['vwnd']) - - def test_non_variable_gradient_input(self): - # input to gradient not a cdms2 variable should raise an error - solution = reference_solutions(self.interface, self.gridtype) - vw = solvers[self.interface](solution['uwnd'], solution['vwnd']) - dummy_solution = reference_solutions('standard', self.gridtype) - with pytest.raises(TypeError): - vw.gradient(dummy_solution['chi']) - - def test_gradient_non_variable_input(self): - # input to gradient not a cdms2 variable should raise an error - solution = reference_solutions(self.interface, self.gridtype) - vw = solvers[self.interface](solution['uwnd'], solution['vwnd']) - dummy_solution = reference_solutions('standard', self.gridtype) - with pytest.raises(TypeError): - vw.gradient(dummy_solution['chi']) - - def test_gradient_different_shape(self): - # input to gradient of different shape should raise an error - solution = reference_solutions(self.interface, self.gridtype) - vw = solvers[self.interface](solution['uwnd'], solution['vwnd']) - with pytest.raises(ValueError): - vw.gradient(solution['chi'][:-1]) - - def test_gradient_unknown_grid(self): - # input to gradient with no identifiable grid should raise an error - solution = reference_solutions(self.interface, self.gridtype) - vw = solvers[self.interface](solution['uwnd'], solution['vwnd']) - lat = solution['chi'].getLatitude() - delattr(lat, 'axis') - lat.id = 'unknown' - with pytest.raises(ValueError): - vw.gradient(solution['chi']) - - def test_truncate_non_variable_input(self): - # input to truncate not a cdms2 variable should raise an error - solution = reference_solutions(self.interface, self.gridtype) - vw = solvers[self.interface](solution['uwnd'], solution['vwnd']) - dummy_solution = reference_solutions('standard', self.gridtype) - with pytest.raises(TypeError): - vw.truncate(dummy_solution['chi']) - - def test_truncate_different_shape(self): - # input to truncate of different shape should raise an error - solution = reference_solutions(self.interface, self.gridtype) - vw = solvers[self.interface](solution['uwnd'], solution['vwnd']) - with pytest.raises(ValueError): - vw.truncate(solution['chi'][:-1]) - - def test_truncate_unknown_grid(self): - # input to truncate with no identifiable grid should raise an error - solution = reference_solutions(self.interface, self.gridtype) - vw = solvers[self.interface](solution['uwnd'], solution['vwnd']) - lat = solution['chi'].getLatitude() - delattr(lat, 'axis') - lat.id = 'unknown' - with pytest.raises(ValueError): - vw.truncate(solution['chi']) - - # ---------------------------------------------------------------------------- # Tests for the iris interface diff --git a/windspharm/tests/test_solution.py b/windspharm/tests/test_solution.py index a2976e5..7bb5e5c 100644 --- a/windspharm/tests/test_solution.py +++ b/windspharm/tests/test_solution.py @@ -228,89 +228,6 @@ class TestStandardLegfuncComputed(StandardSolutionTest): legfunc = 'computed' -# ---------------------------------------------------------------------------- -# Tests for the CDMS interface - - -class CDMSSolutionTest(SolutionTest): - """Base class for all CDMS interface solution test classes.""" - interface = 'cdms' - - def test_truncate_reversed(self): - # vorticity truncated to T21 matches reference? - vrt_trunc = self.vw.truncate(self.solution['vrt'][::-1], truncation=21) - self.assert_error_is_zero(vrt_trunc, self.solution['vrt_trunc']) - - -class TestCDMSRegular(CDMSSolutionTest): - """Regular grid.""" - gridtype = 'regular' - - -class TestCDMSGaussian(CDMSSolutionTest): - """Gaussian grid.""" - gridtype = 'gaussian' - - -class TestCDMSGridTranspose(CDMSSolutionTest): - gridtype = 'regular' - - @classmethod - def pre_modify_solution(cls): - for field_name in cls.solution: - cls.solution[field_name] = cls.solution[field_name].reorder('xy') - - def test_truncate_reversed(self): - # vorticity truncated to T21 matches reference? - vrt_trunc = self.vw.truncate(self.solution['vrt'][:, ::-1], - truncation=21) - self.assert_error_is_zero(vrt_trunc, self.solution['vrt_trunc']) - - -class TestCDMSInvertedLatitude(CDMSSolutionTest): - gridtype = 'regular' - - @classmethod - def pre_modify_solution(cls): - for field_name in ('uwnd', 'vwnd'): - cls.solution[field_name] = \ - cls.solution[field_name](latitude=(-90, 90)) - - @classmethod - def post_modify_solution(cls): - for field_name in ('uwnd', 'vwnd'): - cls.solution[field_name] = \ - cls.solution[field_name](latitude=(90, -90)) - - -class TestCDMSRadiusDefaultExplicit(CDMSSolutionTest): - gridtype = 'regular' - radius = 6.3712e6 - - -class TestCDMSRadius(CDMSSolutionTest): - gridtype = 'regular' - radius = 6.3712e6 / 16. - - @classmethod - def post_modify_solution(cls): - # Divergence and vorticity should be scaled by the inverse of the - # radius factor. - cls.solution['vrt'] = cls.solution['vrt'] * 16. - cls.solution['div'] = cls.solution['div'] * 16. - cls.solution['vrt_trunc'] = cls.solution['vrt_trunc'] * 16 - # Stream function and velocity potential should be scaled by the - # radius factor. - cls.solution['psi'] = cls.solution['psi'] / 16 - cls.solution['chi'] = cls.solution['chi'] / 16 - - -class TestCDMSLegfuncComputed(CDMSSolutionTest): - """Computed Legendre functions.""" - gridtype = 'regular' - legfunc = 'computed' - - # ---------------------------------------------------------------------------- # Tests for the Iris interface diff --git a/windspharm/tests/utils.py b/windspharm/tests/utils.py index 627a896..5d39d83 100644 --- a/windspharm/tests/utils.py +++ b/windspharm/tests/utils.py @@ -35,10 +35,9 @@ def __tomasked(*args): - """Convert cdms2 variables or iris cubes to masked arrays. + """Convert supported data types to masked arrays. - The conversion is safe, so if non-variables/cubes are passed they - are just returned. + The conversion is safe, so anything not recognised is just returned. """ def __asma(a): @@ -48,13 +47,6 @@ def __asma(a): a = a.data except NameError: pass - try: - # Retrieve data from cdms variable. - a = a.asma() - except AttributeError: - # The input is already an array or masked array, either extracted - # from an iris cube, or was like that to begin with. - pass try: if isinstance(a, xr.DataArray): a = a.values