diff --git a/.bmi/api.yaml b/.bmi/api.yaml deleted file mode 100644 index ea56433..0000000 --- a/.bmi/api.yaml +++ /dev/null @@ -1,8 +0,0 @@ -name: HeatPy -language: python - -package: heat -class: BmiHeat - -build: - - python setup.py install diff --git a/.bmi/heat_input.txt.tmpl b/.bmi/heat_input.txt.tmpl deleted file mode 100644 index f37cd38..0000000 --- a/.bmi/heat_input.txt.tmpl +++ /dev/null @@ -1 +0,0 @@ -{thermal_diffusivity}, {run_duration}, {number_of_columns}, {number_of_rows} diff --git a/.bmi/info.yaml b/.bmi/info.yaml deleted file mode 100644 index 5bcbacd..0000000 --- a/.bmi/info.yaml +++ /dev/null @@ -1,4 +0,0 @@ -url: https://github.com/csdms/bmi-python -author: Eric Hutton -email: eric.hutton@colorado.edu -version: 0.1 diff --git a/.bmi/parameters.yaml b/.bmi/parameters.yaml deleted file mode 100644 index 76459ac..0000000 --- a/.bmi/parameters.yaml +++ /dev/null @@ -1,44 +0,0 @@ -%YAML 1.2 ---- -run_duration: - description: Simulation run time - value: - type: float - default: 1. - units: s - range: - min: 0 - max: 1000000 ---- -thermal_diffusivity: - name: Thermal diffusivity - description: Thermal diffusivity - value: - type: float - default: 1. - range: - min: 0.0 - max: 10.0 - units: m^2/s ---- -number_of_rows: - name: Number of rows - description: Number of grid rows. - value: - type: int - default: 10 - range: - min: 0 - max: 1000 - units: - - -number_of_columns: - name: Number of columns - description: Number of grid columns. - value: - type: int - default: 10 - range: - min: 0 - max: 1000 - units: - diff --git a/.codacy.yaml b/.codacy.yaml new file mode 100644 index 0000000..42e47a4 --- /dev/null +++ b/.codacy.yaml @@ -0,0 +1,6 @@ +exclude_paths: + - tests/** + - docs/source/conf.py + - setup.py + - versioneer.py + - heat/_version.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..561ca09 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +heat/_version.py export-subst diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 49a0cb0..0000000 --- a/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "docs/scipy-sphinx-theme"] - path = docs/scipy-sphinx-theme - url = https://github.com/scipy/scipy-sphinx-theme -[submodule "docs/sphinxext"] - path = docs/sphinxext - url = https://github.com/numpy/numpydoc diff --git a/.landscape.yaml b/.landscape.yaml deleted file mode 100644 index e3ff739..0000000 --- a/.landscape.yaml +++ /dev/null @@ -1,7 +0,0 @@ -ignore-patterns: - - ez_setup.py - - setup.py - - bmi_ext.py - - conf.py -strictness: veryhigh -doc-warnings: True diff --git a/.travis.yml b/.travis.yml index 2caa9b6..35dcd63 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,24 +1,58 @@ -language: python -python: - - "2.7" - - "3.5" - - "3.6" - +language: generic os: - - linux - +- linux +- osx +env: + matrix: + - CONDA_ENV=3.7 + - CONDA_ENV=3.6 +sudo: false +jobs: + include: + - stage: lint + os: linux + script: + - make lint + - stage: docs + os: linux + install: + - conda env create --file docs/source/environment.yml + - conda activate heat_docs + script: + - sphinx-apidoc --force -o docs heat *tests + - make -C docs clean html + - stage: deploy + if: tag =~ v.*$ + script: skip + os: linux + deploy: + on: + all_branches: true + provider: pypi + user: mcflugen + password: + secure: nCLTNxxwRBpvaeNosG+V1sQHeYPDd7zfcBvm5sGE6KVtGOfQtO0cNe1NwMKoVKH9Te9B2RJGs+s6tb4mMqJNuXpTyoFsAr+4gBxO9BSAdjm2wadcqyXexhU99L9oBhfrMAuGYEvV57LE57WaRQfmBnnKH9HE57fWmsx8VO50DEw3mMWKusZt4aFxNgpKwjUGJxtYDEIoOzfOdWAlRicPsZ21s/oMsrYKaYMG8mI8uM5/nVGc2jCb18HXflG9LnsmXlU8P/Jfa0Zu52MRgHuJnyflIDolgjkqPSgu8v/pGhjTCOS88tWSC09mIy1mdkZzJOOiIny+CLkEWxcQbikiVaXwq592+I6YcnW9TAls2hOChFaALYldZd5EopOmlc64DmQXMXCOPLbMM4wiUx63F/zJDZg1i0sMl0ucG5EpNPG18EerdygbvdcLLYKM70jSuqyYBOjk4pAO6Y1EvjffZMBu1XxuO/NvTZyAjoJTTb8xbO4s59Z7KB8sYi+9Gq1DATq1YXZ8k3GoU+KlOGJ73o+D87O95Q5qLWI30HvElKj72eEGMCsOTyvxmNZsEf9yCYbxzP9FEWrWV1uWUwWEV6tAATd7o3bcbp8+DzeglaLX8eOch8MwtxqR2aFvoiMQVTIXkfrn+emuZzhqQcTZSQMA9SztnQ8it4F7WeQWqH8= +before_install: +- | + if [[ $TRAVIS_OS_NAME == "osx" ]]; then + brew remove --force $(brew list) + brew cleanup -s + rm -rf $(brew --cache) + fi +- | + if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then + curl https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh > $HOME/miniconda.sh + else + curl https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh > $HOME/miniconda.sh + fi +- bash $HOME/miniconda.sh -b -p $HOME/anaconda +- export PATH="$HOME/anaconda/bin:$PATH" +- hash -r +- conda config --set always_yes yes --set changeps1 no +- conda create -n test_env python=$CONDA_ENV +- source activate test_env install: - - echo "Build on $TRAVIS_OS_NAME for Python $TRAVIS_PYTHON_VERSION" - - bash .travis/install_python.sh - - export PATH="$HOME/miniconda/bin:$PATH" - - source activate test-env - - pip install coveralls - - conda info - - conda list - - python setup.py install - +- pip install . -r requirements.txt script: - - nosetests --with-doctest --with-coverage --cover-package=heat - -after_success: - coveralls +- pytest --cov=heat --cov-report=xml:$(pwd)/coverage.xml -vvv +after_success: coveralls diff --git a/.travis/install_python.sh b/.travis/install_python.sh deleted file mode 100644 index e4a3bf3..0000000 --- a/.travis/install_python.sh +++ /dev/null @@ -1,30 +0,0 @@ -#! /bin/bash - -if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then - OS="MacOSX-x86_64"; -else - OS="Linux-x86_64"; -fi -sudo apt-get update 2> /dev/null || echo "No apt-get" -if [[ "$TRAVIS_PYTHON_VERSION" == 2.* ]]; then - wget http://repo.continuum.io/miniconda/Miniconda-latest-$OS.sh -O miniconda.sh; -else - wget http://repo.continuum.io/miniconda/Miniconda3-latest-$OS.sh -O miniconda.sh; -fi -echo "Install miniconda" -bash miniconda.sh -b -p $HOME/miniconda -export PATH="$HOME/miniconda/bin:$PATH" -echo "Using this conda: $(which conda)" -hash -r -conda config --set always_yes yes --set changeps1 no -echo "Update conda" -conda update -q conda -echo "conda info" -conda info -a -echo "Install packages" -cat requirements.txt | xargs conda create -q -n test-env python=$TRAVIS_PYTHON_VERSION -echo "Activate environment" -source activate test-env -echo "Using this python: $(which python)" -conda install coverage -conda install sphinx diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..28ed8e6 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include versioneer.py +include heat/_version.py diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..783b25d --- /dev/null +++ b/Makefile @@ -0,0 +1,92 @@ +.PHONY: clean clean-test clean-pyc clean-build docs help +.DEFAULT_GOAL := help + +define BROWSER_PYSCRIPT +import os, webbrowser, sys + +try: + from urllib import pathname2url +except: + from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT + +BROWSER := python -c "$$BROWSER_PYSCRIPT" + +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + +clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: ## remove test and coverage artifacts + rm -fr .tox/ + rm -f .coverage + rm -fr htmlcov/ + rm -fr .pytest_cache + +lint: ## check style with flake8 + flake8 heat tests + +pretty: + find heat -name '*.py' | xargs isort + black setup.py tests heat + +test: ## run tests quickly with the default Python + pytest + +test-all: ## run tests on every Python version with tox + tox + +coverage: ## check code coverage quickly with the default Python + coverage run --source heat -m pytest + coverage report -m + coverage html + $(BROWSER) htmlcov/index.html + +docs: ## generate Sphinx HTML documentation, including API docs + rm -f docs/source/heat.rst + rm -f docs/source/modules.rst + sphinx-apidoc -o docs/source heat + $(MAKE) -C docs clean + $(MAKE) -C docs html + $(BROWSER) docs/build/html/index.html + +servedocs: docs ## compile the docs watching for changes + watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . + +release: dist ## package and upload a release + twine upload dist/* + +dist: clean ## builds source and wheel package + python setup.py sdist + python setup.py bdist_wheel + ls -l dist + +install: clean ## install the package to the active Python's site-packages + python setup.py develop diff --git a/README.md b/README.md deleted file mode 100644 index f014548..0000000 --- a/README.md +++ /dev/null @@ -1,9 +0,0 @@ -[![Build Status](https://travis-ci.org/csdms/bmi-python.svg?branch=master)](https://travis-ci.org/csdms/bmi-python) -[![Coverage Status](https://coveralls.io/repos/csdms/bmi-python/badge.png?branch=master)](https://coveralls.io/r/csdms/bmi-python?branch=master) -[![Code Health](https://landscape.io/github/csdms/bmi-python/master/landscape.svg)](https://landscape.io/github/csdms/bmi-python/master) -[![Documentation Status](https://readthedocs.org/projects/bmi-forum/badge/?version=latest)](https://readthedocs.org/projects/bmi-forum/?badge=latest) - -bmi-python -========== - -Python-Bindings for the Basic Modeling Interface diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..ee077b6 --- /dev/null +++ b/README.rst @@ -0,0 +1,23 @@ +.. image:: https://img.shields.io/badge/CSDMS-Basic%20Model%20Interface-green.svg + :target: https://bmi.readthedocs.io/ + :alt: Basic Model Interface + +.. image:: https://travis-ci.org/csdms/bmi-example-python.svg?branch=master + :target: https://travis-ci.org/csdms/bmi-example-python + +.. image:: https://coveralls.io/repos/csdms/bmi-example-python/badge.png?branch=master + :target: https://coveralls.io/r/csdms/bmi-example-python?branch=master + +.. image:: https://readthedocs.org/projects/bmi-forum/badge/?version=latest + :target: https://readthedocs.org/projects/bmi-forum/?badge=latest + +.. image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/csdms/bmi + +.. image:: https://api.codacy.com/project/badge/Grade/e0252b85fefc402ea4cc5e7949219a94 + :target: https://www.codacy.com/app/mcflugen/bmi-example-python?utm_source=github.com&utm_medium=referral&utm_content=csdms/bmi-example-python&utm_campaign=Badge_Grade + +bmi-example-python +================== + +An example BMI implementation written in Python diff --git a/bmi/__init__.py b/bmi/__init__.py deleted file mode 100644 index 29f5766..0000000 --- a/bmi/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""The Basic Model Interface.""" -from .bmi import Bmi - - -__all__ = ['Bmi'] diff --git a/bmi/base.py b/bmi/base.py deleted file mode 100644 index 66986b8..0000000 --- a/bmi/base.py +++ /dev/null @@ -1,115 +0,0 @@ -#! /usr/bin/env python -"""Interface to the basic control functions of a model.""" - - -class BmiBase(object): - - """Functions that control model execution. - - These BMI functions are critical to plug-and-play modeling because they - give a calling component fine-grained control over the model execution. - """ - - def initialize(self, filename): - """Perform startup tasks for the model. - - Perform all tasks that take place before entering the model's time - loop, including opening files and initializing the model state. Model - inputs are read from a text-based configuration file, specified by - `filename`. - - Parameters - ---------- - filename : str, optional - The path to the model configuration file. - - Notes - ----- - Models should be refactored, if necessary, to use a - configuration file. CSDMS does not impose any constraint on - how configuration files are formatted, although YAML is - recommended. A template of a model's configuration file - with placeholder values is used by the BMI. - - .. code-block:: c - - /* C */ - int initialize(void *self, char * filename); - """ - pass - - def update(self): - """Advance model state by one time step. - - Perform all tasks that take place within one pass through the model's - time loop. This typically includes incrementing all of the model's - state variables. If the model's state variables don't change in time, - then they can be computed by the :func:`initialize` method and this - method can return with no action. - - Notes - ----- - .. code-block:: c - - /* C */ - int update(void *self); - """ - pass - - def update_until(self, time): - """Advance model state until the given time. - - Parameters - ---------- - time : float - A model time value. - - See Also - -------- - update - - Notes - ----- - .. code-block:: c - - /* C */ - int update_until(void *self, double time); - """ - pass - - def update_frac(self, time_frac): - """Advance model state by a fraction of a time step. - - Parameters - ---------- - time_frac : float - A fraction of a model time step value. - - See Also - -------- - update - - Notes - ----- - .. code-block:: c - - /* C */ - int update_frac(void *self, double time_frac); - """ - pass - - def finalize(self): - """Perform tear-down tasks for the model. - - Perform all tasks that take place after exiting the model's time - loop. This typically includes deallocating memory, closing files and - printing reports. - - Notes - ----- - .. code-block:: c - - /* C */ - int finalize(void *self); - """ - pass diff --git a/bmi/bmi.py b/bmi/bmi.py deleted file mode 100644 index 7f4bedc..0000000 --- a/bmi/bmi.py +++ /dev/null @@ -1,26 +0,0 @@ -#! /usr/bin/env python -"""The complete Basic Model Interface.""" - - -from .base import BmiBase -from .info import BmiInfo -from .time import BmiTime -from .vars import BmiVars -from .getter_setter import BmiGetter, BmiSetter -from .grid_rectilinear import BmiGridRectilinear -from .grid_uniform_rectilinear import BmiGridUniformRectilinear -from .grid_structured_quad import BmiGridStructuredQuad -from .grid_unstructured import BmiGridUnstructured - - -class Bmi(BmiBase, BmiInfo, BmiTime, BmiVars, BmiGetter, BmiSetter, - BmiGridRectilinear, BmiGridUniformRectilinear, BmiGridStructuredQuad, - BmiGridUnstructured): - - """The complete Basic Model Interface. - - Defines an interface for converting a standalone model into an - integrated modeling framework component. - """ - - pass diff --git a/bmi/getter_setter.py b/bmi/getter_setter.py deleted file mode 100644 index 868942b..0000000 --- a/bmi/getter_setter.py +++ /dev/null @@ -1,144 +0,0 @@ -#! /usr/bin/env python -"""Interface for getting and setting a model's internal variables.""" - - -class BmiGetter(object): - - """Get values from a component. - - Methods that get variables from a model's state. Often a model's state - variables are changing with each time step, so getters are called to get - current values. - """ - - def get_value(self, var_name): - """Get a copy of values of the given variable. - - This is a getter for the model, used to access the model's - current state. It returns a *copy* of a model variable, with - the return type, size and rank dependent on the variable. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - - Returns - ------- - array_like - The value of a model variable. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_value(void * self, const char * var_name, void * buffer); - """ - pass - - def get_value_ref(self, var_name): - """Get a reference to values of the given variable. - - This is a getter for the model, used to access the model's - current state. It returns a reference to a model variable, - with the return type, size and rank dependent on the variable. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - - Returns - ------- - array_like - A reference to a model variable. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_value_ref(void * self, const char * var_name, - void ** buffer); - """ - pass - - def get_value_at_indices(self, var_name, indices): - """Get values at particular indices. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - indices : array_like - The indices into the variable array. - - Returns - ------- - array_like - Value of the model variable at the given location. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_value_at_indices(void * self, const char * var_name, - void * buffer, int * indices, int len); - """ - pass - - -class BmiSetter(object): - - """Set values into a component. - - Methods that set variables of a model's state. - """ - - def set_value(self, var_name, src): - """Specify a new value for a model variable. - - This is the setter for the model, used to change the model's - current state. It accepts, through *src*, a new value for a - model variable, with the type, size and rank of *src* - dependent on the variable. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - src : array_like - The new value for the specified variable. - - Notes - ----- - .. code-block:: c - - /* C */ - int set_value(void * self, const char * var_name, void * src); - """ - pass - - def set_value_at_indices(self, var_name, indices, src): - """Specify a new value for a model variable at particular indices. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - indices : array_like - The indices into the variable array. - src : array_like - The new value for the specified variable. - - Notes - ----- - .. code-block:: c - - /* C */ - int set_value_at_indices(void * self, const char * var_name, - int * indices, int len, void * src); - """ - pass diff --git a/bmi/grid.py b/bmi/grid.py deleted file mode 100644 index ac4209e..0000000 --- a/bmi/grid.py +++ /dev/null @@ -1,87 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes uniform rectilinear grids.""" - - -class BmiGrid(object): - - """Methods that describe a grid. - - """ - - def get_grid_rank(self, grid_id): - """Get number of dimensions of the computational grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - int - Rank of the grid. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_rank(void * self, int grid_id, int * rank); - """ - pass - - def get_grid_size(self, grid_id): - """Get the total number of elements in the computational grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - int - Size of the grid. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_size(void * self, int grid_id, int * size); - """ - pass - - def get_grid_type(self, grid_id): - """Get the grid type as a string. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - str - Type of grid as a string. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_type(void * self, int grid_id, char * type); - """ - pass diff --git a/bmi/grid_rectilinear.py b/bmi/grid_rectilinear.py deleted file mode 100644 index 0888267..0000000 --- a/bmi/grid_rectilinear.py +++ /dev/null @@ -1,126 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes rectilinear grids.""" - -from .grid import BmiGrid - - -class BmiGridRectilinear(BmiGrid): - - """Methods that describe a rectilinear grid. - - In a 2D rectilinear grid, every grid cell (or element) is a rectangle but - different cells can have different dimensions. All cells in the same row - have the same grid spacing in the y direction and all cells in the same - column have the same grid spacing in the x direction. Grid spacings can - be computed as the difference of successive x or y values. - - .. figure:: _static/grid_rectilinear.png - :scale: 10% - :align: center - :alt: An example of a rectilinear grid - """ - - def get_grid_shape(self, grid_id): - """Get dimensions of the computational grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - tuple of int - The dimensions of the grid. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_shape(void * self, const char * var_name, - int * shape); - """ - pass - - def get_grid_x(self, grid_id): - """Get coordinates of grid nodes in the streamwise direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like of float - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_x(void * self, const char * var_name, double * x); - """ - pass - - def get_grid_y(self, grid_id): - """Get coordinates of grid nodes in the transverse direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like of float - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_y(void * self, const char * var_name, double * y); - """ - pass - - def get_grid_z(self, grid_id): - """Get coordinates of grid nodes in the normal direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like of float - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_z(void * self, const char * var_name, double * z); - """ - pass diff --git a/bmi/grid_structured_quad.py b/bmi/grid_structured_quad.py deleted file mode 100644 index 267e00c..0000000 --- a/bmi/grid_structured_quad.py +++ /dev/null @@ -1,119 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes structured quadrilateral grids.""" - -from .grid import BmiGrid - - -class BmiGridStructuredQuad(BmiGrid): - - """Methods that describe a structured grid of quadrilaterals. - - .. figure:: _static/grid_structured_quad.png - :scale: 10% - :align: center - :alt: An example of a structured quad grid. - """ - - def get_grid_shape(self, grid_id): - """Get dimensions of the computational grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The dimensions of the grid. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_shape(void * self, int grid_id, int * shape); - """ - pass - - def get_grid_x(self, grid_id): - """Get coordinates of grid nodes in the streamwise direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_x(void * self, int grid_id, double * x); - """ - pass - - def get_grid_y(self, grid_id): - """Get coordinates of grid nodes in the transverse direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_y(void * self, int grid_id, double * y); - """ - pass - - def get_grid_z(self, grid_id): - """Get coordinates of grid nodes in the normal direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_z(void * self, int grid_id, double * z); - """ - pass diff --git a/bmi/grid_uniform_rectilinear.py b/bmi/grid_uniform_rectilinear.py deleted file mode 100644 index 620cee8..0000000 --- a/bmi/grid_uniform_rectilinear.py +++ /dev/null @@ -1,106 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes uniform rectilinear grids.""" - -from .grid import BmiGrid - - -class BmiGridUniformRectilinear(BmiGrid): - - """Methods that describe a uniform rectilinear grid. - - In a 2D uniform grid, every grid cell (or element) is a rectangle and all - cells have the same dimensions. If the dimensions are equal, then the - grid is a tiling of squares. - - Each of these functions returns information about each dimension of a - grid. The dimensions are ordered with "ij" indexing (as opposed to "xy"). - For example, the :func:`get_grid_shape` function for the example grid would - return the array ``[4, 5]``. If there were a third dimension, the length of - the z dimension would be listed first. This same convention is used in - NumPy. Note that the grid shape is the number of nodes in the coordinate - directions and not the number of cells or elements. It is possible for - grid values to be associated with the nodes or with the cells. - - .. figure:: _static/grid_uniform_rectilinear.png - :scale: 10% - :align: center - :alt: An example of a uniform rectilinear grid - """ - - def get_grid_shape(self, grid_id): - """Get dimensions of the computational grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The dimensions of the grid. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_shape(void * self, int grid_id, int * shape); - """ - pass - - def get_grid_spacing(self, grid_id): - """Get distance between nodes of the computational grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The grid spacing. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_spacing(void * self, int grid_id, double * spacing); - """ - pass - - def get_grid_origin(self, grid_id): - """Get coordinates for the origin of the computational grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The coordinates of the lower left corner of the grid. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_origin(void * self, int grid_id, double * origin); - """ - pass diff --git a/bmi/grid_unstructured.py b/bmi/grid_unstructured.py deleted file mode 100644 index 82f981f..0000000 --- a/bmi/grid_unstructured.py +++ /dev/null @@ -1,146 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes unstructured grids.""" - -from .grid import BmiGrid - - -class BmiGridUnstructured(BmiGrid): - - """Methods that describe an unstructured grid. - - .. figure:: _static/grid_unstructured.png - :scale: 10% - :align: center - :alt: An example of an unstructured grid. - """ - - def get_grid_x(self, grid_id): - """Get coordinates of grid nodes in the streamwise direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_x(void * self, int grid_id, double * x); - """ - pass - - def get_grid_y(self, grid_id): - """Get coordinates of grid nodes in the transverse direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_y(void * self, int grid_id, double * y); - """ - pass - - def get_grid_z(self, grid_id): - """Get coordinates of grid nodes in the normal direction. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like - The positions of the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_z(void * self, int grid_id, double * z); - """ - pass - - def get_grid_connectivity(self, grid_id): - """Get connectivity array of the grid. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like or int - The graph of connections between the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_connectivity(void * self, int grid_id, - int * connectivity); - """ - pass - - def get_grid_offset(self, grid_id): - """Get offsets for the grid nodes. - - Parameters - ---------- - grid_id : int - A grid identifier. - - Returns - ------- - array_like of int - The offsets for the grid nodes. - - See Also - -------- - bmi.vars.BmiVars.get_var_grid : Obtain a `grid_id`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_grid_offset(void * self, int grid_id, int * offset); - """ - pass diff --git a/bmi/info.py b/bmi/info.py deleted file mode 100644 index 65eb149..0000000 --- a/bmi/info.py +++ /dev/null @@ -1,77 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes a model and its input and output variables.""" - - -class BmiInfo(object): - - """Get metadata about a model.""" - - def get_component_name(self): - """Name of the component. - - Returns - ------- - str - The name of the component. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_component_name(void * self, char * name); - """ - pass - - def get_input_var_names(self): - """List of a model's input variables. - - Input variable names must be CSDMS Standard Names, also known - as *long variable names*. - - Returns - ------- - list of str - The input variables for the model. - - Notes - ----- - Standard Names enable the CSDMS framework to determine whether - an input variable in one model is equivalent to, or compatible - with, an output variable in another model. This allows the - framework to automatically connect components. - - Standard Names do not have to be used within the model. - - .. code-block:: c - - /* C */ - int get_input_var_name_count(void * self, int * count); - int get_input_var_names(void * self, char ** names); - """ - pass - - def get_output_var_names(self): - """List of a model's output variables. - - Output variable names must be CSDMS Standard Names, also known - as *long variable names*. - - Returns - ------- - list of str - The output variables for the model. - - See Also - -------- - get_input_var_names - - Notes - ----- - .. code-block:: c - - /* C */ - int get_output_var_name_count(void * self, int * count); - int get_output_var_names(void * self, char ** names); - """ - pass diff --git a/bmi/time.py b/bmi/time.py deleted file mode 100644 index 434125d..0000000 --- a/bmi/time.py +++ /dev/null @@ -1,108 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes the time stepping of a model.""" - - -class BmiTime(object): - - """Methods that get time information from a model.""" - - def get_start_time(self): - """Start time of the model. - - Model times should be of type float. The default model start - time is 0. - - Returns - ------- - float - The model start time. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_start_time(void * self, double * time); - """ - pass - - def get_current_time(self): - """Current time of the model. - - Returns - ------- - float - The current model time. - - See Also - -------- - get_start_time - - Notes - ----- - .. code-block:: c - - /* C */ - int get_current_time(void * self, double * time); - """ - pass - - def get_end_time(self): - """End time of the model. - - Returns - ------- - float - The maximum model time. - - See Also - -------- - get_start_time - - Notes - ----- - .. code-block:: c - - /* C */ - int get_end_time(void * self, double * time); - """ - pass - - def get_time_step(self): - """Current time step of the model. - - The model time step should be of type float. The default time - step is 1.0. - - Returns - ------- - float - The time step used in model. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_time_step(void * self, double * dt); - """ - pass - - def get_time_units(self): - """Time units of the model. - - CSDMS uses the UDUNITS standard from Unidata. - - Returns - ------- - float - The model time unit; e.g., `days` or `s`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_time_units(void * self, char * units); - """ - pass diff --git a/bmi/vars.py b/bmi/vars.py deleted file mode 100644 index 4172fef..0000000 --- a/bmi/vars.py +++ /dev/null @@ -1,144 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes a model's input and output variables.""" - - -class BmiVars(object): - - """Methods that get information about input and output variables. - - These BMI functions obtain information about a particular input or output - variable. They must accommodate any variable that is returned by the BMI - functions :func:`~bmi.info.BmiInfo.get_input_var_names` or - :func:`~bmi.info.BmiInfo.get_output_var_names`. - """ - - def get_var_type(self, var_name): - """Get data type of the given variable. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - - Returns - ------- - str - The Python variable type; e.g., ``str``, ``int``, ``float``. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_var_type(void * self, const char * var_name, char * type); - """ - pass - - def get_var_units(self, var_name): - """Get units of the given variable. - - Standard unit names, in lower case, should be used, such as - ``meters`` or ``seconds``. Standard abbreviations, like ``m`` for - meters, are also supported. For variables with compound units, - each unit name is separated by a single space, with exponents - other than 1 placed immediately after the name, as in ``m s-1`` - for velocity, ``W m-2`` for an energy flux, or ``km2`` for an - area. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - - Returns - ------- - str - The variable units. - - Notes - ----- - CSDMS uses the `UDUNITS`_ standard from Unidata. - - .. code-block:: c - - /* C */ - int get_var_units(void * self, const char * var_name, - char * units); - - .. _UDUNITS: http://www.unidata.ucar.edu/software/udunits - - """ - pass - - def get_var_itemsize(self, var_name): - """Get memory use for each array element in bytes. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - - Returns - ------- - int - Item size in bytes. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_var_itemsize(void * self, const char * var_name, - int * itemsize); - """ - pass - - def get_var_nbytes(self, var_name): - """Get size, in bytes, of the given variable. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - - Returns - ------- - int - The size of the variable, counted in bytes. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_var_nbytes(void * self, const char * var_name, - int * nbytes); - """ - pass - - def get_var_grid(self, var_name): - """Get grid identifier for the given variable. - - Parameters - ---------- - var_name : str - An input or output variable name, a CSDMS Standard Name. - - Returns - ------- - int - The grid identifier. - - See Also - -------- - bmi.info.BmiInfo.get_input_var_names : Get *var_name* from this - method or from :func:`~bmi.info.BmiInfo.get_output_var_names`. - - Notes - ----- - .. code-block:: c - - /* C */ - int get_var_grid(void * self, const char * var_name, int * id); - """ - pass diff --git a/docs/Makefile b/docs/Makefile index 5824911..6ebe2d8 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -23,7 +23,7 @@ I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext pre-hook: - $(SPHINXAPIDOC) -o ./source ../bmi + $(SPHINXAPIDOC) -o ./source ../heat help: @echo "Please use \`make ' where is one of" diff --git a/docs/scipy-sphinx-theme b/docs/scipy-sphinx-theme deleted file mode 160000 index c466764..0000000 --- a/docs/scipy-sphinx-theme +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c466764e2231ba132c09826b5b138fffa1cfcec3 diff --git a/docs/source/_static/csdms.css b/docs/source/_static/csdms.css deleted file mode 100644 index 07c9ae2..0000000 --- a/docs/source/_static/csdms.css +++ /dev/null @@ -1,652 +0,0 @@ -/* - * Alternate Sphinx design - * Originally created by Armin Ronacher for Werkzeug, adapted by Georg Brandl. - */ - -body { - font-family: "Helvetica Neue", Helvetica, 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif; - font-size: 14px; - letter-spacing: -0.01em; - line-height: 150%; - text-align: center; - background-color: #BFD1D4; - color: black; - padding: 0; - border: 1px solid #aaa; - color: #333; - margin: 0px 80px 0px 80px; - min-width: 740px; -} - -a { - color: #CA7900; - text-decoration: none; -} - -strong { - font-weight: strong; -} - -a:hover { - color: #2491CF; -} - -pre { - font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; - font-size: 0.90em; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - letter-spacing: 0.015em; - padding: 1em; - border: 1px solid #ccc; - background-color: #f8f8f8; - line-height: 140%; -} - -td.linenos pre { - padding: 0.5em 0; - border: 0; - background-color: transparent; - color: #aaa; -} - -table.highlighttable { - margin-left: 0.5em; -} - -table.highlighttable td { - padding: 0 0.5em 0 0.5em; -} - -cite, code, tt { - font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; - font-size: 0.95em; - letter-spacing: 0.01em; -} - -hr { - border: 1px solid #abc; - margin: 2em; -} - -tt { - background-color: #f2f2f2; - border-bottom: 1px solid #ddd; - color: #333; -} - -tt.descname { - background-color: transparent; - font-weight: bold; - font-size: 1.2em; - border: 0; -} - -tt.descclassname { - background-color: transparent; - border: 0; -} - -tt.xref { - background-color: transparent; - font-weight: bold; - border: 0; -} - -a tt { - background-color: transparent; - font-weight: bold; - border: 0; - color: #CA7900; -} - -a tt:hover { - color: #2491CF; -} - -dl { - margin-bottom: 15px; -} - -dd p { - margin-top: 1px; -} - -dd ul, dd table { - margin-bottom: 10px; -} - -dd { - margin-top: 3px; - margin-bottom: 10px; - margin-left: 30px; -} - -.refcount { - color: #060; -} - -dt:target, -.highlight { - background-color: #ffffee; -} - -dl.method, dl.attribute { - border-top: 1px solid #aaa; -} - -dl.glossary dt { - font-weight: bold; - font-size: 1.1em; -} - -pre a { - color: inherit; - text-decoration: none; -} - -.first { - margin-top: 0 !important; -} - -div.document { - background-color: white; - text-align: left; - background-image: url(contents.png); - background-repeat: repeat-x; -} - -/* -div.documentwrapper { - width: 100%; -} -*/ - -div.clearer { - clear: both; -} - -div.related h3 { - display: none; -} - -div.related ul { - background-image: url(navigation.png); - height: 2em; - list-style: none; - border-top: 1px solid #ddd; - border-bottom: 1px solid #ddd; - margin: 0; - padding-left: 10px; -} - -div.related ul li { - margin: 0; - padding: 0; - height: 2em; - float: left; -} - -div.related ul li.right { - float: right; - margin-right: 5px; -} - -div.related ul li a { - margin: 0; - padding: 0 5px 0 5px; - line-height: 1.75em; - color: #EE9816; -} - -div.related ul li a:hover { - color: #3CA8E7; -} - -div.body { - margin: 0; - padding: 0.5em 20px 20px 20px; -} - -div.bodywrapper { - margin: 0 240px 0 0; - border-right: 1px solid #ccc; -} - -div.sphinxsidebar { - margin: 0; - padding: 0.5em 15px 15px 0; - width: 210px; - float: right; - text-align: left; -/* margin-left: -100%; */ -} - -div.sphinxsidebar h4, div.sphinxsidebar h3 { - margin: 1em 0 0.5em 0; - font-size: 0.9em; - padding: 0.1em 0 0.1em 0.5em; - color: white; - border: 1px solid #86989B; - background-color: #AFC1C4; -} - -div.sphinxsidebar ul { - padding-left: 1.5em; - margin-top: 7px; - list-style: none; - padding: 0; - line-height: 130%; -} - -div.sphinxsidebar ul ul { - list-style: square; - margin-left: 20px; -} - -p { - margin: 0.8em 0 0.8em 0; -} - -p.rubric { - font-weight: bold; -} - -h1 { - margin: 0.5em 0em; - padding-top: 0.5em; - font-size: 2em; - color: #11557C; -} - -h2 { - margin: 0.5em 0 0.2em 0; - padding-top: 0.5em; - font-size: 1.7em; - padding: 0; -} - -h3 { - margin: 1em 0 -0.3em 0; - font-size: 1.2em; -} - -h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { - color: black!important; -} - -h1 a.anchor, h2 a.anchor, h3 a.anchor, h4 a.anchor, h5 a.anchor, h6 a.anchor { - display: none; - margin: 0 0 0 0.3em; - padding: 0 0.2em 0 0.2em; - color: #aaa!important; -} - -h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, -h5:hover a.anchor, h6:hover a.anchor { - display: inline; -} - -h1 a.anchor:hover, h2 a.anchor:hover, h3 a.anchor:hover, h4 a.anchor:hover, -h5 a.anchor:hover, h6 a.anchor:hover { - color: #777; - background-color: #eee; -} - -table { - border-collapse: collapse; - margin: 0 -0.5em 0 -0.5em; -} - -table td, table th { - padding: 0.2em 0.5em 0.2em 0.5em; -} - -div.footer { - background-color: #E3EFF1; - color: #86989B; - padding: 3px 8px 3px 0; - clear: both; - font-size: 0.8em; - text-align: right; -} - -div.footer a { - color: #86989B; - text-decoration: underline; -} - -div.pagination { - margin-top: 2em; - padding-top: 0.5em; - border-top: 1px solid black; - text-align: center; -} - -div.sphinxsidebar ul.toc { - margin: 1em 0 1em 0; - padding: 0 0 0 0.5em; - list-style: none; -} - -div.sphinxsidebar ul.toc li { - margin: 0.5em 0 0.5em 0; - font-size: 0.9em; - line-height: 130%; -} - -div.sphinxsidebar ul.toc li p { - margin: 0; - padding: 0; -} - -div.sphinxsidebar ul.toc ul { - margin: 0.2em 0 0.2em 0; - padding: 0 0 0 1.8em; -} - -div.sphinxsidebar ul.toc ul li { - padding: 0; -} - -div.admonition, div.warning { - font-size: 0.9em; -} - -div.admonition p, div.warning p { - margin: 0.5em 1em 0.5em 1em; - padding: 0; -} - -div.admonition pre, div.warning pre { - margin: 0.4em 1em 0.4em 1em; -} - -div.admonition p.admonition-title, -div.warning p.admonition-title { - margin: 0; - font-weight: bold; - font-size: 14px; -} - -div.warning { - border: 1px solid #940000; -} - -div.warning p.admonition-title { - background-color: #CF0000; - border-bottom-color: #940000; -} - -div.admonition ul, div.admonition ol, -div.warning ul, div.warning ol { - margin: 0.1em 0.5em 0.5em 3em; - padding: 0; -} - -div.versioninfo { - margin: 1em 0 0 0; - border: 1px solid #ccc; - background-color: #DDEAF0; - padding: 8px; - line-height: 1.3em; - font-size: 0.9em; -} - - -a.headerlink { - color: #c60f0f!important; - font-size: 1em; - margin-left: 6px; - padding: 0 4px 0 4px; - text-decoration: none!important; - visibility: hidden; -} - -h1:hover > a.headerlink, -h2:hover > a.headerlink, -h3:hover > a.headerlink, -h4:hover > a.headerlink, -h5:hover > a.headerlink, -h6:hover > a.headerlink, -dt:hover > a.headerlink { - visibility: visible; -} - -a.headerlink:hover { - background-color: #ccc; - color: white!important; -} - -table.indextable td { - text-align: left; - vertical-align: top; -} - -table.indextable dl, table.indextable dd { - margin-top: 0; - margin-bottom: 0; -} - -table.indextable tr.pcap { - height: 10px; -} - -table.indextable tr.cap { - margin-top: 10px; - background-color: #f2f2f2; -} - -img.toggler { - margin-right: 3px; - margin-top: 3px; - cursor: pointer; -} - -img.inheritance { - border: 0px -} - -form.pfform { - margin: 10px 0 20px 0; -} - -table.contentstable { - width: 90%; -} - -table.contentstable p.biglink { - line-height: 150%; -} - -a.biglink { - font-size: 1.3em; -} - -span.linkdescr { - font-style: italic; - padding-top: 5px; - font-size: 90%; -} - -ul.search { - margin: 10px 0 0 20px; - padding: 0; -} - -ul.search li { - padding: 5px 0 5px 20px; - background-image: url(file.png); - background-repeat: no-repeat; - background-position: 0 7px; -} - -ul.search li a { - font-weight: bold; -} - -ul.search li div.context { - color: #888; - margin: 2px 0 0 30px; - text-align: left; -} - -ul.keywordmatches li.goodmatch a { - font-weight: bold; -} - -table.docutils { - border-spacing: 2px; - border-collapse: collapse; - border-top-width: 1px; - border-right-width: 0px; - border-bottom-width: 1px; - border-left-width: 0px; -} - -/* module summary table */ -.longtable.docutils { - font-size: 12px; - margin-bottom: 30px; - background-color: #f8f8f8; -} -.longtable.docutils, .longtable.docutils td { - border-color: #ccc; -} - -/* module summary table */ -.longtable.docutils { - font-size: 12px; - margin-bottom: 30px; -} -.longtable.docutils, .longtable.docutils td { - border-color: #ccc; -} - -/* function and class description */ -.descclassname { - color: #aaa; - font-weight: normal; - font-family: monospace; -} -.descname { - font-family: monospace; -} - - -table.docutils th { - padding: 1px 8px 1px 5px; - background-color: #eee; - width: 100px; -} - -table.docutils td { - border-width: 1px 0 1px 0; -} - - -dl.class em, dl.function em, dl.class big, dl.function big { - font-weight: normal; - font-family: monospace; -} - -dl.class dd, dl.function dd { - padding: 10px; -} - -/* function and class description */ -dl.class, dl.function, dl.method, dl.attribute { - border-top: 1px solid #ccc; - padding-top: 6px; -} - -dl.class, dl.function { - border-top: 1px solid #888; - margin-top: 15px; -} - - -.descclassname { - color: #aaa; - font-weight: normal; - font-family: monospace; -} -.descname { - font-family: monospace; -} - - -.docutils.field-list th { - background-color: #f8f8f8; - padding: 10px; - text-align: left; - vertical-align: top; - width: 120px; -} -.docutils.field-list td { - padding: 10px 10px 10px 20px; - text-align: left; - vertical-align: top; -} -.docutils.field-list td blockquote p { - font-size: 13px; - line-height: 18px; -} -p.rubric { - font-weight: bold; - font-size: 19px; - margin: 15px 0 10px 0; -} -p.admonition-title { - font-weight: bold; - text-decoration: underline; -} - - -#matplotlib-examples ul li{ - font-size: large; -} - -#matplotlib-examples ul li ul{ - margin-bottom:20px; - overflow:hidden; - border-top:1px solid #ccc; -} - -#matplotlib-examples ul li ul li { - font-size: small; - line-height:1.75em; - display:inline; - float: left; - width: 22em; -} - -#overview ul li ul{ - margin-bottom:20px; - overflow:hidden; - border-top:1px solid #ccc; -} - -#overview ul li ul li { - display:inline; - float: left; - width: 30em; -} - -figure { - margin: 1em; - display: inline-block; -} - -figure img { - margin-left: auto; - margin-right: auto; -} - -figcaption { - text-align: center; -} - - diff --git a/docs/source/_static/powered-by-logo-header.png b/docs/source/_static/powered-by-logo-header.png new file mode 100644 index 0000000..46c82d0 Binary files /dev/null and b/docs/source/_static/powered-by-logo-header.png differ diff --git a/docs/source/_templates/layout.html b/docs/source/_templates/layout.html deleted file mode 100644 index e5b7c5a..0000000 --- a/docs/source/_templates/layout.html +++ /dev/null @@ -1,263 +0,0 @@ -{% extends "sphinxdoc/layout.html" %} -{# "!" (which is handled by sphinx BuiltinTemplateLoader is not used here, - to enable nesting in ReadTheDocs build. -#} - -{# - basic/layout.html - ~~~~~~~~~~~~~~~~~ - - Master layout template for Sphinx themes. - - :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -#} -{%- block doctype -%} - -{%- endblock %} -{%- set reldelim1 = reldelim1 is not defined and ' »' or reldelim1 %} -{%- set reldelim2 = reldelim2 is not defined and ' |' or reldelim2 %} -{%- set render_sidebar = (not embedded) and (not theme_nosidebar|tobool) and - (sidebars != []) %} -{%- set url_root = pathto('', 1) %} -{# XXX necessary? #} -{%- if url_root == '#' %}{% set url_root = '' %}{% endif %} -{%- if not embedded and docstitle %} - {%- set titlesuffix = " — "|safe + docstitle|e %} -{%- else %} - {%- set titlesuffix = "" %} -{%- endif %} - -{%- macro relbar() %} - -{%- endmacro %} - -{%- macro sidebar() %} - {%- if render_sidebar %} -
-
- {%- block sidebarlogo %} - {%- if logo %} - - {%- endif %} - {%- endblock %} - {%- if sidebars != None %} - {#- new style sidebar: explicitly include/exclude templates #} - {%- for sidebartemplate in sidebars %} - {%- include sidebartemplate %} - {%- endfor %} - {%- else %} - {#- old style sidebars: using blocks -- should be deprecated #} - {%- block sidebartoc %} - {%- include "localtoc.html" %} - {%- endblock %} - {%- block sidebarrel %} - {%- include "relations.html" %} - {%- endblock %} - {%- block sidebarsourcelink %} - {%- include "sourcelink.html" %} - {%- endblock %} - {%- if customsidebar %} - {%- include customsidebar %} - {%- endif %} - {%- block sidebarsearch %} - {%- include "searchbox.html" %} - {%- endblock %} - {%- endif %} -
-
- {%- endif %} -{%- endmacro %} - -{%- macro script() %} - - {%- for scriptfile in script_files %} - - {%- endfor %} -{%- endmacro %} - -{%- macro css() %} - - - {%- for cssfile in css_files %} - - {%- endfor %} -{%- endmacro %} - - - - - {{ metatags }} - {%- block htmltitle %} - {{ title|striptags|e }}{{ titlesuffix }} - {%- endblock %} - {{ css() }} - {%- if not embedded %} - {{ script() }} - {%- if use_opensearch %} - - {%- endif %} - {%- if favicon %} - - {%- endif %} - {%- endif %} -{%- block linktags %} - {%- if hasdoc('about') %} - - {%- endif %} - {%- if hasdoc('genindex') %} - - {%- endif %} - {%- if hasdoc('search') %} - - {%- endif %} - {%- if hasdoc('copyright') %} - - {%- endif %} - - {%- if parents %} - - {%- endif %} - {%- if next %} - - {%- endif %} - {%- if prev %} - - {%- endif %} -{%- endblock %} -{%- block extrahead %} {% endblock %} - - - - -{%- block header %}{% endblock %} - -{% block relbar1 %} - - - -
-csdms -
- -{% endblock %} - -{%- block relbar2 %} - -{{ relbar() }} - -{% endblock %} - - - -{%- block content %} - {%- block sidebar1 %} {# possible location for sidebar #} {% endblock %} - - {%- block sidebar2 %}{{ sidebar() }}{% endblock %} - -
- {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} -
- {% block body %} {% endblock %} -
- {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} - -
-
-{%- endblock %} - -{%- block footer %} - - {%- endblock %} - - - - diff --git a/docs/source/_templates/links.html b/docs/source/_templates/links.html new file mode 100644 index 0000000..03f7f56 --- /dev/null +++ b/docs/source/_templates/links.html @@ -0,0 +1,9 @@ +

Useful Links

+ + diff --git a/docs/source/_templates/sidebarintro.html b/docs/source/_templates/sidebarintro.html new file mode 100644 index 0000000..f09d068 --- /dev/null +++ b/docs/source/_templates/sidebarintro.html @@ -0,0 +1,4 @@ +

About bmipy

+

+ Python bindings for the Basic Model Interface. +

diff --git a/docs/source/bmi_ext.py b/docs/source/bmi_ext.py deleted file mode 100644 index 8aa914e..0000000 --- a/docs/source/bmi_ext.py +++ /dev/null @@ -1,84 +0,0 @@ -import re - -from pygments.lexer import RegexLexer -from pygments.token import Text, Comment, String, Generic -from sphinx import addnodes -from docutils import nodes - - -class BmiLexer(RegexLexer): - name = 'bmilexer' - - tokens = { - 'root': [ - (r"'[^']*'", String.Single), - (r'[#].*?$', Comment), - (r'^=-> ', Generic.Prompt), - (r"[^'#\n]+", Text), - ], - } - - -comment_re = re.compile(r'(\(\*.*?\*\))') - - -def doctree_read(app, doctree): - env = app.builder.env - for node in doctree.traverse(addnodes.productionlist): - for production in node: - if not isinstance(production, addnodes.production): - continue - if not isinstance(production[-1], nodes.Text): - continue - parts = comment_re.split(production.pop().astext()) - new_nodes = [] - for s in parts: - if comment_re.match(s): - new_nodes.append(nodes.emphasis(s, s)) - elif s: - new_nodes.append(nodes.Text(s)) - production += new_nodes - - -def role_ftype(name, rawtext, text, lineno, inliner, options=None, content=()): - options = options or {} - node = nodes.strong(text, text) - assert text.count('(') in (0, 1) - assert text.count('(') == text.count(')') - assert ')' not in text or text.endswith(')') - match = re.search(r'\((.*?)\)', text) - node['ids'] = [match.group(1) if match else text] - return [node], [] - - -def setup(app): - app.add_lexer('bmi', BmiLexer()) - app.connect('doctree-read', doctree_read) - app.add_role('ftype', role_ftype) - - -# this is hack is needed to use our layout.html on ReadTheDocs -from sphinx.jinja2glue import BuiltinTemplateLoader -from jinja2 import TemplateNotFound - - -class MyTemplateLoader(BuiltinTemplateLoader): - def get_source(self, environment, template): - # If template name in Jinja's "extends" is prepended with "!" - # Sphinx skips project's template paths. - # In BuiltinTemplateLoader self.templatepathlen is used to remove - # project's template paths and leave only Sphinx's paths. - # This hack should leave the last path, so "!layout.html" will find - # the template from Fityk. To avoid recursion, Fityk template - # is not using "!". - loaders = self.loaders - # exclamation mark starts search from theme - if template.startswith('!'): - loaders = loaders[self.templatepathlen-1:] - template = template[1:] - for loader in loaders: - try: - return loader.get_source(environment, template) - except TemplateNotFound: - pass - raise TemplateNotFound(template) diff --git a/docs/source/conf.py b/docs/source/conf.py index d22a54a..af0082e 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,124 +1,63 @@ -# -*- coding: utf-8 -*- +# Configuration file for the Sphinx documentation builder. # -# Basic Model Interface documentation build configuration file, created by -# sphinx-quickstart on Tue Mar 17 20:28:33 2015. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# http://www.sphinx-doc.org/en/master/config -import sys -import os +# -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('../..')) -sys.path.insert(0, os.path.abspath('../sphinxext')) -sys.path.insert(0, os.path.abspath('.')) +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- -# -- General configuration ------------------------------------------------ +project = 'bmi-heat' +copyright = '2019, Eric Hutton' +author = 'Eric Hutton' -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' + +# -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', - 'sphinx.ext.mathjax', + 'sphinx.ext.intersphinx', + 'sphinx.ext.todo', 'sphinx.ext.viewcode', - 'numpydoc', - 'sphinx.ext.autosummary', + 'sphinx.ext.githubpages', + 'sphinx.ext.napoleon', ] -if os.getenv('READTHEDOCS'): - template_bridge = 'bmi_ext.MyTemplateLoader' - # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'Basic Model Interface' -copyright = u'2015, Eric Hutton' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '0.1' -# The full version, including alpha/beta/rc tags. -release = '0.1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] -# The reST default role (used for this markup: `text`) to use for all -# documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False - # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -#html_theme = 'default' -html_theme = 'sphinxdoc' +html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -html_theme_options = {} +#html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -html_theme_path = [] +#html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". @@ -129,7 +68,7 @@ # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +html_logo = "_static/powered-by-logo-header.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 @@ -155,7 +94,20 @@ #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +html_sidebars = { + "index": [ + "sidebarintro.html", + "links.html", + "sourcelink.html", + "searchbox.html", + ], + "**": [ + "sidebarintro.html", + "links.html", + "sourcelink.html", + "searchbox.html", + ] +} # Additional templates that should be rendered to pages, maps page names to # template names. @@ -187,87 +139,32 @@ # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None -# Output file base name for HTML help builder. -htmlhelp_basename = 'BasicModelInterfacedoc' - - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ('index', 'BasicModelInterface.tex', u'Basic Model Interface Documentation', - u'Eric Hutton', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +#html_search_language = 'en' -# If true, show URL addresses after external links. -#latex_show_urls = False +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +#html_search_options = {'type': 'default'} -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'basicmodelinterface', u'Basic Model Interface Documentation', - [u'Eric Hutton'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +#html_search_scorer = 'scorer.js' +# Output file base name for HTML help builder. +htmlhelp_basename = 'bmidoc' -# -- Options for Texinfo output ------------------------------------------- -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'BasicModelInterface', u'Basic Model Interface Documentation', - u'Eric Hutton', 'BasicModelInterface', 'One line description of project.', - 'Miscellaneous'), -] +# -- Extension configuration ------------------------------------------------- -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True +# -- Options for intersphinx extension --------------------------------------- -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/': None} -# If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False +# -- Options for todo extension ---------------------------------------------- -numpydoc_class_members_toctree = False -html_style = 'csdms.css' +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True diff --git a/docs/source/environment.yml b/docs/source/environment.yml new file mode 100644 index 0000000..3bc075c --- /dev/null +++ b/docs/source/environment.yml @@ -0,0 +1,13 @@ +name: heat_docs +channels: + - conda-forge +dependencies: +- python==3.6 +- pandoc +- pip +- sphinx>=1.5.1 +- sphinx_rtd_theme +- tornado +- entrypoints +- pip: + - sphinxcontrib_github_alt diff --git a/docs/source/index.rst b/docs/source/index.rst index 28f43c2..bef85d1 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,29 +1,7 @@ -.. Basic Model Interface documentation master file, created by - sphinx-quickstart on Tue Mar 17 20:28:33 2015. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +.. title:: bmi-heat -The Basic Model Interface -========================= +.. include:: ../../README.rst -:Release: |release| -:Date: |today| - -Contents -======== - -.. toctree:: - :maxdepth: 2 - - Base control functions - Component info - Time - Variables - Getters and Setters - Uniform rectilinear grids - Rectilinear grids - Structured quadrilateral grids - Unstructured grids Indices and tables ================== diff --git a/docs/source/modules.rst b/docs/source/modules.rst index aefbf12..b3c4868 100644 --- a/docs/source/modules.rst +++ b/docs/source/modules.rst @@ -1,7 +1,7 @@ -bmi -=== +heat +==== .. toctree:: :maxdepth: 4 - bmi + heat diff --git a/docs/sphinxext b/docs/sphinxext deleted file mode 160000 index 96a0fe3..0000000 --- a/docs/sphinxext +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 96a0fe332767846fa3f6904929d8dba7caaef80b diff --git a/heat/__init__.py b/heat/__init__.py index ccda353..5ba44a5 100644 --- a/heat/__init__.py +++ b/heat/__init__.py @@ -1,7 +1,9 @@ """Model the diffusion of heat over a 2D plate.""" +from ._version import get_versions from .bmi_heat import BmiHeat from .heat import solve_2d - -__all__ = ['BmiHeat', 'solve_2d'] +__all__ = ["BmiHeat", "solve_2d"] +__version__ = get_versions()["version"] +del get_versions diff --git a/heat/_version.py b/heat/_version.py new file mode 100644 index 0000000..5ece93e --- /dev/null +++ b/heat/_version.py @@ -0,0 +1,556 @@ +# 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 = "heat-" + cfg.versionfile_source = "heat/_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/heat/bmi_heat.py b/heat/bmi_heat.py index bfb70b9..e2cddd4 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -3,10 +3,8 @@ import numpy as np -import six -from six.moves import range +from bmipy import Bmi -from bmi import Bmi from .heat import Heat @@ -14,18 +12,23 @@ class BmiHeat(Bmi): """Solve the heat equation for a 2D plate.""" - _name = 'The 2D Heat Equation' - _input_var_names = ('plate_surface__temperature',) - _output_var_names = ('plate_surface__temperature',) + _name = "The 2D Heat Equation" + _input_var_names = ("plate_surface__temperature",) + _output_var_names = ("plate_surface__temperature",) def __init__(self): """Create a BmiHeat model that is ready for initialization.""" self._model = None self._values = {} self._var_units = {} + self._var_loc = {} self._grids = {} self._grid_type = {} + self._start_time = 0.0 + self._end_time = np.finfo("d").max + self._time_units = "s" + def initialize(self, filename=None): """Initialize the Heat model. @@ -36,24 +39,17 @@ def initialize(self, filename=None): """ if filename is None: self._model = Heat() - elif isinstance(filename, six.string_types): - with open(filename, 'r') as file_obj: + elif isinstance(filename, str): + with open(filename, "r") as file_obj: self._model = Heat.from_file_like(file_obj.read()) else: self._model = Heat.from_file_like(filename) - self._values = { - 'plate_surface__temperature': self._model.temperature, - } - self._var_units = { - 'plate_surface__temperature': 'K' - } - self._grids = { - 0: ['plate_surface__temperature'] - } - self._grid_type = { - 0: 'uniform_rectilinear_grid' - } + self._values = {"plate_surface__temperature": self._model.temperature} + self._var_units = {"plate_surface__temperature": "K"} + self._var_loc = {"plate_surface__temperature": "node"} + self._grids = {0: ["plate_surface__temperature"]} + self._grid_type = {0: "uniform_rectilinear_grid"} def update(self): """Advance model by one time step.""" @@ -103,7 +99,7 @@ def get_var_type(self, var_name): str Data type. """ - return str(self.get_value_ref(var_name).dtype) + return str(self.get_value_ptr(var_name).dtype) def get_var_units(self, var_name): """Get units of variable. @@ -133,7 +129,13 @@ def get_var_nbytes(self, var_name): int Size of data array in bytes. """ - return self.get_value_ref(var_name).nbytes + return self.get_value_ptr(var_name).nbytes + + def get_var_itemsize(self, name): + return np.dtype(self.get_var_type(name)).itemsize + + def get_var_location(self, name): + return self._var_loc[name] def get_var_grid(self, var_name): """Grid id for a variable. @@ -182,7 +184,7 @@ def get_grid_size(self, grid_id): """ return np.prod(self.get_grid_shape(grid_id)) - def get_value_ref(self, var_name): + def get_value_ptr(self, var_name): """Reference to values. Parameters @@ -210,7 +212,7 @@ def get_value(self, var_name): array_like Copy of values. """ - return self.get_value_ref(var_name).copy() + return self.get_value_ptr(var_name).copy() def get_value_at_indices(self, var_name, indices): """Get values at particular indices. @@ -227,7 +229,7 @@ def get_value_at_indices(self, var_name, indices): array_like Values at indices. """ - return self.get_value_ref(var_name).take(indices) + return self.get_value_ptr(var_name).take(indices) def set_value(self, var_name, src): """Set model values. @@ -239,10 +241,10 @@ def set_value(self, var_name, src): src : array_like Array of new values. """ - val = self.get_value_ref(var_name) + val = self.get_value_ptr(var_name) val[:] = src - def set_value_at_indices(self, var_name, src, indices): + def set_value_at_indices(self, name, inds, src): """Set model values at particular indices. Parameters @@ -254,8 +256,8 @@ def set_value_at_indices(self, var_name, src, indices): indices : array_like Array of indices. """ - val = self.get_value_ref(var_name) - val.flat[indices] = src + val = self.get_value_ptr(name) + val.flat[inds] = src def get_component_name(self): """Name of the component.""" @@ -272,7 +274,7 @@ def get_output_var_names(self): def get_grid_shape(self, grid_id): """Number of rows and columns of uniform rectilinear grid.""" var_name = self._grids[grid_id][0] - return self.get_value_ref(var_name).shape + return self.get_value_ptr(var_name).shape def get_grid_spacing(self, grid_id): """Spacing of rows and columns of uniform rectilinear grid.""" @@ -288,16 +290,44 @@ def get_grid_type(self, grid_id): def get_start_time(self): """Start time of model.""" - return 0. + return self._start_time def get_end_time(self): """End time of model.""" - return np.finfo('d').max + return self._end_time def get_current_time(self): - """Current time of model.""" return self._model.time def get_time_step(self): - """Time step of model.""" return self._model.time_step + + def get_time_units(self): + return self._time_units + + def get_grid_edge_count(self, grid): + raise NotImplementedError("get_grid_edge_count") + + def get_grid_edge_nodes(self, grid, edge_nodes): + raise NotImplementedError("get_grid_edge_nodes") + + def get_grid_face_count(self, grid): + raise NotImplementedError("get_grid_face_count") + + def get_grid_face_nodes(self, grid, face_nodes): + raise NotImplementedError("get_grid_face_nodes") + + def get_grid_node_count(self, grid): + raise NotImplementedError("get_grid_node_count") + + def get_grid_nodes_per_face(self, grid, nodes_per_face): + raise NotImplementedError("get_grid_nodes_per_face") + + def get_grid_x(self, grid, x): + raise NotImplementedError("get_grid_x") + + def get_grid_y(self, grid, y): + raise NotImplementedError("get_grid_y") + + def get_grid_z(self, grid, z): + raise NotImplementedError("get_grid_z") diff --git a/heat/heat.py b/heat/heat.py index 8c5e25a..56ab831 100644 --- a/heat/heat.py +++ b/heat/heat.py @@ -1,11 +1,11 @@ """The 2D heat model.""" import numpy as np -from scipy import ndimage, random import yaml +from scipy import ndimage, random -def solve_2d(temp, spacing, out=None, alpha=1., time_step=1.): +def solve_2d(temp, spacing, out=None, alpha=1.0, time_step=1.0): """Solve the 2D Heat Equation on a uniform mesh. Parameters @@ -37,16 +37,19 @@ def solve_2d(temp, spacing, out=None, alpha=1., time_step=1.): [0. , 0. , 0. ]]) """ dy2, dx2 = spacing[0] ** 2, spacing[1] ** 2 - stencil = np.array([[0., dy2, 0.], - [dx2, -2. * (dx2 + dy2), dx2], - [0., dy2, 0.]]) * alpha * time_step / (dx2 * dy2) + stencil = ( + np.array([[0.0, dy2, 0.0], [dx2, -2.0 * (dx2 + dy2), dx2], [0.0, dy2, 0.0]]) + * alpha + * time_step + / (dx2 * dy2) + ) if out is None: out = np.empty_like(temp) ndimage.convolve(temp, stencil, output=out) - out[(0, -1), :] = 0. - out[:, (0, -1)] = 0. + out[(0, -1), :] = 0.0 + out[:, (0, -1)] = 0.0 return np.add(temp, out, out=out) @@ -78,8 +81,9 @@ class Heat(object): 2.0 """ - def __init__(self, shape=(10, 20), spacing=(1., 1.), origin=(0., 0.), - alpha=1.): + def __init__( + self, shape=(10, 20), spacing=(1.0, 1.0), origin=(0.0, 0.0), alpha=1.0 + ): """Create a new heat model. Paramters @@ -96,9 +100,9 @@ def __init__(self, shape=(10, 20), spacing=(1., 1.), origin=(0., 0.), self._shape = shape self._spacing = spacing self._origin = origin - self._time = 0. + self._time = 0.0 self._alpha = alpha - self._time_step = min(spacing) ** 2 / (4. * self._alpha) + self._time_step = min(spacing) ** 2 / (4.0 * self._alpha) self._temperature = random.random(self._shape) self._next_temperature = np.empty_like(self._temperature) @@ -158,13 +162,18 @@ def from_file_like(cls, file_like): Heat A new instance of a Heat object. """ - config = yaml.load(file_like) + config = yaml.safe_load(file_like) return cls(**config) def advance_in_time(self): """Calculate new temperatures for the next time step.""" - solve_2d(self._temperature, self._spacing, out=self._next_temperature, - alpha=self._alpha, time_step=self._time_step) + solve_2d( + self._temperature, + self._spacing, + out=self._next_temperature, + alpha=self._alpha, + time_step=self._time_step, + ) np.copyto(self._temperature, self._next_temperature) self._time += self._time_step diff --git a/heat/tests/test_get_value.py b/heat/tests/test_get_value.py deleted file mode 100644 index 9c9e264..0000000 --- a/heat/tests/test_get_value.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python -from nose.tools import assert_equal, assert_true, assert_is, assert_is_not -from numpy.testing import assert_array_less, assert_array_almost_equal -import numpy as np - -from six.moves import range -from heat import BmiHeat - - -def test_get_initial_value(): - model = BmiHeat() - model.initialize() - - z0 = model.get_value_ref('plate_surface__temperature') - assert_array_less(z0, 1.) - assert_array_less(0., z0) - - -def test_get_value_copy(): - model = BmiHeat() - model.initialize() - - z0 = model.get_value('plate_surface__temperature') - z1 = model.get_value('plate_surface__temperature') - - assert_is_not(z0, z1) - assert_array_almost_equal(z0, z1) - - -def test_get_value_reference(): - model = BmiHeat() - model.initialize() - - z0 = model.get_value_ref('plate_surface__temperature') - z1 = model.get_value('plate_surface__temperature') - - assert_is_not(z0, z1) - assert_array_almost_equal(z0, z1) - - for _ in range(10): - model.update() - - assert_is(z0, model.get_value_ref('plate_surface__temperature')) - - -def test_get_value_at_indices(): - model = BmiHeat() - model.initialize() - - z0 = model.get_value_ref('plate_surface__temperature') - z1 = model.get_value_at_indices('plate_surface__temperature', [0, 2, 4]) - - assert_array_almost_equal(z0.take((0, 2, 4)), z1) - - -def test_value_size(): - model = BmiHeat() - model.initialize() - - z = model.get_value_ref('plate_surface__temperature') - assert_equal(model.get_grid_size(0), z.size) - - -def test_value_nbytes(): - model = BmiHeat() - model.initialize() - - z = model.get_value_ref('plate_surface__temperature') - assert_equal(model.get_var_nbytes('plate_surface__temperature'), z.nbytes) diff --git a/heat/tests/test_set_value.py b/heat/tests/test_set_value.py deleted file mode 100644 index 67fe7f8..0000000 --- a/heat/tests/test_set_value.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python -from nose.tools import assert_is, assert_is_not -from numpy.testing import assert_array_almost_equal -import numpy as np - -from heat import BmiHeat - - -def test_set_value(): - model = BmiHeat() - model.initialize() - - z0 = model.get_value_ref('plate_surface__temperature') - z1 = np.zeros_like(z0) - 1 - - model.set_value('plate_surface__temperature', z1) - - new_z = model.get_value_ref('plate_surface__temperature') - - assert_is(new_z, z0) - assert_is_not(new_z, z1) - assert_array_almost_equal(new_z, z1) - - -def test_set_value_at_indices(): - model = BmiHeat() - model.initialize() - - z0 = model.get_value_ref('plate_surface__temperature') - - model.set_value_at_indices('plate_surface__temperature', [-1, -1, -1], - [0, 2, 4]) - - new_z = model.get_value_ref('plate_surface__temperature') - assert_array_almost_equal(new_z.take((0, 2, 4)), -1.) diff --git a/requirements.txt b/requirements.txt index 9d15b6c..55594fb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -numpy -scipy -PyYAML -nose +coveralls +flake8 +pytest +pytest-cov diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..ca3acd6 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,42 @@ +[versioneer] +VCS = git +style = pep440 +versionfile_source = heat/_version.py +versionfile_build = heat/_version.py +tag_prefix = v +parentdir_prefix = heat- + +[tool:pytest] +minversion = 3.0 +testpaths = heat tests +norecursedirs = .* *.egg* build dist +addopts = + --ignore setup.py + --ignore versioneer.py + --ignore heat/_version.py + --tb native + --strict + --durations 16 + --doctest-modules +doctest_optionflags = + NORMALIZE_WHITESPACE + IGNORE_EXCEPTION_DETAIL + ALLOW_UNICODE + +[isort] +multi_line_output=3 +include_trailing_comma=True +force_grid_wrap=0 +combine_as_imports=True +line_length=88 + +[flake8] +exclude = docs heat/_version.py +ignore = + E203 + E501 + W503 +max-line-length = 88 + +[pylint] +disable = missing-docstring,line-too-long diff --git a/setup.py b/setup.py index 15f9f03..4be18ac 100644 --- a/setup.py +++ b/setup.py @@ -1,18 +1,30 @@ #! /usr/bin/env python from setuptools import setup, find_packages -setup(name='bmi-heat', - version='0.1.0', - author='Eric Hutton', - author_email='eric.hutton@colorado.edu', - description='BMI Python example', - long_description=open('README.md').read(), - packages=find_packages(), - install_requires=['six'], - classifiers=[ - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.5', - ] +import versioneer + + +setup( + name="bmi-heat", + version=versioneer.get_version(), + author="Eric Hutton", + author_email="eric.hutton@colorado.edu", + description="BMI Python example", + long_description=open("README.rst").read(), + classifiers=[ + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Cython", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: Implementation :: CPython", + "Topic :: Scientific/Engineering :: Physics", + ], + install_requires=["bmipy", "pyyaml", "scipy"], + packages=find_packages(), + cmdclass=versioneer.get_cmdclass(), ) diff --git a/heat/tests/__init__.py b/tests/__init__.py similarity index 100% rename from heat/tests/__init__.py rename to tests/__init__.py diff --git a/tests/test_get_value.py b/tests/test_get_value.py new file mode 100644 index 0000000..3bbaa12 --- /dev/null +++ b/tests/test_get_value.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +from numpy.testing import assert_array_almost_equal, assert_array_less + +from heat import BmiHeat + + +def test_get_initial_value(): + model = BmiHeat() + model.initialize() + + z0 = model.get_value_ptr("plate_surface__temperature") + assert_array_less(z0, 1.0) + assert_array_less(0.0, z0) + + +def test_get_value_copy(): + model = BmiHeat() + model.initialize() + + z0 = model.get_value("plate_surface__temperature") + z1 = model.get_value("plate_surface__temperature") + + assert z0 is not z1 + assert_array_almost_equal(z0, z1) + + +def test_get_value_pointer(): + model = BmiHeat() + model.initialize() + + z0 = model.get_value_ptr("plate_surface__temperature") + z1 = model.get_value("plate_surface__temperature") + + assert z0 is not z1 + assert_array_almost_equal(z0, z1) + + for _ in range(10): + model.update() + + assert z0 is model.get_value_ptr("plate_surface__temperature") + + +def test_get_value_at_indices(): + model = BmiHeat() + model.initialize() + + z0 = model.get_value_ptr("plate_surface__temperature") + z1 = model.get_value_at_indices("plate_surface__temperature", [0, 2, 4]) + + assert_array_almost_equal(z0.take((0, 2, 4)), z1) + + +def test_value_size(): + model = BmiHeat() + model.initialize() + + z = model.get_value_ptr("plate_surface__temperature") + assert model.get_grid_size(0) == z.size + + +def test_value_nbytes(): + model = BmiHeat() + model.initialize() + + z = model.get_value_ptr("plate_surface__temperature") + assert model.get_var_nbytes("plate_surface__temperature") == z.nbytes diff --git a/heat/tests/test_grid_info.py b/tests/test_grid_info.py similarity index 53% rename from heat/tests/test_grid_info.py rename to tests/test_grid_info.py index 97a6e58..0efbfc6 100644 --- a/heat/tests/test_grid_info.py +++ b/tests/test_grid_info.py @@ -1,94 +1,93 @@ #!/usr/bin/env python -from nose.tools import assert_equal, assert_tuple_equal, raises -import numpy as np +import pytest from heat import BmiHeat - grid_id = 0 invalid_grid_id = 12345 + def test_grid_var_names(): model = BmiHeat() model.initialize() names = model.get_input_var_names() - assert_tuple_equal(names, ('plate_surface__temperature',)) + assert names == ("plate_surface__temperature",) names = model.get_output_var_names() - assert_tuple_equal(names, ('plate_surface__temperature',)) + assert names == ("plate_surface__temperature",) def test_grid_var_units(): model = BmiHeat() model.initialize() - assert_equal(model.get_var_units('plate_surface__temperature'), 'K') + assert model.get_var_units("plate_surface__temperature") == "K" def test_grid_id(): model = BmiHeat() model.initialize() - assert_equal(model.get_var_grid('plate_surface__temperature'), grid_id) + assert model.get_var_grid("plate_surface__temperature") == grid_id def test_grid_var_rank(): model = BmiHeat() model.initialize() - assert_equal(model.get_grid_rank(grid_id), 2) + assert model.get_grid_rank(grid_id) == 2 -@raises(KeyError) def test_grid_var_rank_fail(): model = BmiHeat() model.initialize() - model.get_grid_rank(invalid_grid_id) + with pytest.raises(KeyError): + model.get_grid_rank(invalid_grid_id) def test_grid_var_size(): model = BmiHeat() model.initialize() - assert_equal(model.get_grid_size(grid_id), 200) + assert model.get_grid_size(grid_id) == 200 -@raises(KeyError) def test_grid_var_size_fail(): model = BmiHeat() model.initialize() - model.get_grid_size(invalid_grid_id) + with pytest.raises(KeyError): + model.get_grid_size(invalid_grid_id) def test_grid_var_shape(): model = BmiHeat() model.initialize() - assert_equal(model.get_grid_shape(grid_id), (10, 20)) + assert model.get_grid_shape(grid_id) == (10, 20) -@raises(KeyError) def test_grid_var_shape_fail(): model = BmiHeat() model.initialize() - model.get_grid_shape(invalid_grid_id) + with pytest.raises(KeyError): + model.get_grid_shape(invalid_grid_id) def test_grid_var_spacing(): model = BmiHeat() model.initialize() - assert_equal(model.get_grid_spacing(grid_id), (1., 1.)) + assert model.get_grid_spacing(grid_id) == (1.0, 1.0) def test_grid_var_origin(): model = BmiHeat() model.initialize() - assert_equal(model.get_grid_origin(grid_id), (0., 0.)) + assert model.get_grid_origin(grid_id) == (0.0, 0.0) def test_grid_var_type(): model = BmiHeat() model.initialize() - assert_equal(model.get_var_type('plate_surface__temperature'), 'float64') + assert model.get_var_type("plate_surface__temperature") == "float64" def test_grid_type(): model = BmiHeat() model.initialize() - assert_equal(model.get_grid_type(grid_id), 'uniform_rectilinear_grid') + assert model.get_grid_type(grid_id) == "uniform_rectilinear_grid" diff --git a/heat/tests/test_irf.py b/tests/test_irf.py similarity index 58% rename from heat/tests/test_irf.py rename to tests/test_irf.py index 372b836..7c61522 100644 --- a/heat/tests/test_irf.py +++ b/tests/test_irf.py @@ -1,7 +1,9 @@ #!/usr/bin/env python -from nose.tools import assert_equal, assert_is +from io import StringIO + from numpy.testing import assert_almost_equal, assert_array_less import numpy as np +import yaml from six.moves import range from heat import BmiHeat @@ -11,8 +13,8 @@ def test_component_name(): model = BmiHeat() name = model.get_component_name() - assert_equal(name, 'The 2D Heat Equation') - assert_is(model.get_component_name(), name) + assert name == "The 2D Heat Equation" + assert model.get_component_name() is name def test_start_time(): @@ -26,27 +28,24 @@ def test_end_time(): model = BmiHeat() model.initialize() - assert_almost_equal(model.get_end_time(), np.finfo('d').max) + assert_almost_equal(model.get_end_time(), np.finfo("d").max) def test_initialize_defaults(): model = BmiHeat() model.initialize() - assert_almost_equal(model.get_current_time(), 0.) - assert_array_less(model.get_value('plate_surface__temperature'), 1.) - assert_array_less(0., model.get_value('plate_surface__temperature')) + assert_almost_equal(model.get_current_time(), 0.0) + assert_array_less(model.get_value("plate_surface__temperature"), 1.0) + assert_array_less(0.0, model.get_value("plate_surface__temperature")) def test_initialize_from_file_like(): - from six import StringIO - import yaml - - config = StringIO(yaml.dump({'shape': (7, 5)})) + config = StringIO(yaml.dump({"shape": [7, 5]})) model = BmiHeat() model.initialize(config) - assert_equal(model.get_grid_shape(0), (7, 5)) + assert model.get_grid_shape(0) == (7, 5) def test_initialize_from_file(): @@ -54,8 +53,8 @@ def test_initialize_from_file(): import yaml import tempfile - with tempfile.NamedTemporaryFile('w', delete=False) as fp: - fp.write(yaml.dump({'shape': (7, 5)})) + with tempfile.NamedTemporaryFile("w", delete=False) as fp: + fp.write(yaml.dump({"shape": [7, 5]})) name = fp.name model = BmiHeat() @@ -63,7 +62,7 @@ def test_initialize_from_file(): os.remove(name) - assert_equal(model.get_grid_shape(0), (7, 5)) + assert model.get_grid_shape(0) == (7, 5) def test_update(): @@ -72,8 +71,7 @@ def test_update(): for inc in range(10): model.update() - assert_almost_equal(model.get_current_time(), - (inc + 1) * model.get_time_step()) + assert_almost_equal(model.get_current_time(), (inc + 1) * model.get_time_step()) def test_update_until(): diff --git a/tests/test_set_value.py b/tests/test_set_value.py new file mode 100644 index 0000000..8b4898f --- /dev/null +++ b/tests/test_set_value.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +import numpy as np +from numpy.testing import assert_array_almost_equal + +from heat import BmiHeat + + +def test_set_value(): + model = BmiHeat() + model.initialize() + + z0 = model.get_value_ptr("plate_surface__temperature") + z1 = np.zeros_like(z0) - 1 + + model.set_value("plate_surface__temperature", z1) + + new_z = model.get_value_ptr("plate_surface__temperature") + + assert new_z is z0 + assert new_z is not z1 + assert_array_almost_equal(new_z, z1) + + +def test_set_value_at_indices(): + model = BmiHeat() + model.initialize() + + model.set_value_at_indices("plate_surface__temperature", [0, 2, 4], [-1, -1, -1]) + + new_z = model.get_value_ptr("plate_surface__temperature") + assert_array_almost_equal(new_z.take((0, 2, 4)), -1.0) diff --git a/versioneer.py b/versioneer.py new file mode 100644 index 0000000..64fea1c --- /dev/null +++ b/versioneer.py @@ -0,0 +1,1822 @@ + +# 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)