From 985b707b8e3fb47299e26f3e55cd3cd69b75137e Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:16:13 -0600 Subject: [PATCH 01/35] chore: install versioneer --- .gitattributes | 1 + MANIFEST.in | 2 + heat/__init__.py | 4 + heat/_version.py | 520 +++++++++++++ versioneer.py | 1822 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 2349 insertions(+) create mode 100644 .gitattributes create mode 100644 MANIFEST.in create mode 100644 heat/_version.py create mode 100644 versioneer.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/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/heat/__init__.py b/heat/__init__.py index ccda353..cce40e1 100644 --- a/heat/__init__.py +++ b/heat/__init__.py @@ -5,3 +5,7 @@ __all__ = ['BmiHeat', 'solve_2d'] + +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions diff --git a/heat/_version.py b/heat/_version.py new file mode 100644 index 0000000..c696154 --- /dev/null +++ b/heat/_version.py @@ -0,0 +1,520 @@ + +# 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/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) From ed8b4880cf9da9ebca6f25627f23b373d2916607 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:17:19 -0600 Subject: [PATCH 02/35] chore: add convenience makefile --- Makefile | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a6365f5 --- /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/heat.rst + rm -f docs/modules.rst + sphinx-apidoc -o docs/ 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 From eba882dd602475dea6f95acf4f91cb7d58e53755 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:18:19 -0600 Subject: [PATCH 03/35] chore: add classifiers --- setup.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index fa50938..1d8c7cb 100644 --- a/setup.py +++ b/setup.py @@ -3,12 +3,26 @@ use_setuptools() from setuptools import setup, find_packages +import versioneer + setup(name='bmi-heat', - version='0.1.0', + version=versioneer.get_version(), author='Eric Hutton', author_email='eric.hutton@colorado.edu', description='BMI Python example', long_description=open('README.md').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", + ], packages=find_packages(), + cmdclass=versioneer.get_cmdclass(), ) From bd537d22ad0df8781d15ff5b5d59b05074c69619 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:20:11 -0600 Subject: [PATCH 04/35] style: reformat for black --- heat/__init__.py | 7 +- heat/_version.py | 154 +++++++++++++++++++++-------------- heat/bmi_heat.py | 30 +++---- heat/heat.py | 35 +++++--- heat/tests/test_get_value.py | 30 +++---- heat/tests/test_grid_info.py | 20 ++--- heat/tests/test_irf.py | 21 +++-- heat/tests/test_set_value.py | 17 ++-- setup.py | 22 ++--- 9 files changed, 187 insertions(+), 149 deletions(-) diff --git a/heat/__init__.py b/heat/__init__.py index cce40e1..91a8704 100644 --- a/heat/__init__.py +++ b/heat/__init__.py @@ -1,11 +1,10 @@ """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'] - -from ._version import get_versions -__version__ = get_versions()['version'] +__version__ = get_versions()["version"] del get_versions diff --git a/heat/_version.py b/heat/_version.py index c696154..5ece93e 100644 --- a/heat/_version.py +++ b/heat/_version.py @@ -1,4 +1,3 @@ - # 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 @@ -58,17 +57,18 @@ class NotThisMethod(Exception): 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): +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 @@ -76,10 +76,13 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, 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)) + 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] @@ -116,16 +119,22 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): 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} + 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)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -181,7 +190,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = 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 @@ -190,7 +199,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set([r for r in refs if re.search(r"\d", r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -198,19 +207,26 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") @@ -225,8 +241,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + 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) @@ -234,10 +249,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) + describe_out, rc = 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") @@ -260,17 +284,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -279,10 +302,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -293,13 +318,13 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) + count_out, rc = 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() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ + 0 + ].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces @@ -330,8 +355,7 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -445,11 +469,13 @@ def render_git_describe_long(pieces): def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default @@ -469,9 +495,13 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } def get_versions(): @@ -485,8 +515,7 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass @@ -495,13 +524,16 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for 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} + 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) @@ -515,6 +547,10 @@ def get_versions(): except NotThisMethod: pass - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } diff --git a/heat/bmi_heat.py b/heat/bmi_heat.py index ea345da..e4eadd1 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -2,9 +2,11 @@ """Basic Model Interface implementation for the 2D heat model.""" import types + import numpy as np from bmi import Bmi + from .heat import Heat @@ -12,9 +14,9 @@ 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.""" @@ -35,23 +37,15 @@ def initialize(self, filename=None): if filename is None: self._model = Heat() elif isinstance(filename, types.StringTypes): - with open(filename, 'r') as file_obj: + 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._grids = {0: ["plate_surface__temperature"]} + self._grid_type = {0: "uniform_rectilinear_grid"} def update(self): """Advance model by one time step.""" @@ -286,11 +280,11 @@ def get_grid_type(self, grid_id): def get_start_time(self): """Start time of model.""" - return 0. + return 0.0 def get_end_time(self): """End time of model.""" - return np.finfo('d').max + return np.finfo("d").max def get_current_time(self): """Current time of model.""" diff --git a/heat/heat.py b/heat/heat.py index 9715885..5ccbc5a 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) @@ -163,8 +167,13 @@ def from_file_like(cls, file_like): 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 index 413ace8..c2b5137 100644 --- a/heat/tests/test_get_value.py +++ b/heat/tests/test_get_value.py @@ -1,7 +1,7 @@ #!/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 nose.tools import assert_equal, assert_is, assert_is_not, assert_true +from numpy.testing import assert_array_almost_equal, assert_array_less from heat import BmiHeat @@ -10,17 +10,17 @@ 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) + z0 = model.get_value_ref("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') + 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) @@ -30,8 +30,8 @@ def test_get_value_reference(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref('plate_surface__temperature') - z1 = model.get_value('plate_surface__temperature') + 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) @@ -39,15 +39,15 @@ def test_get_value_reference(): for _ in xrange(10): model.update() - assert_is(z0, model.get_value_ref('plate_surface__temperature')) + 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]) + 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) @@ -56,7 +56,7 @@ def test_value_size(): model = BmiHeat() model.initialize() - z = model.get_value_ref('plate_surface__temperature') + z = model.get_value_ref("plate_surface__temperature") assert_equal(model.get_grid_size(0), z.size) @@ -64,5 +64,5 @@ 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) + 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_grid_info.py b/heat/tests/test_grid_info.py index 97a6e58..ae7cd8d 100644 --- a/heat/tests/test_grid_info.py +++ b/heat/tests/test_grid_info.py @@ -1,34 +1,34 @@ #!/usr/bin/env python -from nose.tools import assert_equal, assert_tuple_equal, raises import numpy as np +from nose.tools import assert_equal, assert_tuple_equal, raises 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_tuple_equal(names, ("plate_surface__temperature",)) names = model.get_output_var_names() - assert_tuple_equal(names, ('plate_surface__temperature',)) + assert_tuple_equal(names, ("plate_surface__temperature",)) def test_grid_var_units(): model = BmiHeat() model.initialize() - assert_equal(model.get_var_units('plate_surface__temperature'), 'K') + assert_equal(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_equal(model.get_var_grid("plate_surface__temperature"), grid_id) def test_grid_var_rank(): @@ -73,22 +73,22 @@ def test_grid_var_shape_fail(): def test_grid_var_spacing(): model = BmiHeat() model.initialize() - assert_equal(model.get_grid_spacing(grid_id), (1., 1.)) + assert_equal(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_equal(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_equal(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_equal(model.get_grid_type(grid_id), "uniform_rectilinear_grid") diff --git a/heat/tests/test_irf.py b/heat/tests/test_irf.py index 86921bd..a186ed9 100644 --- a/heat/tests/test_irf.py +++ b/heat/tests/test_irf.py @@ -1,7 +1,7 @@ #!/usr/bin/env python +import numpy as np from nose.tools import assert_equal, assert_is from numpy.testing import assert_almost_equal, assert_array_less -import numpy as np from heat import BmiHeat @@ -10,7 +10,7 @@ def test_component_name(): model = BmiHeat() name = model.get_component_name() - assert_equal(name, 'The 2D Heat Equation') + assert_equal(name, "The 2D Heat Equation") assert_is(model.get_component_name(), name) @@ -25,23 +25,23 @@ 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 StringIO import StringIO import yaml - config = StringIO(yaml.dump({'shape': (7, 5)})) + config = StringIO(yaml.dump({"shape": (7, 5)})) model = BmiHeat() model.initialize(config) @@ -53,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() @@ -71,8 +71,7 @@ def test_update(): for inc in xrange(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/heat/tests/test_set_value.py b/heat/tests/test_set_value.py index 67fe7f8..0beebb4 100644 --- a/heat/tests/test_set_value.py +++ b/heat/tests/test_set_value.py @@ -1,7 +1,7 @@ #!/usr/bin/env python +import numpy as np 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 @@ -10,12 +10,12 @@ def test_set_value(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref('plate_surface__temperature') + z0 = model.get_value_ref("plate_surface__temperature") z1 = np.zeros_like(z0) - 1 - model.set_value('plate_surface__temperature', z1) + model.set_value("plate_surface__temperature", z1) - new_z = model.get_value_ref('plate_surface__temperature') + new_z = model.get_value_ref("plate_surface__temperature") assert_is(new_z, z0) assert_is_not(new_z, z1) @@ -26,10 +26,9 @@ def test_set_value_at_indices(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref('plate_surface__temperature') + z0 = model.get_value_ref("plate_surface__temperature") - model.set_value_at_indices('plate_surface__temperature', [-1, -1, -1], - [0, 2, 4]) + 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.) + new_z = model.get_value_ref("plate_surface__temperature") + assert_array_almost_equal(new_z.take((0, 2, 4)), -1.0) diff --git a/setup.py b/setup.py index 1d8c7cb..6edf8c1 100644 --- a/setup.py +++ b/setup.py @@ -1,18 +1,20 @@ #! /usr/bin/env python from ez_setup import use_setuptools + use_setuptools() from setuptools import setup, find_packages 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.md').read(), - classifiers=[ +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.md").read(), + classifiers=[ "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", @@ -22,7 +24,7 @@ "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Scientific/Engineering :: Physics", - ], - packages=find_packages(), - cmdclass=versioneer.get_cmdclass(), + ], + packages=find_packages(), + cmdclass=versioneer.get_cmdclass(), ) From 1a6ec4734b5add37977bba5e9d7d8e0c5383de71 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:21:12 -0600 Subject: [PATCH 05/35] chore: remove ez_setup.py --- ez_setup.py | 284 ---------------------------------------------------- setup.py | 3 - 2 files changed, 287 deletions(-) delete mode 100644 ez_setup.py diff --git a/ez_setup.py b/ez_setup.py deleted file mode 100644 index b74adc0..0000000 --- a/ez_setup.py +++ /dev/null @@ -1,284 +0,0 @@ -#!python -"""Bootstrap setuptools installation - -If you want to use setuptools in your package's setup.py, just include this -file in the same directory with it, and add this to the top of your setup.py:: - - from ez_setup import use_setuptools - use_setuptools() - -If you want to require a specific version of setuptools, set a download -mirror, or use an alternate download directory, you can do so by supplying -the appropriate options to ``use_setuptools()``. - -This file can also be run as a script to install or upgrade setuptools. -""" -import sys -DEFAULT_VERSION = "0.6c11" -DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] - -md5_data = { - 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', - 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', - 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', - 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', - 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', - 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', - 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', - 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', - 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', - 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', - 'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090', - 'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4', - 'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7', - 'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5', - 'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de', - 'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b', - 'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2', - 'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086', - 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', - 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', - 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', - 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', - 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', - 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', - 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', - 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', - 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', - 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', - 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', - 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', - 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', - 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', - 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', - 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', - 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', - 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', - 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', - 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', - 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', - 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', - 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', - 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', -} - -import sys, os -try: from hashlib import md5 -except ImportError: from md5 import md5 - -def _validate_md5(egg_name, data): - if egg_name in md5_data: - digest = md5(data).hexdigest() - if digest != md5_data[egg_name]: - print >>sys.stderr, ( - "md5 validation of %s failed! (Possible download problem?)" - % egg_name - ) - sys.exit(2) - return data - -def use_setuptools( - version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, - download_delay=15 -): - """Automatically find/download setuptools and make it available on sys.path - - `version` should be a valid setuptools version number that is available - as an egg for download under the `download_base` URL (which should end with - a '/'). `to_dir` is the directory where setuptools will be downloaded, if - it is not already available. If `download_delay` is specified, it should - be the number of seconds that will be paused before initiating a download, - should one be required. If an older version of setuptools is installed, - this routine will print a message to ``sys.stderr`` and raise SystemExit in - an attempt to abort the calling script. - """ - was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules - def do_download(): - egg = download_setuptools(version, download_base, to_dir, download_delay) - sys.path.insert(0, egg) - import setuptools; setuptools.bootstrap_install_from = egg - try: - import pkg_resources - except ImportError: - return do_download() - try: - pkg_resources.require("setuptools>="+version); return - except pkg_resources.VersionConflict, e: - if was_imported: - print >>sys.stderr, ( - "The required version of setuptools (>=%s) is not available, and\n" - "can't be installed while this script is running. Please install\n" - " a more recent version first, using 'easy_install -U setuptools'." - "\n\n(Currently using %r)" - ) % (version, e.args[0]) - sys.exit(2) - except pkg_resources.DistributionNotFound: - pass - - del pkg_resources, sys.modules['pkg_resources'] # reload ok - return do_download() - -def download_setuptools( - version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, - delay = 15 -): - """Download setuptools from a specified location and return its filename - - `version` should be a valid setuptools version number that is available - as an egg for download under the `download_base` URL (which should end - with a '/'). `to_dir` is the directory where the egg will be downloaded. - `delay` is the number of seconds to pause before an actual download attempt. - """ - import urllib2, shutil - egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) - url = download_base + egg_name - saveto = os.path.join(to_dir, egg_name) - src = dst = None - if not os.path.exists(saveto): # Avoid repeated downloads - try: - from distutils import log - if delay: - log.warn(""" ---------------------------------------------------------------------------- -This script requires setuptools version %s to run (even to display -help). I will attempt to download it for you (from -%s), but -you may need to enable firewall access for this script first. -I will start the download in %d seconds. - -(Note: if this machine does not have network access, please obtain the file - - %s - -and place it in this directory before rerunning this script.) ----------------------------------------------------------------------------""", - version, download_base, delay, url - ); from time import sleep; sleep(delay) - log.warn("Downloading %s", url) - src = urllib2.urlopen(url) - # Read/write all in one block, so we don't create a corrupt file - # if the download is interrupted. - data = _validate_md5(egg_name, src.read()) - dst = open(saveto,"wb"); dst.write(data) - finally: - if src: src.close() - if dst: dst.close() - return os.path.realpath(saveto) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -def main(argv, version=DEFAULT_VERSION): - """Install or upgrade setuptools and EasyInstall""" - try: - import setuptools - except ImportError: - egg = None - try: - egg = download_setuptools(version, delay=0) - sys.path.insert(0,egg) - from setuptools.command.easy_install import main - return main(list(argv)+[egg]) # we're done here - finally: - if egg and os.path.exists(egg): - os.unlink(egg) - else: - if setuptools.__version__ == '0.0.1': - print >>sys.stderr, ( - "You have an obsolete version of setuptools installed. Please\n" - "remove it from your system entirely before rerunning this script." - ) - sys.exit(2) - - req = "setuptools>="+version - import pkg_resources - try: - pkg_resources.require(req) - except pkg_resources.VersionConflict: - try: - from setuptools.command.easy_install import main - except ImportError: - from easy_install import main - main(list(argv)+[download_setuptools(delay=0)]) - sys.exit(0) # try to force an exit - else: - if argv: - from setuptools.command.easy_install import main - main(argv) - else: - print "Setuptools version",version,"or greater has been installed." - print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' - -def update_md5(filenames): - """Update our built-in md5 registry""" - - import re - - for name in filenames: - base = os.path.basename(name) - f = open(name,'rb') - md5_data[base] = md5(f.read()).hexdigest() - f.close() - - data = [" %r: %r,\n" % it for it in md5_data.items()] - data.sort() - repl = "".join(data) - - import inspect - srcfile = inspect.getsourcefile(sys.modules[__name__]) - f = open(srcfile, 'rb'); src = f.read(); f.close() - - match = re.search("\nmd5_data = {\n([^}]+)}", src) - if not match: - print >>sys.stderr, "Internal error!" - sys.exit(2) - - src = src[:match.start(1)] + repl + src[match.end(1):] - f = open(srcfile,'w') - f.write(src) - f.close() - - -if __name__=='__main__': - if len(sys.argv)>2 and sys.argv[1]=='--md5update': - update_md5(sys.argv[2:]) - else: - main(sys.argv[1:]) - - - - - - diff --git a/setup.py b/setup.py index 6edf8c1..ff874d9 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,4 @@ #! /usr/bin/env python -from ez_setup import use_setuptools - -use_setuptools() from setuptools import setup, find_packages import versioneer From 990dfbd1b98d2c8a4b5eec03c5e046baf55a31c3 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:21:44 -0600 Subject: [PATCH 06/35] chore: add setup.cfg with sensible defaults --- setup.cfg | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 setup.cfg diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..ded975b --- /dev/null +++ b/setup.cfg @@ -0,0 +1,39 @@ +[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 = 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 +ignore = + E203 + E501 + W503 +max-line-length = 88 From af852f75caf15b2124339316f9d1c1b5115a1dab Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:30:26 -0600 Subject: [PATCH 07/35] chore: move tests into separate tests folder --- {heat/tests => tests}/__init__.py | 0 {heat/tests => tests}/test_get_value.py | 0 {heat/tests => tests}/test_grid_info.py | 0 {heat/tests => tests}/test_irf.py | 0 {heat/tests => tests}/test_set_value.py | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename {heat/tests => tests}/__init__.py (100%) rename {heat/tests => tests}/test_get_value.py (100%) rename {heat/tests => tests}/test_grid_info.py (100%) rename {heat/tests => tests}/test_irf.py (100%) rename {heat/tests => tests}/test_set_value.py (100%) 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/heat/tests/test_get_value.py b/tests/test_get_value.py similarity index 100% rename from heat/tests/test_get_value.py rename to tests/test_get_value.py diff --git a/heat/tests/test_grid_info.py b/tests/test_grid_info.py similarity index 100% rename from heat/tests/test_grid_info.py rename to tests/test_grid_info.py diff --git a/heat/tests/test_irf.py b/tests/test_irf.py similarity index 100% rename from heat/tests/test_irf.py rename to tests/test_irf.py diff --git a/heat/tests/test_set_value.py b/tests/test_set_value.py similarity index 100% rename from heat/tests/test_set_value.py rename to tests/test_set_value.py From ab9b910eb20c150b480b35636ea647380f161c6e Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:52:55 -0600 Subject: [PATCH 08/35] chore: use pytest instead of nose --- tests/test_get_value.py | 13 ++++++------- tests/test_grid_info.py | 36 ++++++++++++++++++------------------ tests/test_irf.py | 20 ++++++++++---------- tests/test_set_value.py | 5 ++--- 4 files changed, 36 insertions(+), 38 deletions(-) diff --git a/tests/test_get_value.py b/tests/test_get_value.py index c2b5137..3406350 100644 --- a/tests/test_get_value.py +++ b/tests/test_get_value.py @@ -1,6 +1,5 @@ #!/usr/bin/env python import numpy as np -from nose.tools import assert_equal, assert_is, assert_is_not, assert_true from numpy.testing import assert_array_almost_equal, assert_array_less from heat import BmiHeat @@ -22,7 +21,7 @@ def test_get_value_copy(): z0 = model.get_value("plate_surface__temperature") z1 = model.get_value("plate_surface__temperature") - assert_is_not(z0, z1) + assert z0 is not z1 assert_array_almost_equal(z0, z1) @@ -33,13 +32,13 @@ def test_get_value_reference(): z0 = model.get_value_ref("plate_surface__temperature") z1 = model.get_value("plate_surface__temperature") - assert_is_not(z0, z1) + assert z0 is not z1 assert_array_almost_equal(z0, z1) - for _ in xrange(10): + for _ in range(10): model.update() - assert_is(z0, model.get_value_ref("plate_surface__temperature")) + assert z0 is model.get_value_ref("plate_surface__temperature") def test_get_value_at_indices(): @@ -57,7 +56,7 @@ def test_value_size(): model.initialize() z = model.get_value_ref("plate_surface__temperature") - assert_equal(model.get_grid_size(0), z.size) + assert model.get_grid_size(0) == z.size def test_value_nbytes(): @@ -65,4 +64,4 @@ def test_value_nbytes(): model.initialize() z = model.get_value_ref("plate_surface__temperature") - assert_equal(model.get_var_nbytes("plate_surface__temperature"), z.nbytes) + assert model.get_var_nbytes("plate_surface__temperature") == z.nbytes diff --git a/tests/test_grid_info.py b/tests/test_grid_info.py index ae7cd8d..3638bf9 100644 --- a/tests/test_grid_info.py +++ b/tests/test_grid_info.py @@ -1,6 +1,6 @@ #!/usr/bin/env python import numpy as np -from nose.tools import assert_equal, assert_tuple_equal, raises +import pytest from heat import BmiHeat @@ -13,82 +13,82 @@ def test_grid_var_names(): 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.0, 1.0)) + 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, 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/tests/test_irf.py b/tests/test_irf.py index a186ed9..397d064 100644 --- a/tests/test_irf.py +++ b/tests/test_irf.py @@ -1,17 +1,20 @@ #!/usr/bin/env python -import numpy as np -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 heat import BmiHeat + 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(): @@ -38,14 +41,11 @@ def test_initialize_defaults(): def test_initialize_from_file_like(): - from StringIO import StringIO - import yaml - 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(): @@ -62,14 +62,14 @@ 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(): model = BmiHeat() model.initialize() - for inc in xrange(10): + for inc in range(10): model.update() assert_almost_equal(model.get_current_time(), (inc + 1) * model.get_time_step()) diff --git a/tests/test_set_value.py b/tests/test_set_value.py index 0beebb4..34165da 100644 --- a/tests/test_set_value.py +++ b/tests/test_set_value.py @@ -1,6 +1,5 @@ #!/usr/bin/env python import numpy as np -from nose.tools import assert_is, assert_is_not from numpy.testing import assert_array_almost_equal from heat import BmiHeat @@ -17,8 +16,8 @@ def test_set_value(): new_z = model.get_value_ref("plate_surface__temperature") - assert_is(new_z, z0) - assert_is_not(new_z, z1) + assert new_z is z0 + assert new_z is not z1 assert_array_almost_equal(new_z, z1) From 27a1573aed7eb3eb72f20083805a249350772a6c Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:53:39 -0600 Subject: [PATCH 09/35] test: fix for new numpy formatting --- heat/heat.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/heat/heat.py b/heat/heat.py index 5ccbc5a..a6f5bff 100644 --- a/heat/heat.py +++ b/heat/heat.py @@ -32,9 +32,9 @@ def solve_2d(temp, spacing, out=None, alpha=1.0, time_step=1.0): >>> z0 = np.zeros((3, 3)) >>> z0[1:-1, 1:-1] = 1. >>> solve_2d(z0, (1., 1.), alpha=.125) - array([[ 0. , 0. , 0. ], - [ 0. , 0.5, 0. ], - [ 0. , 0. , 0. ]]) + array([[0. , 0. , 0. ], + [0. , 0.5, 0. ], + [0. , 0. , 0. ]]) """ dy2, dx2 = spacing[0] ** 2, spacing[1] ** 2 stencil = ( From 0924157b26bbd9507ab80e4d4897465358b2f77a Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:53:58 -0600 Subject: [PATCH 10/35] chore: drop python 2.7 compatibility --- heat/bmi_heat.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/heat/bmi_heat.py b/heat/bmi_heat.py index e4eadd1..7bbe4c9 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -36,7 +36,7 @@ def initialize(self, filename=None): """ if filename is None: self._model = Heat() - elif isinstance(filename, types.StringTypes): + elif isinstance(filename, str): with open(filename, "r") as file_obj: self._model = Heat.from_file_like(file_obj.read()) else: @@ -74,7 +74,7 @@ def update_until(self, then): """ n_steps = (then - self.get_current_time()) / self.get_time_step() - for _ in xrange(int(n_steps)): + for _ in range(int(n_steps)): self.update() self.update_frac(n_steps - int(n_steps)) From e4ccb5a1ab744f5dabb2875d5cf2ee57f835666f Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:55:32 -0600 Subject: [PATCH 11/35] test: look in tests folder for tests --- setup.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index ded975b..bdc85c6 100644 --- a/setup.cfg +++ b/setup.cfg @@ -8,7 +8,7 @@ parentdir_prefix = heat- [tool:pytest] minversion = 3.0 -testpaths = tests +testpaths = heat tests norecursedirs = .* *.egg* build dist addopts = --ignore setup.py From b4304fa0c20cbf1f9237d7b2fed26e60cb2134b2 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 10:57:00 -0600 Subject: [PATCH 12/35] refactor: remove local bmi package, use bmipy --- bmi/__init__.py | 5 -- bmi/base.py | 115 ------------------------- bmi/bmi.py | 26 ------ bmi/getter_setter.py | 144 ------------------------------- bmi/grid.py | 87 ------------------- bmi/grid_rectilinear.py | 126 --------------------------- bmi/grid_structured_quad.py | 119 -------------------------- bmi/grid_uniform_rectilinear.py | 106 ----------------------- bmi/grid_unstructured.py | 146 -------------------------------- bmi/info.py | 79 ----------------- bmi/time.py | 110 ------------------------ bmi/vars.py | 144 ------------------------------- 12 files changed, 1207 deletions(-) delete mode 100644 bmi/__init__.py delete mode 100644 bmi/base.py delete mode 100644 bmi/bmi.py delete mode 100644 bmi/getter_setter.py delete mode 100644 bmi/grid.py delete mode 100644 bmi/grid_rectilinear.py delete mode 100644 bmi/grid_structured_quad.py delete mode 100644 bmi/grid_uniform_rectilinear.py delete mode 100644 bmi/grid_unstructured.py delete mode 100644 bmi/info.py delete mode 100644 bmi/time.py delete mode 100644 bmi/vars.py 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 0fc219f..0000000 --- a/bmi/info.py +++ /dev/null @@ -1,79 +0,0 @@ -#! /usr/bin/env python -"""Interface that describes a model and it's 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. - - Notes - ----- - .. 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 076a72f..0000000 --- a/bmi/time.py +++ /dev/null @@ -1,110 +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. - - Returns - ------- - float - The model time unit; e.g., `days` or `s`. - - Notes - ----- - CSDMS uses the UDUNITS standard from Unidata. - - 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 From 7b05d94591aaa6fb5cc0c4d573c8766566bb6a00 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 11:13:13 -0600 Subject: [PATCH 13/35] fix: use get_value_ptr, not get_value_ref --- tests/test_get_value.py | 14 +++++++------- tests/test_set_value.py | 8 ++++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/test_get_value.py b/tests/test_get_value.py index 3406350..210778d 100644 --- a/tests/test_get_value.py +++ b/tests/test_get_value.py @@ -9,7 +9,7 @@ def test_get_initial_value(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref("plate_surface__temperature") + z0 = model.get_value_ptr("plate_surface__temperature") assert_array_less(z0, 1.0) assert_array_less(0.0, z0) @@ -25,11 +25,11 @@ def test_get_value_copy(): assert_array_almost_equal(z0, z1) -def test_get_value_reference(): +def test_get_value_pointer(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref("plate_surface__temperature") + z0 = model.get_value_ptr("plate_surface__temperature") z1 = model.get_value("plate_surface__temperature") assert z0 is not z1 @@ -38,14 +38,14 @@ def test_get_value_reference(): for _ in range(10): model.update() - assert z0 is model.get_value_ref("plate_surface__temperature") + assert z0 is model.get_value_ptr("plate_surface__temperature") def test_get_value_at_indices(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref("plate_surface__temperature") + 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) @@ -55,7 +55,7 @@ def test_value_size(): model = BmiHeat() model.initialize() - z = model.get_value_ref("plate_surface__temperature") + z = model.get_value_ptr("plate_surface__temperature") assert model.get_grid_size(0) == z.size @@ -63,5 +63,5 @@ def test_value_nbytes(): model = BmiHeat() model.initialize() - z = model.get_value_ref("plate_surface__temperature") + z = model.get_value_ptr("plate_surface__temperature") assert model.get_var_nbytes("plate_surface__temperature") == z.nbytes diff --git a/tests/test_set_value.py b/tests/test_set_value.py index 34165da..7930dda 100644 --- a/tests/test_set_value.py +++ b/tests/test_set_value.py @@ -9,12 +9,12 @@ def test_set_value(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref("plate_surface__temperature") + 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_ref("plate_surface__temperature") + new_z = model.get_value_ptr("plate_surface__temperature") assert new_z is z0 assert new_z is not z1 @@ -25,9 +25,9 @@ def test_set_value_at_indices(): model = BmiHeat() model.initialize() - z0 = model.get_value_ref("plate_surface__temperature") + z0 = model.get_value_ptr("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") + new_z = model.get_value_ptr("plate_surface__temperature") assert_array_almost_equal(new_z.take((0, 2, 4)), -1.0) From 1b52f8f1e1e48f6bbc90999e59a774ebfbabb8f7 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Tue, 16 Apr 2019 11:13:46 -0600 Subject: [PATCH 14/35] chore: NotImplementedError for usused methods --- heat/bmi_heat.py | 54 +++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/heat/bmi_heat.py b/heat/bmi_heat.py index 7bbe4c9..5841ac4 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -95,7 +95,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. @@ -125,7 +125,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 "node" def get_var_grid(self, var_name): """Grid id for a variable. @@ -174,7 +180,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 @@ -202,7 +208,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. @@ -219,7 +225,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. @@ -231,7 +237,7 @@ 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): @@ -246,7 +252,7 @@ def set_value_at_indices(self, var_name, src, indices): indices : array_like Array of indices. """ - val = self.get_value_ref(var_name) + val = self.get_value_ptr(var_name) val.flat[indices] = src def get_component_name(self): @@ -264,7 +270,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.""" @@ -287,9 +293,37 @@ def get_end_time(self): return np.finfo("d").max 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 "s" + + 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") From 6fa0a0544fa747c07cd3af40857409398682f47d Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 09:29:33 -0600 Subject: [PATCH 15/35] chore: add install requirements in setup.py --- requirements.txt | 6 ++---- setup.py | 1 + 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/requirements.txt b/requirements.txt index 9d15b6c..9955dec 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,2 @@ -numpy -scipy -PyYAML -nose +pytest +pytest-cov diff --git a/setup.py b/setup.py index ff874d9..0a68bbe 100644 --- a/setup.py +++ b/setup.py @@ -22,6 +22,7 @@ "Programming Language :: Python :: Implementation :: CPython", "Topic :: Scientific/Engineering :: Physics", ], + install_requires=["bmipy", "pyyaml", "scipy"], packages=find_packages(), cmdclass=versioneer.get_cmdclass(), ) From b309bc579df85d673205f54c927c7219f91623af Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 09:30:35 -0600 Subject: [PATCH 16/35] test: use build stages for Travis CI --- .travis.yml | 74 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 55 insertions(+), 19 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7fcae08..35dcd63 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,22 +1,58 @@ -language: python -python: - - "2.7" - +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 From 288f285856223a9fd8f368146f411da99606f06f Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 09:33:32 -0600 Subject: [PATCH 17/35] chore: update versioneer --- heat/__init__.py | 4 ++ heat/_version.py | 154 ++++++++++++++++++----------------------------- 2 files changed, 63 insertions(+), 95 deletions(-) diff --git a/heat/__init__.py b/heat/__init__.py index 91a8704..b9d6ab4 100644 --- a/heat/__init__.py +++ b/heat/__init__.py @@ -8,3 +8,7 @@ __version__ = get_versions()["version"] del get_versions + +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions diff --git a/heat/_version.py b/heat/_version.py index 5ece93e..c696154 100644 --- a/heat/_version.py +++ b/heat/_version.py @@ -1,3 +1,4 @@ + # 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 @@ -57,18 +58,17 @@ class NotThisMethod(Exception): 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): +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 @@ -76,13 +76,10 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= 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), - ) + 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] @@ -119,22 +116,16 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): 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, - } + 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) - ) + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -190,7 +181,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = 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 @@ -199,7 +190,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -207,26 +198,19 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix) :] + r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) - return { - "version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": None, - "date": date, - } + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return { - "version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": "no suitable tags", - "date": None, - } + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") @@ -241,7 +225,8 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) + 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) @@ -249,19 +234,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command( - GITS, - [ - "describe", - "--tags", - "--dirty", - "--always", - "--long", - "--match", - "%s*" % tag_prefix, - ], - cwd=root, - ) + describe_out, rc = 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") @@ -284,16 +260,17 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[: git_describe.rindex("-dirty")] + git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) return pieces # tag @@ -302,12 +279,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( - full_tag, - tag_prefix, - ) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix) :] + pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -318,13 +293,13 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) + count_out, rc = 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() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces @@ -355,7 +330,8 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -469,13 +445,11 @@ def render_git_describe_long(pieces): def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: - return { - "version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None, - } + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} if not style or style == "default": style = "pep440" # the default @@ -495,13 +469,9 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - return { - "version": rendered, - "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], - "error": None, - "date": pieces.get("date"), - } + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} def get_versions(): @@ -515,7 +485,8 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) except NotThisMethod: pass @@ -524,16 +495,13 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split("/"): + for 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, - } + 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) @@ -547,10 +515,6 @@ def get_versions(): except NotThisMethod: pass - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", - "date": None, - } + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} From 382589dac9fee5ac30ee2d5187a424b54dd844b4 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 09:34:02 -0600 Subject: [PATCH 18/35] style: format for black --- heat/__init__.py | 3 +- heat/_version.py | 154 ++++++++++++++++++++++++++++------------------ heat/bmi_heat.py | 2 +- tests/test_irf.py | 1 - 4 files changed, 97 insertions(+), 63 deletions(-) diff --git a/heat/__init__.py b/heat/__init__.py index b9d6ab4..4bab8b7 100644 --- a/heat/__init__.py +++ b/heat/__init__.py @@ -9,6 +9,5 @@ __version__ = get_versions()["version"] del get_versions -from ._version import get_versions -__version__ = get_versions()['version'] +__version__ = get_versions()["version"] del get_versions diff --git a/heat/_version.py b/heat/_version.py index c696154..5ece93e 100644 --- a/heat/_version.py +++ b/heat/_version.py @@ -1,4 +1,3 @@ - # 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 @@ -58,17 +57,18 @@ class NotThisMethod(Exception): 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): +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 @@ -76,10 +76,13 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, 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)) + 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] @@ -116,16 +119,22 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): 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} + 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)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -181,7 +190,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = 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 @@ -190,7 +199,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set([r for r in refs if re.search(r"\d", r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -198,19 +207,26 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") @@ -225,8 +241,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + 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) @@ -234,10 +249,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) + describe_out, rc = 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") @@ -260,17 +284,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -279,10 +302,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -293,13 +318,13 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) + count_out, rc = 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() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ + 0 + ].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces @@ -330,8 +355,7 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -445,11 +469,13 @@ def render_git_describe_long(pieces): def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default @@ -469,9 +495,13 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } def get_versions(): @@ -485,8 +515,7 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass @@ -495,13 +524,16 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for 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} + 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) @@ -515,6 +547,10 @@ def get_versions(): except NotThisMethod: pass - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } diff --git a/heat/bmi_heat.py b/heat/bmi_heat.py index 5841ac4..192a963 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -5,7 +5,7 @@ import numpy as np -from bmi import Bmi +from bmipy import Bmi from .heat import Heat diff --git a/tests/test_irf.py b/tests/test_irf.py index 397d064..6731939 100644 --- a/tests/test_irf.py +++ b/tests/test_irf.py @@ -8,7 +8,6 @@ from heat import BmiHeat - def test_component_name(): model = BmiHeat() From 31ae9cb000ec2d731fcad85d018a88e669b3ded9 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 09:36:24 -0600 Subject: [PATCH 19/35] style: remove lint --- heat/__init__.py | 4 ---- heat/bmi_heat.py | 2 -- setup.cfg | 2 +- tests/test_get_value.py | 1 - tests/test_grid_info.py | 1 - tests/test_set_value.py | 2 -- 6 files changed, 1 insertion(+), 11 deletions(-) diff --git a/heat/__init__.py b/heat/__init__.py index 4bab8b7..5ba44a5 100644 --- a/heat/__init__.py +++ b/heat/__init__.py @@ -5,9 +5,5 @@ from .heat import solve_2d __all__ = ["BmiHeat", "solve_2d"] - -__version__ = get_versions()["version"] -del get_versions - __version__ = get_versions()["version"] del get_versions diff --git a/heat/bmi_heat.py b/heat/bmi_heat.py index 192a963..ea8843d 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -1,8 +1,6 @@ #! /usr/bin/env python """Basic Model Interface implementation for the 2D heat model.""" -import types - import numpy as np from bmipy import Bmi diff --git a/setup.cfg b/setup.cfg index bdc85c6..3beb1df 100644 --- a/setup.cfg +++ b/setup.cfg @@ -31,7 +31,7 @@ combine_as_imports=True line_length=88 [flake8] -exclude = docs +exclude = docs heat/_version.py ignore = E203 E501 diff --git a/tests/test_get_value.py b/tests/test_get_value.py index 210778d..3bbaa12 100644 --- a/tests/test_get_value.py +++ b/tests/test_get_value.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import numpy as np from numpy.testing import assert_array_almost_equal, assert_array_less from heat import BmiHeat diff --git a/tests/test_grid_info.py b/tests/test_grid_info.py index 3638bf9..0efbfc6 100644 --- a/tests/test_grid_info.py +++ b/tests/test_grid_info.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import numpy as np import pytest from heat import BmiHeat diff --git a/tests/test_set_value.py b/tests/test_set_value.py index 7930dda..b6b080d 100644 --- a/tests/test_set_value.py +++ b/tests/test_set_value.py @@ -25,8 +25,6 @@ def test_set_value_at_indices(): model = BmiHeat() model.initialize() - z0 = model.get_value_ptr("plate_surface__temperature") - model.set_value_at_indices("plate_surface__temperature", [-1, -1, -1], [0, 2, 4]) new_z = model.get_value_ptr("plate_surface__temperature") From 2d24c6a7fc93d03883a5bdc5026fb152fc90aac7 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 09:37:00 -0600 Subject: [PATCH 20/35] docs: add conda env file for building docs --- docs/source/environment.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/source/environment.yml 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 From 0a556ed783bf05cccbd62b9365de5d2bcfd389b5 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 12:40:05 -0600 Subject: [PATCH 21/35] test: add flake8, coveralls to test requirements --- requirements.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/requirements.txt b/requirements.txt index 9955dec..55594fb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,4 @@ +coveralls +flake8 pytest pytest-cov From 722fd8ab379295aefb22b1b8629c851027e7205a Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 12:43:32 -0600 Subject: [PATCH 22/35] docs: remove submodules --- .gitmodules | 6 ------ docs/scipy-sphinx-theme | 1 - docs/sphinxext | 1 - 3 files changed, 8 deletions(-) delete mode 160000 docs/scipy-sphinx-theme delete mode 160000 docs/sphinxext diff --git a/.gitmodules b/.gitmodules index 49a0cb0..e69de29 100644 --- a/.gitmodules +++ b/.gitmodules @@ -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/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/sphinxext b/docs/sphinxext deleted file mode 160000 index 96a0fe3..0000000 --- a/docs/sphinxext +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 96a0fe332767846fa3f6904929d8dba7caaef80b From 8d3c9049f0ff2cbcb48917c433790a855f2db0fb Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 12:58:01 -0600 Subject: [PATCH 23/35] docs: add csdms logo and sidebar template --- .../source/_static/powered-by-logo-header.png | Bin 0 -> 15416 bytes docs/source/_templates/layout.html | 263 ------------------ docs/source/_templates/links.html | 9 + docs/source/_templates/sidebarintro.html | 4 + 4 files changed, 13 insertions(+), 263 deletions(-) create mode 100644 docs/source/_static/powered-by-logo-header.png delete mode 100644 docs/source/_templates/layout.html create mode 100644 docs/source/_templates/links.html create mode 100644 docs/source/_templates/sidebarintro.html 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 0000000000000000000000000000000000000000..46c82d07f6e2f212423e1512dd8462b623ffd7b8 GIT binary patch literal 15416 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�APjn(D*x^=)xYMois~`;GZSk@LI`_*boQQt_!n_>d}5|Eh|?F9ONaI$*VBO>PCl$Xu+N2j+@aSoSI zbhTE2Gl?^n7lScCwgRLF{C|3daJ)b!q3KKj^EdI2560rs)BtZ)L5voGpdQVuU4*Zn zWy`Jv^=vei|7+*_8HoT~|B3k?&$vN^?vTM49Ss+nI8r*DevJ*Y@z;NKK-#F1b#I=) ze;a%SU$SVkR&f?nZG8wtZ98*r0w!)bIbl!ZHTg`}lO_AN!YHrFq= zhc6$tW4C|DQG~_B487j3$9BKJo}JId+r8pr)5}>(yv9ld3XoK*JsPlI2d(ASx}%1mmG8zmoM(0%oSzvd2#!j#ZRDIBnNl!^6lHVhqLzc8tY{aLOwUt-QC@f z0rct%siGdVenqwv{O;m;MTq7xX>?o-J z(0x%&WfoFcXKYiHHgWqs>GZ7jio<3l?0(&sB%RY1*(@=>k0+2NxA0OQg3zKU+ zZY|h3pIs|uDbZKl_cPs|4vSeFcBGQ69rwovfs38rwp3Km$G(1lz34~Ls56FxM?i>6 zON;m{o3wGaY*>I(aqTEg(~-R{yuCihrKW}x*mj_Gzg)@o$O@kV7DC~> z0F#Kq^+zJ$aB6!WCh?8x4TRZ_=3G1Y_YDn1Vxs|(HCvkRp*k@(#z+TlM^es3@)_u?suPJ|9+g% ze*aj3Cs-hyh5+P%6qvBA?%bQgpL_BsUs=(PBH%<8e7O+q+4Z_x{Lykf&fA$}Qmb(R z*vx3H!@Z=U0`cI5Djv>t-J4UbO8fAhWz&xTA@HLzk#lrpvuWMM=6ip+UcEX^H__yK zd)Vf3*a;gxM!=@;x!N6dXRsZPAxdF2iO}O5_I|!IxY`-{Ju8cC z3#OM^-QB&tt-0^E!PAF3 zEBhCl{V4+89+L`;YwYao8%f`7gmrawlVf+aivO9`=QcE8vYGxBvbMIaQMI~0Dz9#u zo!+$5zdKo6XfVgH-EUsBa@&cMFPD{<+b>%;KVnfj^ANGJ zv9Xx`#l=O0W=0G=IbU%!=NH% zWJD&9gH=^k1?<;5SNUC0Pw%`wDwEgMaJ9|3<#8{)(+1`Cc2X5U^+W14w{4_xv{a&R z=^RM!uj}v8$5rjfDopC;3CMV-O}T3119zD+aTZ}A2VVfv(l(l zsZno=l*FhL0R%zzK7tzHqD?ldM^{Tha2OYT2u%7zQFs~3N+*OtdR~{Ge&is240Gm2 zMoJI_0&Prj?lN+4U<25Lz+t-pdt zv-j)MZN|Q4mlt=I@0)uzr#Kicn<=8e`->xBya30v;O0X(0uHO5w6B(26Qj(CAF-Xm z=Z^0C&`;teZyP5?nZoPJ_<=h6S)Rxc!V{|^+3tIIC+poLoNI3R6Yhce648B4*2~P+ zOYGy`RvZL2-LEdmU~E9rJXx%V0m6j!2LMe0hsp~4!GM)T^QY|2nq5w{#;G4bx+wm@ z(km&!i}~(1EYtc_$LEDwBm0vDmcJ=1`J?+W(b0oIAYPm{uN!Xm1wRZ6zWIxWBDczk z2)dl4%o|C@5=Xb6ceTszM&q)4c;Xf8IFRQaj`iM;uF|Ft2jUe3M%)=g3@!j*-vZ#+ zPlNuh9a$t7RW_M%P+iaaQ!Z$s@CjyX)pdOkAShd|`bkoh8jTiMPCP{W0z}Ue)6>)T z4;KaiY>l7ue9Pj)`^XvlF7=C1I_)m*tJr17WS|ch+>RmUKXSC$t}*EUNW|F+Xqg7M z(5@@?Fal2p6dg}T{O3BJ@ubfp*05zm&&WCC;-1&O9oUy#)!0iKMO+TAoZ|LyB8Q+56 zOfNTi&hujhBC5OJ@NGM9u?>xk`0qB;Cg2)w23@R(k!P~sUw({twdj}5T6A0v5rC8U zPVnD5wM|@42*z&qhr&4dgcx|;fqM{WVE*}^selt@O$|uCX6NMG228WP@;2f7h5=Bb zj)XyRQdClM^1kCHeX1kZqP#qa?$^8Yd27HNfbSC9a*M3{JfAXtU41(4dOj0XQBmm` zrvCi-@#UE|QRd}P!59AF1j>%5)K=)}am8-vQcC^HS{mu_KuJV_`*^w4v3K{wR_CFXxuK}Qdn;rsMQ&-XRaaoPKR6(%?!n|glS zZuLSlX%KL9_iy?0f4nWkB~b((NY8f}v|E1OJI3I#Q5`rwSOgFX`gl$5tJ5ZeN>y~5 z?Qg|Hwme{=0jl5kvlq30)V)Ol2cjo~+tKYyKgsp}#J-gc-Ip)D315`$_A_0tJOcmz z`E&KuCX(9&BrSKk;#uGwuNc--+Bm6!QGHCk*9jJu7wsR~CU)OY;0A9|5#bXG?hj!q ztNTL~c6Rx+pYLv+cIO#|IK=O70oBYwC}`IYdO#OaWE`4c32dJf9IE5XFjO&9^_Nisj8s;-yK5&izq^JW78DK<9?`M z-s!K6o#iQ++wZD2UpX-9T|WhA)})|(0Oj53GO&CTdBu5N=jVvA4$qn~>m~qF!X6%N z^Fi=kS)i7r#w}6Ttahg3vtu%i&iCpXkPDn}otNU|ARUH-_l)tK0 zDO*ZrEyk@g8RBP@tJ;oeE3{kDfdW7SfO{LDv|{|GS*t<+u)O{j0x;@zlbq1%`!%9t z#k+yl=fJZz;s8K(CniVt^yzp0NBaXDP+Saak9X;?@6Uwri1<N_}m zi&~KbSqPG-#9YyT@`Fwv@ zW_qZuVxoe7(|DoA;G+TnsGz&o&6FfAvp(2<7l3uz%M%n5Q5S6!K&DkxQ5o>$r=z3u zrg9^FfxYp7m6%kl;zb9)S2YaB6!AZf?g&Tn!58u!Vn!@b>Me|`@e`SQ?sAh$u_M}B zy^givZmx#A(DS}kZBAI!88BqQX4DQd8jdlTDN)qDUu<=x21X7G_E9`?Puv1Y?@G6O zwp`tDFX{8k@zE`66fi!CS+-X4XZUcr&40EtuxGZS1A@S4$bp9%EfJkD`%J(7=b_%3#os1Uhnb-^Xk3_Vg(gBG_aY6 zJ5$~Z$VVNSu@4jL$7Hy|@5eL8Uxn541Py{jq_6L zCv%1vFgxyby1j(olcGOzF7lvaP|0n`G4|A1#a0q4DJuG}w!7xn)%{AoE-WrK>VrC8 zjMUoy_br1fj;&S5$43Cj@I$gXVET_&yB}oz)XQ6krYck)iiieg2)av6%l9*8_;MEg z>CZgmaI#7TJ$!kfp9w0XoHXy})F_+v;Je%Bv>*0mxZ<%6Q$Xy0(4IBi9*TYdN{aSI zjqE-x>2^=vcq$WURuy6%5udt(O&2Mf>Vmz0Ffqa}Ik zl>G0@1440;P}l&v)UFJ$CQzk@qBq12%t23kTd_P*xD>YfO(sz$GL@5|r@Z<->=L8u zwAO*d=fNNw;{pd@bhpRz*GhAPkvNJvI;(fjWvb;hZkJn4;SU_?NU}-vy+GXKIcaLQ z3h<8SdI2P#Yu!^vhiLC_Du&8a{m_ua3Xly;%F5s$2w$a3szZf7dAr6$%#hLk>Mk^S z!te({m5Lx0v!i4EhSd>&(#?SCA!Swi)JW^pt3)10{>7cED&2*e*msM+(Vg7bDc!P})O)b1(x?Pf0~Z&dQ1oFr%-4j&lKsG#;z( z09EbnaKGllNj#I2mWD$n$9xaIBz{r z9v$R{+8tLmJ1{B??$%ET^aIpe8~WSHN-M^Pg5Z_(IIFH_@bYlE(CzD+{D&=7PNPQO zf4-Lsv0wjB!WYJBpjdGfC`KjZc7Ot6aS%t(YxBNj76=jOkC$tmp6x34Z;XUhp+d~` zDBGz(Ntnd&j)xRIltYIJTfYc3cX-kATbxA{oW&QTr9C~&x=(0&0+rWO04Zs4%Wv!~ z?P|ohKDUUQ-B-Cw$9c?aXE(F&&AU6m1X9+z5L5yz5D#c+!5kR;Od;UIY-kj(A9g~t zijvM@-3JiX1#=6gTu>Muo9RXj?^#cQbUd@u0VsLz5h&+&_Vx^cTIvBvuJ(I>@v8R~ zX)w9$Ho$m@5iozzyy*_$ zr$%!Xnwijj2K^xhy#b#-N;Xzj)}^BE#ZwpKA3uzMuRH+BoEsCt?r}=A|C62Ii59^w&hgE{9UUnuGD!d z>>DmzoJedm0i@aMwh#5ORGa_XE)bCc@YTj@$i2SLr34v!s6u}cc z3xPzLVEgSM1Aq=O<0Af)DFnncF#x1o&eu-s1%Vkhe1Chz74+$tKLrMR_^$^o#9(R7 zRa8{8SdY0t>C3P9c<$mAP>xlt)nZ*u3vnB1a&v~Bs4_Y;A3q*f?1g5cR_eZH599T&u!zqTpL!U`K zY20scFh#}77WX;GkH4DbN;9hpQDtR*LS)_nau%nj1LAYh6X^-QYeal}{EH>a>PPRW z{!Li3o>3r#Nzub=>^4Obl9CJ${}pBuPtVK*eU#Mu+%azGX1SmZ^(VPY|Yut+-A$qA~3DJZ|;6O$*5?go^HdG2L;=trix~hGybOED8 z$E%p@;aTYS7b71Y7`3@<`$qXos5*AfByMMI2MAuEmW9d!YEE71RabTZq&fg@Y27Ud zgl$+<)IgqiWLx3iVPa3jNF1iSR+N6`59H5Pp>@}Zkfuc61TbvqDSpax5>s|(@?a|`JSIN|7 zgMhFI-l~08cUn74`~hXmzHeURK4VqCq$u5PXVqV`bbFW)*F26H~@QVWdY3V3ljI6Ahg zxBw%6+p3JMqX0C!bsxbfis5z+kE-$kay0TAd|Yz&$z%4g$x<})$zIglKoCvOleast zl6J1r`M?HPAlNZAYyyQQH7l!^f^(f#<-<$w{0(dgF;&XPK;R^f zU&;17;~p;>0`%C8qI8=pw+|U4h1=0I`DizK)?%#8EWpl?vo}$ zwASG@Rf}LVZaT8Fo}iw>$3mr(zmwm(S@4f9@6ug+HxG2YduS7h?*(rd$;ms4Z7He% z9Tx!H4;lvjy~#@0$jGR8_=BC)jWYJ%&g;c4+jbL8P3c(nx$tB@06g$wjC1`%pYy52 zNX^KITCD$J1i*Agcuo5efaDsrhMxefH2gz@qA>bUEP$eM3vj003hfGJ-E1hlJQnA$i&O+3D}h}^{p_IKJW zz`lg>*BRPRh-g~4H(I!ez$3nx#6b=Sio>C?Vkj(jo&>I8iL5vw{PH)$Hd%6rOK_62 ziJ4PXg)EVe1}F=_mIR=^0_dX~+D5;a0Ge=L1Fcg7G)iy)@_G~1*Q3{)UZ`hOFTXGf zV7ac{3QivOZ97r~-5}+T4y=kY%EktQ7TVYLe!B77AQ^NQa4J`IAc%&z=?ziMKtYgE znT!v#y^B}N9%_^+lO|l>Z<9m&6b^w;BEk>y zKbTYTFHisAfHd4HhDVb|RKg-;#H?0ODUtERXBwn`N_nV9h=@p4PYXhP2E$C6-8^QX z-bCzgE>DtW-mW8)QeY2iqxG@pAzEnNwmeyC{byM<1Bgt}V&b34S!ux)rvg#&Qo~9P z#DI-B9m(RbWSIwo0B4B7N-#Rjx-jE_0;^PtxGb$r`B=7t%hBjk)YgW}+f>;zQgLd> z)1Cw_O^Pa194V~gL{6R$O~zXHm4-^l<;y%hSx}Jw8y1a!l76d!uK;08Pm&gVh&HWA zf?9Zs)Yp)K<2ZJqdFmv8E1N1wn{mbr2Cj%-ThnG{B^I(E()iMxY4Lu$FQ^jYpZic# z{eJ(33KPrCB$0t7^EvPZ?oXzS09emnPY`@++-_B_yZZm zBlQiB2E1p}7_bVQOEx_`4Vk~6L5}hWYN2vZP8@|&dCN^bIlW}XN1Ivd9Vwv_Sfl?# z_Smkd1Rq$lqd09AFunK|2Q1mgWoN}@hX+p1Y=#v!^T%M4rq9EP7TBYz3(9dCuJaq5 z``1mSpQ6kCI|SI(YU?2otOG2n5TeSB4Mr7_id;)vjs}h&8vLJ)(f@~yt^XHa6ow-G kGLuLOwAuR-Zr{N>nRg^@%ZnL+t-xT?;__luBKiUU3yFsMD*ylh literal 0 HcmV?d00001 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. +

From a8480abcd1ef5599c6d8384624e4a42d7a791fcb Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 13:23:53 -0600 Subject: [PATCH 24/35] chore: reformat readme from markdown to rst --- README.rst | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 README.rst diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..696f8c7 --- /dev/null +++ b/README.rst @@ -0,0 +1,17 @@ +.. 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://landscape.io/github/csdms/bmi-python/master/landscape.svg + :target: https://landscape.io/github/csdms/bmi-python/master + +.. image:: https://readthedocs.org/projects/bmi-forum/badge/?version=latest + :target: https://readthedocs.org/projects/bmi-forum/?badge=latest + + +bmi-example-python +================== + +An example BMI implementation written in Python From d9c8fea55bf3b3d9a828c174f6acef7c0263535f Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 13:25:25 -0600 Subject: [PATCH 25/35] docs: add bmi-heat docs, remove bmi-python stuff --- Makefile | 8 +- README.md | 9 -- docs/Makefile | 2 +- docs/source/conf.py | 223 +++++++++++----------------------------- docs/source/index.rst | 26 +---- docs/source/modules.rst | 6 +- 6 files changed, 70 insertions(+), 204 deletions(-) delete mode 100644 README.md diff --git a/Makefile b/Makefile index a6365f5..783b25d 100644 --- a/Makefile +++ b/Makefile @@ -70,12 +70,12 @@ coverage: ## check code coverage quickly with the default Python $(BROWSER) htmlcov/index.html docs: ## generate Sphinx HTML documentation, including API docs - rm -f docs/heat.rst - rm -f docs/modules.rst - sphinx-apidoc -o docs/ heat + 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 + $(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 . 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/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/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/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 From f56b75d9a2403665534c9dec3df9cb6da7184f62 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 13:31:37 -0600 Subject: [PATCH 26/35] chore: use README.rst for long description --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 0a68bbe..2a58668 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ author="Eric Hutton", author_email="eric.hutton@colorado.edu", description="BMI Python example", - long_description=open("README.md").read(), + long_description=open("README.rst").read(), classifiers=[ "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", From 60b996e5fe0215b8ffa6276c62c5aaebce08c831 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 15:33:05 -0600 Subject: [PATCH 27/35] chore: remove unused model metadata --- .bmi/api.yaml | 8 -------- .bmi/heat_input.txt.tmpl | 1 - .bmi/info.yaml | 4 ---- .bmi/parameters.yaml | 44 ---------------------------------------- .gitmodules | 0 5 files changed, 57 deletions(-) delete mode 100644 .bmi/api.yaml delete mode 100644 .bmi/heat_input.txt.tmpl delete mode 100644 .bmi/info.yaml delete mode 100644 .bmi/parameters.yaml delete mode 100644 .gitmodules 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/.gitmodules b/.gitmodules deleted file mode 100644 index e69de29..0000000 From b94ccd94953c5dae81e2e5c8e54ecb16aaa983a8 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 15:37:07 -0600 Subject: [PATCH 28/35] fix: order of args for set_value_at_indices --- heat/bmi_heat.py | 6 +++--- tests/test_set_value.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/heat/bmi_heat.py b/heat/bmi_heat.py index ea8843d..fa3998c 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -238,7 +238,7 @@ def set_value(self, var_name, src): 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 @@ -250,8 +250,8 @@ def set_value_at_indices(self, var_name, src, indices): indices : array_like Array of indices. """ - val = self.get_value_ptr(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.""" diff --git a/tests/test_set_value.py b/tests/test_set_value.py index b6b080d..8b4898f 100644 --- a/tests/test_set_value.py +++ b/tests/test_set_value.py @@ -25,7 +25,7 @@ def test_set_value_at_indices(): model = BmiHeat() model.initialize() - model.set_value_at_indices("plate_surface__temperature", [-1, -1, -1], [0, 2, 4]) + 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) From 63c8ae7728c671fef270ab9d0578e3c1afffd080 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 15:41:23 -0600 Subject: [PATCH 29/35] chore: use yaml.safe_load --- heat/heat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/heat/heat.py b/heat/heat.py index a6f5bff..56ab831 100644 --- a/heat/heat.py +++ b/heat/heat.py @@ -162,7 +162,7 @@ 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): From 07543227633655838bdfc65b6fa758028643af2a Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 15:41:42 -0600 Subject: [PATCH 30/35] chore: more badges, including BMI --- README.rst | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 696f8c7..ddf92c2 100644 --- a/README.rst +++ b/README.rst @@ -1,15 +1,24 @@ +.. 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://landscape.io/github/csdms/bmi-python/master/landscape.svg - :target: https://landscape.io/github/csdms/bmi-python/master +.. image:: https://landscape.io/github/csdms/bmi-example-python/master/landscape.svg + :target: https://landscape.io/github/csdms/bmi-example-python/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/pymt + +.. image:: https://www.codacy.com/app/mcflugen/pymt?utm_source=github.com&utm_medium=referral&utm_content=csdms/pymt&utm_campaign=Badge_Grade + :target: https://api.codacy.com/project/badge/Grade/e8e273131ecb4d7d981fe9f4cf3e83d9 bmi-example-python ================== From 46a9cc4296df284face4ff511ab7e363364f0216 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 15:42:01 -0600 Subject: [PATCH 31/35] chore: add codacy config file --- .codacy.yaml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .codacy.yaml diff --git a/.codacy.yaml b/.codacy.yaml new file mode 100644 index 0000000..cdfc148 --- /dev/null +++ b/.codacy.yaml @@ -0,0 +1,6 @@ +exclude_paths: + - tests/** + - docs/conf.py + - setup.py + - versioneer.py + - heat/_version.py From c3138e91f4d0d300aec66229f47a1ea607170ca4 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 15:57:28 -0600 Subject: [PATCH 32/35] chore: remove cruft --- .landscape.yaml | 7 - .travis/install_python.sh | 30 -- docs/source/_static/csdms.css | 652 ---------------------------------- docs/source/bmi_ext.py | 84 ----- 4 files changed, 773 deletions(-) delete mode 100644 .landscape.yaml delete mode 100644 .travis/install_python.sh delete mode 100644 docs/source/_static/csdms.css delete mode 100644 docs/source/bmi_ext.py 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/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/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/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) From 661a18de3f47d1627332637615728b6e777de5eb Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 15:59:20 -0600 Subject: [PATCH 33/35] chore: update codacy config --- .codacy.yaml | 2 +- README.rst | 7 ++----- setup.cfg | 3 +++ 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.codacy.yaml b/.codacy.yaml index cdfc148..42e47a4 100644 --- a/.codacy.yaml +++ b/.codacy.yaml @@ -1,6 +1,6 @@ exclude_paths: - tests/** - - docs/conf.py + - docs/source/conf.py - setup.py - versioneer.py - heat/_version.py diff --git a/README.rst b/README.rst index ddf92c2..9f57420 100644 --- a/README.rst +++ b/README.rst @@ -8,16 +8,13 @@ .. 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://landscape.io/github/csdms/bmi-example-python/master/landscape.svg - :target: https://landscape.io/github/csdms/bmi-example-python/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/pymt + :target: https://github.com/csdms/bmi -.. image:: https://www.codacy.com/app/mcflugen/pymt?utm_source=github.com&utm_medium=referral&utm_content=csdms/pymt&utm_campaign=Badge_Grade +.. image:: 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 :target: https://api.codacy.com/project/badge/Grade/e8e273131ecb4d7d981fe9f4cf3e83d9 bmi-example-python diff --git a/setup.cfg b/setup.cfg index 3beb1df..ca3acd6 100644 --- a/setup.cfg +++ b/setup.cfg @@ -37,3 +37,6 @@ ignore = E501 W503 max-line-length = 88 + +[pylint] +disable = missing-docstring,line-too-long From 6a18d7456e0a31f5ab9f6702fbbb6dcb0bb83503 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 16:07:17 -0600 Subject: [PATCH 34/35] style: remove lint --- heat/bmi_heat.py | 14 ++++++++++---- tests/test_irf.py | 4 ++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/heat/bmi_heat.py b/heat/bmi_heat.py index fa3998c..e2cddd4 100644 --- a/heat/bmi_heat.py +++ b/heat/bmi_heat.py @@ -21,9 +21,14 @@ def __init__(self): 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. @@ -42,6 +47,7 @@ def initialize(self, filename=None): 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"} @@ -129,7 +135,7 @@ def get_var_itemsize(self, name): return np.dtype(self.get_var_type(name)).itemsize def get_var_location(self, name): - return "node" + return self._var_loc[name] def get_var_grid(self, var_name): """Grid id for a variable. @@ -284,11 +290,11 @@ def get_grid_type(self, grid_id): def get_start_time(self): """Start time of model.""" - return 0.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): return self._model.time @@ -297,7 +303,7 @@ def get_time_step(self): return self._model.time_step def get_time_units(self): - return "s" + return self._time_units def get_grid_edge_count(self, grid): raise NotImplementedError("get_grid_edge_count") diff --git a/tests/test_irf.py b/tests/test_irf.py index 6731939..a6811ac 100644 --- a/tests/test_irf.py +++ b/tests/test_irf.py @@ -40,7 +40,7 @@ def test_initialize_defaults(): def test_initialize_from_file_like(): - config = StringIO(yaml.dump({"shape": (7, 5)})) + config = StringIO(yaml.dump({"shape": [7, 5]})) model = BmiHeat() model.initialize(config) @@ -53,7 +53,7 @@ def test_initialize_from_file(): import tempfile with tempfile.NamedTemporaryFile("w", delete=False) as fp: - fp.write(yaml.dump({"shape": (7, 5)})) + fp.write(yaml.dump({"shape": [7, 5]})) name = fp.name model = BmiHeat() From e1700481ddb11634e9465f932dea2447f31254e4 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 19 Apr 2019 16:12:40 -0600 Subject: [PATCH 35/35] chore: update codacy badge --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 9f57420..ee077b6 100644 --- a/README.rst +++ b/README.rst @@ -14,8 +14,8 @@ .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/csdms/bmi -.. image:: 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 - :target: https://api.codacy.com/project/badge/Grade/e8e273131ecb4d7d981fe9f4cf3e83d9 +.. 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 ==================