diff --git a/.gitattributes b/.gitattributes index 5dc017363..e4c1cc00f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ pint/extern/_version.py export-subst +src/pint/extern/_version.py export-subst diff --git a/AUTHORS.rst b/AUTHORS.rst index 07bbac26c..de5bf4441 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -41,7 +41,7 @@ Active developers are indicated by (*). Authors of the PINT paper are indicated * Sasha Levina * Nikhil Mahajan * Alex McEwen -* Patrick O'Neill +* Patrick O'Neill (*) * Tim Pennucci * Camryn Phillips (#) * Matt Pitkin diff --git a/CHANGELOG-unreleased.md b/CHANGELOG-unreleased.md index 21722454a..6d7dae96c 100644 --- a/CHANGELOG-unreleased.md +++ b/CHANGELOG-unreleased.md @@ -14,6 +14,7 @@ the released changes. - Made `Residuals` independent of `GLSFitter` (GLS chi2 is now computed using the new function `Residuals._calc_gls_chi2()`). - `ssb_to_psb_ICRS` implementation is now a lot faster (uses erfa functions directly) - `ssb_to_psb_ECL` implementation within `AstrometryEcliptic` model is now a lot faster (uses erfa functions directly) +- Upgraded versioneer for compatibility with Python 3.12 ### Added - CHI2, CHI2R, TRES, DMRES now in postfit par files - Added `WaveX` model as a `DelayComponent` with Fourier amplitudes as fitted parameters @@ -22,6 +23,8 @@ the released changes. - Added radial velocity methods for binary models - Support for wideband data in `pint.bayesian` (no correlated noise). - Added `DMWaveX` model (Fourier representation of DM noise) +- Piecewise orbital model (`BinaryBTPiecewise`) +- Simulate correlated noise using `pint.simulation` (also available via the `zima` script) ### Fixed - Wave model `validate()` can correctly use PEPOCH to assign WAVEEPOCH parameter - Fixed RTD by specifying theme explicitly. diff --git a/src/pint/data/examples/B1855+09_NANOGrav_9yv1.gls.par b/src/pint/data/examples/B1855+09_NANOGrav_9yv1.gls.par index 2138184bd..645cb802a 100644 --- a/src/pint/data/examples/B1855+09_NANOGrav_9yv1.gls.par +++ b/src/pint/data/examples/B1855+09_NANOGrav_9yv1.gls.par @@ -453,7 +453,7 @@ FD3 1.07526915D-04 1 2.50177766D-05 SOLARN0 0.00 EPHEM DE421 ECL IERS2003 -CLK TT(BIPM) +CLK TT(BIPM2019) UNITS TDB TIMEEPH FB90 #T2CMETHOD TEMPO diff --git a/src/pint/extern/__init__.py b/src/pint/extern/__init__.py index 37dfc738e..6d5e6c4d5 100644 --- a/src/pint/extern/__init__.py +++ b/src/pint/extern/__init__.py @@ -1,2 +1,6 @@ # __init__.py for pint/extern """External/third-party modules that are distributed with PINT.""" + +from . import _version + +__version__ = _version.get_versions()["version"] diff --git a/src/pint/extern/_version.py b/src/pint/extern/_version.py index 878bad322..39cfe2330 100644 --- a/src/pint/extern/_version.py +++ b/src/pint/extern/_version.py @@ -4,8 +4,9 @@ # 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) +# This file is released into the public domain. +# Generated by versioneer-0.29 +# https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" @@ -14,9 +15,11 @@ import re import subprocess import sys +from typing import Any, Callable, Dict, List, Optional, Tuple +import functools -def get_keywords(): +def get_keywords() -> Dict[str, str]: """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 @@ -32,8 +35,15 @@ def get_keywords(): class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + parentdir_prefix: str + versionfile_source: str + verbose: bool -def get_config(): + +def get_config() -> VersioneerConfig: """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py @@ -42,7 +52,7 @@ def get_config(): cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "'pint-'" - cfg.versionfile_source = "pint/extern/_version.py" + cfg.versionfile_source = "src/pint/extern/_version.py" cfg.verbose = False return cfg @@ -51,14 +61,14 @@ class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" -LONG_VERSION_PY = {} -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} @@ -68,24 +78,39 @@ def decorate(f): return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, + process = subprocess.Popen( + [command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, ) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -96,18 +121,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= if verbose: print("unable to find command, tried %s" % (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -116,7 +143,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return { @@ -126,9 +153,8 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): "error": None, "date": None, } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: print( @@ -139,41 +165,48 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """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 = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -186,11 +219,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -199,7 +232,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -208,6 +241,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix) :] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r"\d", r): + continue if verbose: print("picking %s" % r) return { @@ -230,7 +268,9 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -241,7 +281,14 @@ 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) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -249,7 +296,7 @@ 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( + describe_out, rc = runner( GITS, [ "describe", @@ -258,7 +305,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): "--always", "--long", "--match", - "%s*" % tag_prefix, + f"{tag_prefix}[[:digit:]]*", ], cwd=root, ) @@ -266,16 +313,48 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -292,7 +371,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces @@ -318,26 +397,27 @@ 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) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -361,23 +441,70 @@ def render_pep440(pieces): return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] + rendered = "0.post0.dev%d" % pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -404,12 +531,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -426,7 +582,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -446,7 +602,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -466,7 +622,7 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return { @@ -482,10 +638,14 @@ def render(pieces, style): if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -504,7 +664,7 @@ def render(pieces, style): } -def get_versions(): +def get_versions() -> Dict[str, Any]: """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 @@ -524,7 +684,7 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split("/"): + for _ in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: return { diff --git a/src/pint/models/__init__.py b/src/pint/models/__init__.py index f5a46d3b9..e08e69965 100644 --- a/src/pint/models/__init__.py +++ b/src/pint/models/__init__.py @@ -20,7 +20,7 @@ # Import all standard model components here from pint.models.astrometry import AstrometryEcliptic, AstrometryEquatorial -from pint.models.binary_bt import BinaryBT +from pint.models.binary_bt import BinaryBT, BinaryBTPiecewise from pint.models.binary_dd import BinaryDD, BinaryDDS, BinaryDDGR from pint.models.binary_ddk import BinaryDDK from pint.models.binary_ell1 import BinaryELL1, BinaryELL1H, BinaryELL1k diff --git a/src/pint/models/binary_bt.py b/src/pint/models/binary_bt.py index 2797ca5cc..6a40ae9f4 100644 --- a/src/pint/models/binary_bt.py +++ b/src/pint/models/binary_bt.py @@ -1,9 +1,22 @@ """The BT (Blandford & Teukolsky) model.""" - +import numpy as np from pint.models.parameter import floatParameter from pint.models.pulsar_binary import PulsarBinary from pint.models.stand_alone_psr_binaries.BT_model import BTmodel -from pint.models.timing_model import MissingParameter +from pint.models.stand_alone_psr_binaries.BT_piecewise import BTpiecewise +from pint.models.timing_model import MissingParameter, TimingModel +import astropy.units as u +from pint import GMsun, Tsun, ls +from astropy.table import Table +from astropy.time import Time +from pint.models.parameter import ( + MJDParameter, + floatParameter, + prefixParameter, + maskParameter, +) + +from pint.toa_select import TOASelect class BinaryBT(PulsarBinary): @@ -66,3 +79,464 @@ def validate(self): if self.GAMMA.value is None: self.GAMMA.value = "0" self.GAMMA.frozen = True + + +"""The BT (Blandford & Teukolsky) model with piecewise orbital parameters. +See Blandford & Teukolsky 1976, ApJ, 205, 580. +""" + + +class BinaryBTPiecewise(PulsarBinary): + """Model implementing the BT model with piecewise orbital parameters A1X and T0X. This model lets the user specify time ranges and fit for a different piecewise orbital parameter in each time range, + This is a PINT pulsar binary BTPiecewise model class, a subclass of PulsarBinary. + It is a wrapper for stand alone BTPiecewise class defined in + ./stand_alone_psr_binary/BT_piecewise.py + The aim for this class is to connect the stand alone binary model with the PINT platform. + BTpiecewise special parameters, where xxxx denotes the 4-digit index of the piece: + T0X_xxxx Piecewise T0 values for piece + A1X_xxxx Piecewise A1 values for piece + XR1_xxxx Lower time boundary of piece + XR2_xxxx Upper time boundary of piece + """ + + register = True + + def __init__(self): + super(BinaryBTPiecewise, self).__init__() + self.binary_model_name = "BT_piecewise" + self.binary_model_class = BTpiecewise + self.add_param( + floatParameter( + name="GAMMA", + value=0.0, + units="second", + description="Time dilation & gravitational redshift", + ) + ) + self.A1_value_funcs = [] + self.T0_value_funcs = [] + self.remove_param("M2") + self.remove_param("SINI") + self.add_group_range(None, None) + self.add_piecewise_param(0, T0=0 * u.d) + self.add_piecewise_param(0, A1=0 * ls) + + def add_group_range( + self, + group_start_mjd, + group_end_mjd, + piece_index=None, + ): + """Add an orbital piecewise parameter group range. If piece_index is not provided a new piece will be added with index equal to the number of pieces plus one. Pieces cannot have the duplicate pieces and cannot have the same index. A pair of consisting of a piecewise A1 and T0 may share an index and will act over the same piece range. + Parameters + ---------- + group_start_mjd : float or astropy.quantity.Quantity or astropy.time.Time + MJD for the piece lower boundary + group_end_mjd : float or astropy.quantity.Quantity or astropy.time.Time + MJD for the piece upper boundary + piece_index : int + Number to label the piece being added. + """ + if group_start_mjd is not None and group_end_mjd is not None: + if isinstance(group_start_mjd, Time): + group_start_mjd = group_start_mjd.mjd + elif isinstance(group_start_mjd, u.quantity.Quantity): + group_start_mjd = group_start_mjd.value + if isinstance(group_end_mjd, Time): + group_end_mjd = group_end_mjd.mjd + elif isinstance(group_end_mjd, u.quantity.Quantity): + group_end_mjd = group_end_mjd.value + + elif group_start_mjd is None or group_end_mjd is None: + if group_start_mjd is None and group_end_mjd is not None: + group_start_mjd = group_end_mjd - 100 + elif group_start_mjd is not None and group_end_mjd is None: + group_end_mjd = group_start_mjd + 100 + else: + group_start_mjd = 50000 + group_end_mjd = 60000 + + if piece_index is None: + dct = self.get_prefix_mapping_component("XR1_") + if len(list(dct.keys())) > 0: + piece_index = np.max(list(dct.keys())) + 1 + else: + piece_index = 0 + + # check the validity of the desired group to add + + if group_end_mjd is not None and group_start_mjd is not None: + if group_end_mjd <= group_start_mjd: + raise ValueError("Starting MJD is greater than ending MJD.") + elif piece_index < 0: + raise ValueError( + f"Invalid index for group: {piece_index} should be greater than or equal to 0" + ) + elif piece_index > 9999: + raise ValueError( + f"Invalid index for group. Cannot index beyond 9999 (yet?)" + ) + + i = f"{int(piece_index):04d}" + self.add_param( + prefixParameter( + name="XR1_{0}".format(i), + units="MJD", + description="Beginning of paramX interval", + parameter_type="MJD", + time_scale="utc", + value=group_start_mjd, + ) + ) + self.add_param( + prefixParameter( + name="XR2_{0}".format(i), + units="MJD", + description="End of paramX interval", + parameter_type="MJD", + time_scale="utc", + value=group_end_mjd, + ) + ) + self.setup() + + def remove_range(self, index): + """Removes all orbital piecewise parameters associated with a given index/list of indices. + Parameters + ---------- + index : float, int, list, np.ndarray + Number or list/array of numbers corresponding to T0X/A1X indices to be removed from model. + """ + + if ( + isinstance(index, int) + or isinstance(index, float) + or isinstance(index, np.int64) + ): + indices = [index] + elif not isinstance(index, list) or not isinstance(index, np.ndarray): + raise TypeError( + f"index must be a float, int, list, or array - not {type(index)}" + ) + for index in indices: + index_rf = f"{int(index):04d}" + for prefix in ["T0X_", "A1X_", "XR1_", "XR2_"]: + if hasattr(self, f"{prefix+index_rf}"): + self.remove_param(prefix + index_rf) + if hasattr(self.binary_instance, "param_pieces"): + if len(self.binary_instance.param_pieces) > 0: + temp_piece_information = [] + for item in self.binary_instance.param_pieces: + if item[0] != index_rf: + temp_piece_information.append(item) + self.binary_instance.param_pieces = temp_piece_information + # self.binary_instance.param_pieces = self.binary_instance.param_pieces.remove('index_rf') + + self.validate() + self.setup() + + def add_piecewise_param(self, piece_index, **kwargs): + """Add an orbital piecewise parameter. + Parameters + ---------- + piece_index : int + Number to label the piece being added. Expected to match a set of piece boundaries. + param : str + Piecewise parameter label e.g. "T0" or "A1". + paramx : np.float128 or astropy.quantity.Quantity + Piecewise parameter value. + """ + for key in ("T0", "A1"): + if key in kwargs: + param = key + paramx = kwargs[key] + + if key == "T0": + param_unit = u.d + if isinstance(paramx, u.quantity.Quantity): + paramx = paramx.value + elif isinstance(paramx, np.float128): + paramx = paramx + elif isinstance(paramx, Time): + paramx = paramx.mjd + else: + raise ValueError( + "Unspported data type '%s' for piecewise T0. Ensure the piecewise parameter value is a np.float128, Time or astropy.quantity.Quantity" + % type(paramx) + ) + elif key == "A1": + param_unit = ls + if isinstance(paramx, u.quantity.Quantity): + paramx = paramx.value + elif isinstance(paramx, np.float64): + paramx = paramx + else: + raise ValueError( + "Unspported data type '%s' for piecewise A1. Ensure the piecewise parameter value is a np.float64 or astropy.quantity.Quantity" + % type(paramx) + ) + key_found = True + + if not key_found: + raise AttributeError( + "No piecewise parameters passed. Use T0 = / A1 = to declare a piecewise variable." + ) + + if piece_index is None: + dct = self.get_prefix_mapping_component(param + "X_") + if len(list(dct.keys())) > 0: + piece_index = np.max(list(dct.keys())) + 1 + else: + piece_index = 0 + elif int(piece_index) in self.get_prefix_mapping_component(param + "X_"): + raise ValueError( + "Index '%s' is already in use in this model. Please choose another." + % piece_index + ) + i = f"{int(piece_index):04d}" + + # handling if None are passed as arguments + if any(i is None for i in [param, param_unit, paramx]): + if param is not None: + # if parameter value or unit unset, set with default according to param + if param_unit is None: + param_unit = (getattr(self, param)).units + if paramx is None: + paramx = (getattr(self, param)).value + # check if name exists and is currently available + + self.add_param( + prefixParameter( + name=param + f"X_{i}", + units=param_unit, + value=paramx, + description="Parameter" + param + "variation", + parameter_type="float", + frozen=False, + ) + ) + self.setup() + + def setup(self): + """Raises + ------ + ValueError + if there are values that have been added without name/ranges associated (should only be raised if add_piecewise_param has been side-stepped with an alternate method) + """ + super().setup() + for bpar in self.params: + self.register_deriv_funcs(self.d_binary_delay_d_xxxx, bpar) + # Setup the model isinstance + self.binary_instance = self.binary_model_class() + # piecewise T0's + T0X_mapping = self.get_prefix_mapping_component("T0X_") + T0Xs = {} + # piecewise A1's (doing piecewise A1's requires more thought and work) + A1X_mapping = self.get_prefix_mapping_component("A1X_") + A1Xs = {} + # piecewise parameter ranges XR1-piece lower bound + XR1_mapping = self.get_prefix_mapping_component("XR1_") + XR1s = {} + # piecewise parameter ranges XR2-piece upper bound + XR2_mapping = self.get_prefix_mapping_component("XR2_") + XR2s = {} + + for index in XR1_mapping.values(): + index = index.split("_")[1] + piece_index = f"{int(index):04d}" + if hasattr(self, f"T0X_{piece_index}"): + if getattr(self, f"T0X_{piece_index}") is not None: + self.binary_instance.add_binary_params( + f"T0X_{piece_index}", getattr(self, f"T0X_{piece_index}") + ) + else: + self.binary_instance.add_binary_params( + f"T0X_{piece_index}", self.T0.value + ) + + if hasattr(self, f"A1X_{piece_index}"): + if hasattr(self, f"A1X_{piece_index}"): + if getattr(self, f"A1X_{piece_index}") is not None: + self.binary_instance.add_binary_params( + f"A1X_{piece_index}", getattr(self, f"A1X_{piece_index}") + ) + else: + self.binary_instance.add_binary_params( + f"A1X_{piece_index}", self.A1.value + ) + + if hasattr(self, f"XR1_{piece_index}"): + if getattr(self, f"XR1_{piece_index}") is not None: + self.binary_instance.add_binary_params( + f"XR1_{piece_index}", getattr(self, f"XR1_{piece_index}") + ) + else: + raise ValueError(f"No date provided to create a group with") + else: + raise ValueError(f"No name provided to create a group with") + + if hasattr(self, f"XR2_{piece_index}"): + if getattr(self, f"XR2_{piece_index}") is not None: + self.binary_instance.add_binary_params( + f"XR2_{piece_index}", getattr(self, f"XR2_{piece_index}") + ) + else: + raise ValueError(f"No date provided to create a group with") + else: + raise ValueError(f"No name provided to create a group with") + + self.update_binary_object(None) + + def validate(self): + """Include catches for overlapping groups. etc + Raises + ------ + ValueError + if there are pieces with no associated boundaries (T0X_0000 does not have a corresponding XR1_0000/XR2_0000) + ValueError + if any boundaries overlap (as it makes TOA assignment to a single group ambiguous). i.e. XR1_0000XR1_0001 + ValueError + if the number of lower and upper bounds don't match (should only be raised if XR1 is defined without XR2 and validate is run or vice versa) + """ + super().validate() + for p in ("T0", "A1"): + if getattr(self, p).value is None: + raise MissingParameter("BT", p, "%s is required for BT" % p) + + # If any *DOT is set, we need T0 + for p in ("PBDOT", "OMDOT", "EDOT", "A1DOT"): + if getattr(self, p).value is None: + getattr(self, p).set("0") + getattr(self, p).frozen = True + + if getattr(self, p).value is not None: + if self.T0.value is None: + raise MissingParameter("BT", "T0", "T0 is required if *DOT is set") + + if self.GAMMA.value is None: + self.GAMMA.set("0") + self.GAMMA.frozen = True + + dct_plb = self.get_prefix_mapping_component("XR1_") + dct_pub = self.get_prefix_mapping_component("XR2_") + dct_T0X = self.get_prefix_mapping_component("T0X_") + dct_A1X = self.get_prefix_mapping_component("A1X_") + if len(dct_plb) > 0 and len(dct_pub) > 0: + ls_plb = list(dct_plb.items()) + ls_pub = list(dct_pub.items()) + ls_T0X = list(dct_T0X.items()) + ls_A1X = list(dct_A1X.items()) + + j_plb = [((tup[1]).split("_"))[1] for tup in ls_plb] + j_pub = [((tup[1]).split("_"))[1] for tup in ls_pub] + j_T0X = [((tup[1]).split("_"))[1] for tup in ls_T0X] + j_A1X = [((tup[1]).split("_"))[1] for tup in ls_A1X] + + if j_plb != j_pub: + raise ValueError( + f"Group boundary mismatch error. Number of detected lower bounds: {j_plb}. Number of detected upper bounds: {j_pub}" + ) + if len(np.setdiff1d(j_plb, j_pub)) > 0: + raise ValueError( + f"Group index mismatch error. Check the indexes of XR1_/XR2_ parameters in the model" + ) + if not len(ls_A1X) > 0: + if len(ls_pub) > 0 and len(ls_T0X) > 0: + if len(np.setdiff1d(j_pub, j_T0X)) > 0: + raise ValueError( + f"Group index mismatch error. Check the indexes of T0X groups, make sure they match there are corresponding group ranges (XR1/XR2)" + ) + if not len(ls_T0X) > 0: + if len(ls_pub) > 0 and len(ls_A1X) > 0: + if len(np.setdiff1d(j_pub, j_A1X)) > 0: + raise ValueError( + f"Group index mismatch error. Check the indexes of A1X groups, make sure they match there are corresponding group ranges (/XR2)" + ) + lb = [(getattr(self, tup[1])).value for tup in ls_plb] + ub = [(getattr(self, tup[1])).value for tup in ls_pub] + + for i in range(len(lb)): + for j in range(len(lb)): + if i != j: + if max(lb[i], lb[j]) < min(ub[i], ub[j]): + raise ValueError( + f"Group boundary overlap detected. Make sure groups are not overlapping" + ) + + def paramx_per_toa(self, param_name, toas): + """Find the piecewise parameter value each toa will reference during calculations + Parameters + ---------- + param_name : string + which piecewise parameter to show: 'A1'/'T0'. TODO this should raise an error if not present) + toa : pint.toa.TOA + Returns + ------- + u.quantity.Quantity + length(toa) elements are T0X or A1X values to reference for each toa during binary calculations. + """ + condition = {} + tbl = toas.table + XR1_mapping = self.get_prefix_mapping_component("XR1_") + XR2_mapping = self.get_prefix_mapping_component("XR2_") + if not hasattr(self, "toas_selector"): + self.toas_selector = TOASelect(is_range=True) + if param_name[0:2] == "T0": + paramX_mapping = self.get_prefix_mapping_component("T0X_") + param_unit = u.d + elif param_name[0:2] == "A1": + paramX_mapping = self.get_prefix_mapping_component("A1X_") + param_unit = ls + else: + raise AttributeError( + "param '%s' not found. Please choose another. Currently implemented: 'T0' or 'A1' " + % param_name + ) + for piece_index in paramX_mapping.keys(): + r1 = getattr(self, XR1_mapping[piece_index]).quantity + r2 = getattr(self, XR2_mapping[piece_index]).quantity + condition[paramX_mapping[piece_index]] = (r1.mjd, r2.mjd) + select_idx = self.toas_selector.get_select_index(condition, tbl["mjd_float"]) + paramx = np.zeros(len(tbl)) * param_unit + for k, v in select_idx.items(): + paramx[v] += getattr(self, k).quantity + for i in range(len(paramx)): + if paramx[i] == 0: + paramx[i] = (getattr(self, param_name[0:2])).value * param_unit + + return paramx + + def get_number_of_groups(self): + """Get the number of piecewise parameters""" + return len(self.binary_instance.piecewise_parameter_information) + + def which_group_is_toa_in(self, toa): + """Find the group a toa belongs to based on the boundaries of groups passed to BT_piecewise + Parameters + ---------- + Returns + ------- + list + str elements, look like ['0000','0001'] for two TOAs where one refences T0X/A1X. + """ + # if isinstance(toa, pint.toa.TOAs): + # pass + # else: + # raise TypeError(f'toa must be a Time or pint.toa.TOAs - not {type(toa)}') + + tbl = toa.table + condition = {} + XR1_mapping = self.get_prefix_mapping_component("XR1_") + XR2_mapping = self.get_prefix_mapping_component("XR2_") + if not hasattr(self, "toas_selector"): + self.toas_selector = TOASelect(is_range=True) + boundaries = {} + for piece_index in XR1_mapping.keys(): + r1 = getattr(self, XR1_mapping[piece_index]).quantity + r2 = getattr(self, XR2_mapping[piece_index]).quantity + condition[(XR1_mapping[piece_index]).split("_")[-1]] = (r1.mjd, r2.mjd) + select_idx = self.toas_selector.get_select_index(condition, tbl["mjd_float"]) + paramx = np.empty(len(tbl), dtype=">import astropy.units as u + >>import numpy as np + + >>binary_model=BTpiecewise() + >>param_dict = {'T0': 50000, 'ECC': 0.2} + >>binary_model.update_input(**param_dict) + + >>t=np.linspace(50001.,60000.,10)*u.d + + Adding binary parameters and piece ranges + >>binary_model.add_binary_params('T0X_0000', 60000*u.d) + >>binary_model.add_binary_params('XR1_0000', 50000*u.d) + >>binary_model.add_binary_params('XR2_0000', 55000*u.d) + + Can add more pieces here... + + Overide default values values if desired + >>updates = {'T0X_0000':60000.*u.d,'XR1_0000':50000.*u.d,'XR2_0000': 55000*u.d} + + update the model with the piecewise parameter value(s) and piece ranges + >>binary_model.update_input(**updates) + + Using pint's get_model and loading this as a timing model and following the method described in ../binary_piecewise.py + sets _t multiple times during pint's residual calculation + for simplicity we're just going to set _t directly though this is not recommended. + >>setattr(binary_model,'_t' ,t) + + #here we call get_tt0 to get the "loaded toas" to interact with the pieces passed to the model earlier + #sets the attribute "T0X_per_toa" and/or "A1X_per_toa", contains the piecewise parameter value that will be referenced + #for each toa future calculations + >>binary_model.get_tt0(t) + #For a piecewise T0, tt0 becomes a piecewise quantity, otherwise it is how it functions in BT_model.py. + + #get_tt0 sets the attribute "T0X_per_toa" and/or "A1X_per_toa". + #contains the piecewise parameter value that will be referenced for each toa future calculations + >>binary_model.T0X_per_toa + + Information about any group can be found with the following: + >>binary_model.piecewise_parameter_information + Order: [[Group index, Piecewise T0, Piecewise A1, Piece lower bound, Piece upper bound]] + + Making sure a binary_model.tt0 exists + >>binary_model._tt0 = binary_model.get_tt0(binary_model._t) + + Obtain piecewise BTdelay() + >>binary_model.BTdelay() + """ + + def __init__(self, axis_store_initial=None, t=None, input_params=None): + self.binary_name = "BT_piecewise" + super(BTpiecewise, self).__init__() + if t is None: + self._t = None + self.axis_store_initial = [] + self.extended_group_range = [] + self.param_pieces = [] + self.d_binarydelay_d_par_funcs = [self.d_BTdelay_d_par] + if t is not None: + self._t = t + if input_params is not None: + if self.T0X is None: + self.update_input(input_params) + self.binary_params = list(self.param_default_value.keys()) + + def set_param_values(self, valDict=None): + super().set_param_values(valDict=valDict) + self.setup_internal_structures(valDict=valDict) + + def setup_internal_structures(self, valDict=None): + # initialise arrays to store T0X/A1X values per toa + self.T0X_arr = [] + self.A1X_arr = [] + # initialise arrays to store piecewise group boundaries + self.lower_group_edge = [] + self.upper_group_edge = [] + # initialise array that will be 5 x n in shape. Where n is the number of pieces required by the model + piecewise_parameter_information = [] + # If there are no updates passed by binary_instance, sets default value (usually overwritten when reading from parfile) + + if valDict is None: + self.T0X_arr = [self.T0] + self.A1X_arr = [self.A1] + self.lower_group_edge = [0] + self.upper_group_edge = [1e9] + self.piecewise_parameter_information = [ + 0, + self.T0, + self.A1, + 0 * u.d, + 1e9 * u.d, + ] + else: + # initialise array used to count the number of pieces. Operates by seaching for "A1X_i/T0X_i" and appending i to the array. + piece_index = [] + # Searches through updates for keys prefixes matching T0X/A1X, can be allowed to be more flexible with param+"X_" provided param is defined earlier. + for key, value in valDict.items(): + if ( + key[0:4] == "T0X_" + or key[0:4] == "A1X_" + and not (key[4:8] in piece_index) + ): + # appends index to array + piece_index.append((key[4:8])) + # makes sure only one instance of each index is present returns order indeces + piece_index = np.unique(piece_index) + # looping through each index in order they are given (0 -> n) + for index in piece_index: + # array to store specific piece i's information in the order [index,T0X,A1X,Group's lower edge, Group's upper edge,] + param_pieces = [] + piece_number = f"{int(index):04d}" + param_pieces.append(piece_number) + string = [ + "T0X_" + index, + "A1X_" + index, + "XR1_" + index, + "XR2_" + index, + ] + + # if string[0] not in param_pieces: + for i in range(0, len(string)): + if string[i] in valDict: + param_pieces.append(valDict[string[i]]) + elif string[i] not in valDict: + attr = string[i][0:2] + + if hasattr(self, attr): + param_pieces.append(getattr(self, attr)) + else: + raise AttributeError( + "Malformed valDict being used, attempting to set an attribute that doesn't exist. Likely a corner case slipping through validate() in binary_piecewise." + ) + # Raises error if range not defined as there is no Piece upper/lower bound in the model. + + piecewise_parameter_information.append(param_pieces) + + self.valDict = valDict + # sorts the array chronologically by lower edge of each group,correctly works for unordered pieces + + self.piecewise_parameter_information = sorted( + piecewise_parameter_information, key=lambda x: x[3] + ) + + # Uses the index for each toa array to create arrays where elements are the A1X/T0X to use with that toa + if len(self.piecewise_parameter_information) > 0: + if self._t is not None: + self.group_index_array = self.toa_belongs_in_group(self._t) + + ( + self.T0X_per_toa, + self.A1X_per_toa, + ) = self.piecewise_parameter_from_information_array(self._t) + + def piecewise_parameter_from_information_array(self, t): + """Creates a list of piecewise orbital parameters to use in calculations. It is the same dimensions as the TOAs loaded in. Each entry is the piecewise parameter value from the group it belongs to. + ---------- + t : Quantity. TOA, not necesserily barycentered + Returns + ------- + list + Quantity (length: t). T0X parameter to use for each TOA in calculations. + Quantity (length: t). A1X parameter to use for each TOA in calculations. + """ + A1X_per_toa = [] + T0X_per_toa = [] + if not hasattr(self, "group_index_array"): + self.group_index_array = self.toa_belongs_in_group(t) + if len(self.group_index_array) != len(t): + self.group_index_array = self.toa_belongs_in_group(t) + # searches the 5 x n array to find the index matching the toa_index + possible_groups = [item[0] for item in self.piecewise_parameter_information] + if len(self.group_index_array) > 1 and len(t) > 1: + for i in self.group_index_array: + if i != -1: + for k, j in enumerate(possible_groups): + if str(i) == j: + group_index = k + T0X_per_toa.append( + self.piecewise_parameter_information[group_index][ + 1 + ].value + ) + + A1X_per_toa.append( + self.piecewise_parameter_information[group_index][ + 2 + ].value + ) + + # if a toa lies between 2 groups, use default T0/A1 values (i.e. toa lies after previous upper bound but before next lower bound) + else: + T0X_per_toa.append(self.T0.value) + A1X_per_toa.append(self.A1.value) + + else: + T0X_per_toa = self.T0.value + A1X_per_toa = self.A1.value + + T0X_per_toa = T0X_per_toa * u.d + A1X_per_toa = A1X_per_toa * ls + + return [T0X_per_toa, A1X_per_toa] + + def toa_belongs_in_group(self, toas): + """Get the piece a TOA belongs to by finding which checking upper/lower edges of each piece. + ---------- + toas : Astropy.quantity.Quantity. + Returns + ------- + list + int (length: t). Group numbers + """ + group_no = [] + gb = self.get_group_boundaries() + + lower_edge = [] + upper_edge = [] + for i in range(len(gb[0])): + lower_edge.append(gb[0][i].value) + upper_edge.append(gb[1][i].value) + + # lower_edge, upper_edge = [self.get_group_boundaries()[:].value],[self.get_group_boundaries()[1].value] + for i in toas.value: + lower_bound = np.searchsorted(np.array(lower_edge), i) - 1 + upper_bound = np.searchsorted(np.array(upper_edge), i) + if lower_bound == upper_bound: + index_no = lower_bound + else: + index_no = -1 + if index_no != -1: + group_no.append(self.piecewise_parameter_information[index_no][0]) + else: + group_no.append(index_no) + return group_no + + def get_group_boundaries(self): + """Get the piecewise group boundaries from the dictionary of piecewise parameter information. + Returns + ------- + list + list (length: number of pieces). Contains all pieces' lower edge. + list (length: number of pieces). Contains all pieces' upper edge. + """ + lower_group_edge = [] + upper_group_edge = [] + if hasattr(self, "piecewise_parameter_information"): + for i in range(0, len(self.piecewise_parameter_information)): + lower_group_edge.append(self.piecewise_parameter_information[i][3]) + upper_group_edge.append(self.piecewise_parameter_information[i][4]) + return [lower_group_edge, upper_group_edge] + + def a1(self): + if len(self.piecewise_parameter_information) > 0: + # defines index for each toa as an array of length = len(self._t) + # Uses the index for each toa array to create arrays where elements are the A1X/T0X to use with that toa + self.A1X_per_toa = self.piecewise_parameter_from_information_array(self.t)[ + 1 + ] + + if hasattr(self, "A1X_per_toa"): + ret = self.A1X_per_toa + self.tt0 * self.A1DOT + else: + ret = self.A1 + self.tt0 * self.A1DOT + return ret + + def get_tt0(self, barycentricTOA): + """Finds (barycentricTOA - T0_x). Where T0_x is the piecewise T0 value, if it exists, correponding to the group the TOA belongs to. If T0_x does not exist, use the global T0 vlaue. + ---------- + Returns + ------- + astropy.quantity.Quantity + time since T0 + """ + if barycentricTOA is None or self.T0 is None: + return None + if len(barycentricTOA) > 1: + # defines index for each toa as an array of length = len(self._t) + # Uses the index for each toa array to create arrays where elements are the A1X/T0X to use with that toa + self.T0X_per_toa = self.piecewise_parameter_from_information_array( + barycentricTOA + )[0] + T0 = self.T0X_per_toa + else: + T0 = self.T0 + if not hasattr(barycentricTOA, "unit") or barycentricTOA.unit == None: + barycentricTOA = barycentricTOA * u.day + tt0 = (barycentricTOA - T0).to("second") + return tt0 + + def d_delayL1_d_par(self, par): + if par not in self.binary_params: + raise ValueError(f"{par} is not in binary parameter list.") + par_obj = getattr(self, par) + index, par_temp = self.in_piece(par) + if par_temp is None: + if hasattr(self, "d_delayL1_d_" + par): + func = getattr(self, "d_delayL1_d_" + par) + return func() * index + else: + if par in self.orbits_cls.orbit_params: + return self.d_delayL1_d_E() * self.d_E_d_par(par) + else: + return np.zeros(len(self.t)) * u.second / par_obj.unit + else: + if hasattr(self, "d_delayL1_d_" + par_temp): + func = getattr(self, "d_delayL1_d_" + par_temp) + return func() * index + else: + if par in self.orbits_cls.orbit_params: + return self.d_delayL1_d_E() * self.d_E_d_par() + else: + return np.zeros(len(self.t)) * u.second / par_obj.unit + + def d_delayL2_d_par(self, par): + if par not in self.binary_params: + raise ValueError(f"{par} is not in binary parameter list.") + par_obj = getattr(self, par) + index, par_temp = self.in_piece(par) + if par_temp is None: + if hasattr(self, "d_delayL2_d_" + par): + func = getattr(self, "d_delayL2_d_" + par) + return func() * index + else: + if par in self.orbits_cls.orbit_params: + return self.d_delayL2_d_E() * self.d_E_d_par(par) + else: + return np.zeros(len(self.t)) * u.second / par_obj.unit + else: + if hasattr(self, "d_delayL2_d_" + par_temp): + func = getattr(self, "d_delayL2_d_" + par_temp) + return func() * index + else: + if par in self.orbits_cls.orbit_params: + return self.d_delayL2_d_E() * self.d_E_d_par() + else: + return np.zeros(len(self.t)) * u.second / par_obj.unit + + def in_piece(self, par): + """Finds which TOAs reference which piecewise binary parameter group using the group_index_array property. + ---------- + par : str + Name of piecewise parameter e.g. 'T0X_0001' or 'A1X_0001' + Returns + ------- + list + boolean list (length: self._t). True where TOA references a given group, False otherwise. + binary piecewise parameter label str. e.g. 'T0X' or 'A1X'. + """ + if "_" in par: + text = par.split("_") + param = text[0] + toa_index = f"{int(text[1]):04d}" + else: + param = par + if hasattr(self, "group_index_array"): + # group_index_array should exist before fitting, constructing the model/residuals should add this(?) + group_indexes = np.array(self.group_index_array) + if param == "T0X": + ret = group_indexes == toa_index + return [ret, "T0X"] + elif param == "A1X": + ret = group_indexes == toa_index + return [ret, "A1X"] + # The toa_index = -1 corresponds to TOAs that don't reference any groups + else: + ret = group_indexes == -1 + return [ret, None] + #'None' corresponds to a parameter without a piecewise counterpart, so will effect all TOAs + else: + return [np.zeros(len(self._t)) + 1, None] + + def d_BTdelay_d_par(self, par): + return self.delayR() * (self.d_delayL2_d_par(par) + self.d_delayL1_d_par(par)) + + def d_delayL1_d_A1X(self): + return np.sin(self.omega()) * (np.cos(self.E()) - self.ecc()) / c.c + + def d_delayL2_d_A1X(self): + return ( + np.cos(self.omega()) * np.sqrt(1 - self.ecc() ** 2) * np.sin(self.E()) / c.c + ) + + def d_delayL1_d_T0X(self): + return self.d_delayL1_d_E() * self.d_E_d_T0X() + + def d_delayL2_d_T0X(self): + return self.d_delayL2_d_E() * self.d_E_d_T0X() + + def d_E_d_T0X(self): + """Analytic derivative + d(E-e*sinE)/dT0 = dM/dT0 + dE/dT0(1-cosE*e)-de/dT0*sinE = dM/dT0 + dE/dT0(1-cosE*e)+eDot*sinE = dM/dT0 + """ + RHS = self.prtl_der("M", "T0") + E = self.E() + EDOT = self.EDOT + ecc = self.ecc() + with u.set_enabled_equivalencies(u.dimensionless_angles()): + return (RHS - EDOT * np.sin(E)) / (1.0 - np.cos(E) * ecc) + + def prtl_der(self, y, x): + """Find the partial derivatives in binary model pdy/pdx + Parameters + ---------- + y : str + Name of variable to be differentiated + x : str + Name of variable the derivative respect to + Returns + ------- + np.array + The derivatives pdy/pdx + """ + if y not in self.binary_params + self.inter_vars: + errorMesg = y + " is not in binary parameter and variables list." + raise ValueError(errorMesg) + + if x not in self.inter_vars + self.binary_params: + errorMesg = x + " is not in binary parameters and variables list." + raise ValueError(errorMesg) + # derivative to itself + if x == y: + return np.longdouble(np.ones(len(self.tt0))) * u.Unit("") + # Get the unit right + yAttr = getattr(self, y) + xAttr = getattr(self, x) + U = [None, None] + for i, attr in enumerate([yAttr, xAttr]): + # If attr is a PINT Parameter class type + if hasattr(attr, "units"): + U[i] = attr.units + # If attr is a Quantity type + elif hasattr(attr, "unit"): + U[i] = attr.unit + # If attr is a method + elif hasattr(attr, "__call__"): + U[i] = attr().unit + else: + raise TypeError(type(attr) + "can not get unit") + yU = U[0] + xU = U[1] + # Call derivtive functions + derU = yU / xU + if hasattr(self, "d_" + y + "_d_" + x): + dername = "d_" + y + "_d_" + x + result = getattr(self, dername)() + elif hasattr(self, "d_" + y + "_d_par"): + dername = "d_" + y + "_d_par" + result = getattr(self, dername)(x) + else: + result = np.longdouble(np.zeros(len(self.tt0))) + if hasattr(result, "unit"): + return result.to(derU, equivalencies=u.dimensionless_angles()) + else: + return result * derU + + def d_M_d_par(self, par): + """derivative for M respect to bianry parameter. + Parameters + ---------- + par : string + parameter name + Returns + ------- + Derivitve of M respect to par + """ + if par not in self.binary_params: + errorMesg = par + " is not in binary parameter list." + raise ValueError(errorMesg) + par_obj = getattr(self, par) + result = self.orbits_cls.d_orbits_d_par(par) + with u.set_enabled_equivalencies(u.dimensionless_angles()): + result = result.to(u.Unit("") / par_obj.unit) + return result diff --git a/src/pint/scripts/zima.py b/src/pint/scripts/zima.py index 2f5f370a5..89641ee07 100755 --- a/src/pint/scripts/zima.py +++ b/src/pint/scripts/zima.py @@ -65,6 +65,12 @@ def main(argv=None): default=False, help="Actually add in random noise, or just populate the column", ) + parser.add_argument( + "--addcorrnoise", + action="store_true", + default=False, + help="Add in a correlated noise realization if it's present in the model", + ) parser.add_argument( "--wideband", action="store_true", @@ -127,13 +133,17 @@ def main(argv=None): freq=np.atleast_1d(args.freq) * u.MHz, fuzz=args.fuzzdays * u.d, add_noise=args.addnoise, + add_correlated_noise=args.addcorrnoise, wideband=args.wideband, wideband_dm_error=args.dmerror * pint.dmu, ) else: log.info(f"Reading initial TOAs from {args.inputtim}") ts = pint.simulation.make_fake_toas_fromtim( - args.inputtim, model=m, add_noise=args.addnoise + args.inputtim, + model=m, + add_noise=args.addnoise, + add_correlated_noise=args.addcorrnoise, ) # Write TOAs to a file diff --git a/src/pint/simulation.py b/src/pint/simulation.py index 45b9eb5c8..92a9c71d1 100644 --- a/src/pint/simulation.py +++ b/src/pint/simulation.py @@ -128,7 +128,7 @@ def get_fake_toa_clock_versions(model, include_bipm=False, include_gps=True): } -def make_fake_toas(ts, model, add_noise=False, name="fake"): +def make_fake_toas(ts, model, add_noise=False, add_correlated_noise=False, name="fake"): """Make toas from an array of times Can include alternating frequencies if fed an array of frequencies, @@ -142,6 +142,8 @@ def make_fake_toas(ts, model, add_noise=False, name="fake"): current model add_noise : bool, optional Add noise to the TOAs (otherwise `error` just populates the column) + add_correlated_noise : bool, optional + Add correlated noise to the TOAs if it's present in the timing mode. name : str, optional Name for the TOAs (goes into the flags) @@ -156,6 +158,13 @@ def make_fake_toas(ts, model, add_noise=False, name="fake"): """ tsim = deepcopy(ts) zero_residuals(tsim, model) + + if add_correlated_noise: + U = model.noise_model_designmatrix(tsim) + b = model.noise_model_basis_weight(tsim) + corrn = (U @ (b**0.5 * np.random.normal(size=len(b)))) << u.s + tsim.adjust_TOAs(time.TimeDelta(corrn)) + if add_noise: # this function will include EFAC and EQUAD err = model.scaled_toa_uncertainty(tsim) * np.random.normal(size=len(tsim)) @@ -198,6 +207,7 @@ def make_fake_toas_uniform( obs="GBT", error=1 * u.us, add_noise=False, + add_correlated_noise=False, wideband=False, wideband_dm_error=1e-4 * pint.dmu, name="fake", @@ -229,6 +239,8 @@ def make_fake_toas_uniform( uncertainty to attach to each TOA add_noise : bool, optional Add noise to the TOAs (otherwise `error` just populates the column) + add_correlated_noise : bool, optional + Add correlated noise to the TOAs if it's present in the timing mode. wideband : bool, optional Whether to include wideband DM information with each TOA; default is not to include any wideband DM information. If True, the DM associated @@ -301,7 +313,13 @@ def make_fake_toas_uniform( if wideband: ts = update_fake_dms(model, ts, wideband_dm_error, add_noise) - return make_fake_toas(ts, model=model, add_noise=add_noise, name=name) + return make_fake_toas( + ts, + model=model, + add_noise=add_noise, + add_correlated_noise=add_correlated_noise, + name=name, + ) def make_fake_toas_fromMJDs( @@ -311,6 +329,7 @@ def make_fake_toas_fromMJDs( obs="GBT", error=1 * u.us, add_noise=False, + add_correlated_noise=False, wideband=False, wideband_dm_error=1e-4 * pint.dmu, name="fake", @@ -336,6 +355,8 @@ def make_fake_toas_fromMJDs( uncertainty to attach to each TOA add_noise : bool, optional Add noise to the TOAs (otherwise `error` just populates the column) + add_correlated_noise : bool, optional + Add correlated noise to the TOAs if it's present in the timing mode. wideband : astropy.units.Quantity, optional Whether to include wideband DM values with each TOA; default is not to include any DM information @@ -396,10 +417,18 @@ def make_fake_toas_fromMJDs( if wideband: ts = update_fake_dms(model, ts, wideband_dm_error, add_noise) - return make_fake_toas(ts, model=model, add_noise=add_noise, name=name) + return make_fake_toas( + ts, + model=model, + add_noise=add_noise, + add_correlated_noise=add_correlated_noise, + name=name, + ) -def make_fake_toas_fromtim(timfile, model, add_noise=False, name="fake"): +def make_fake_toas_fromtim( + timfile, model, add_noise=False, add_correlated_noise=False, name="fake" +): """Make fake toas with the same times as an input tim file Can include alternating frequencies if fed an array of frequencies, @@ -413,6 +442,8 @@ def make_fake_toas_fromtim(timfile, model, add_noise=False, name="fake"): current model add_noise : bool, optional Add noise to the TOAs (otherwise `error` just populates the column) + add_correlated_noise : bool, optional + Add correlated noise to the TOAs if it's present in the timing mode. name : str, optional Name for the TOAs (goes into the flags) @@ -432,7 +463,13 @@ def make_fake_toas_fromtim(timfile, model, add_noise=False, name="fake"): dm_errors = input_ts.get_dm_errors() ts = update_fake_dms(model, ts, dm_errors, add_noise) - return make_fake_toas(input_ts, model=model, add_noise=add_noise, name=name) + return make_fake_toas( + input_ts, + model=model, + add_noise=add_noise, + add_correlated_noise=add_correlated_noise, + name=name, + ) def calculate_random_models( diff --git a/src/pint/utils.py b/src/pint/utils.py index c4410618a..9fcdb31dc 100644 --- a/src/pint/utils.py +++ b/src/pint/utils.py @@ -1328,8 +1328,9 @@ def wavex_setup(model, T_span, freqs=None, n_freqs=None): "Both freqs and n_freqs are specified. Only one or the other should be used" ) - if n_freqs <= 0: + if n_freqs is not None and n_freqs <= 0: raise ValueError("Must use a non-zero number of wave frequencies") + model.add_component(WaveX()) if isinstance(T_span, u.quantity.Quantity): T_span.to(u.d) @@ -1356,11 +1357,11 @@ def wavex_setup(model, T_span, freqs=None, n_freqs=None): if n_freqs is not None: if n_freqs == 1: - wave_freq = 2.0 * np.pi / T_span + wave_freq = 1 / T_span model.WXFREQ_0001.quantity = wave_freq else: wave_numbers = np.arange(1, n_freqs + 1) - wave_freqs = 2.0 * np.pi * wave_numbers / T_span + wave_freqs = wave_numbers / T_span model.WXFREQ_0001.quantity = wave_freqs[0] model.components["WaveX"].add_wavex_components(wave_freqs[1:]) return model.components["WaveX"].get_indices() @@ -1408,8 +1409,9 @@ def dmwavex_setup(model, T_span, freqs=None, n_freqs=None): "Both freqs and n_freqs are specified. Only one or the other should be used" ) - if n_freqs <= 0: + if n_freqs is not None and n_freqs <= 0: raise ValueError("Must use a non-zero number of wave frequencies") + model.add_component(DMWaveX()) if isinstance(T_span, u.quantity.Quantity): T_span.to(u.d) @@ -1436,11 +1438,11 @@ def dmwavex_setup(model, T_span, freqs=None, n_freqs=None): if n_freqs is not None: if n_freqs == 1: - wave_freq = 2.0 * np.pi / T_span + wave_freq = 1 / T_span model.DMWXFREQ_0001.quantity = wave_freq else: wave_numbers = np.arange(1, n_freqs + 1) - wave_freqs = 2.0 * np.pi * wave_numbers / T_span + wave_freqs = wave_numbers / T_span model.DMWXFREQ_0001.quantity = wave_freqs[0] model.components["DMWaveX"].add_dmwavex_components(wave_freqs[1:]) return model.components["DMWaveX"].get_indices() diff --git a/tests/datafile/B1855+09_NANOGrav_9yv1.gls.par b/tests/datafile/B1855+09_NANOGrav_9yv1.gls.par index 2138184bd..645cb802a 100644 --- a/tests/datafile/B1855+09_NANOGrav_9yv1.gls.par +++ b/tests/datafile/B1855+09_NANOGrav_9yv1.gls.par @@ -453,7 +453,7 @@ FD3 1.07526915D-04 1 2.50177766D-05 SOLARN0 0.00 EPHEM DE421 ECL IERS2003 -CLK TT(BIPM) +CLK TT(BIPM2019) UNITS TDB TIMEEPH FB90 #T2CMETHOD TEMPO diff --git a/tests/test_BT_piecewise.py b/tests/test_BT_piecewise.py new file mode 100644 index 000000000..daf75143f --- /dev/null +++ b/tests/test_BT_piecewise.py @@ -0,0 +1,695 @@ +from pint.models import get_model +import pint.toa +import numpy as np +import pint.fitter +import astropy.units as u +from pint import ls +from copy import deepcopy +import pint.residuals +from astropy.time import Time +import pint.models.stand_alone_psr_binaries.BT_piecewise as BTpiecewise +import matplotlib.pyplot as plt +import unittest +from io import StringIO +from pylab import * +import pytest +from pint.simulation import make_fake_toas_uniform +import pint.logging + +pint.logging.setup(level="ERROR") + + +@pytest.fixture +def model_no_pieces(scope="session"): + # builds a J1023+0038-like model with no pieces + par_base = """ + PSR 1023+0038 + TRACK -3 + EPHEM DE421 + CLOCK TT(BIPM2019) + START 55000. + FINISH 55200. + DILATEFREQ N + RAJ 10:23:47.68719801 + DECJ 0:38:40.84551000 + POSEPOCH 54995. + F0 592. + F1 -2. + PEPOCH 55000. + PLANET_SHAPIRO N + DM 14. + BINARY BT_piecewise + PB 0.2 + PBDOT 0.0 + A1 0.34333468063634737 1 + A1DOT 0.0 + ECC 0.0 + EDOT 0.0 + T0 55000. + TZRMJD 55000. + TZRSITE 1 + """ + model = get_model(StringIO(par_base)) + # lurking bug: T0X_0000/A1X_0000 and boundaries are not automatically deleted on intialisation + model.remove_range(0) + return model + + +@pytest.fixture +def model_BT(): + # builds a J1023+0038-like model with no pieces + par_base = """ + PSR 1023+0038 + TRACK -3 + EPHEM DE421 + CLOCK TT(BIPM2019) + START 55000. + FINISH 55200. + DILATEFREQ N + RAJ 10:23:47.68719801 + DECJ 0:38:40.84551000 + POSEPOCH 54995. + F0 592. + F1 -2. + PEPOCH 55000. + PLANET_SHAPIRO N + DM 14. + BINARY BT + PB 0.2 + PBDOT 0.0 + A1 0.34333468063634737 1 + A1DOT 0.0 + ECC 0.0 + EDOT 0.0 + T0 55000. + TZRMJD 55000. + TZRSITE 1 + """ + model = get_model(StringIO(par_base)) + return model + + +@pytest.fixture() +def build_piecewise_model_with_one_A1_piece(model_no_pieces): + # takes the basic model frame and adds 2 non-ovelerlapping pieces to it + piecewise_model = deepcopy(model_no_pieces) + lower_bound = [55000] + upper_bound = [55100] + piecewise_model.add_group_range(lower_bound[0], upper_bound[0], piece_index=0) + piecewise_model.add_piecewise_param( + A1=piecewise_model.A1.value + 1.0e-3, piece_index=0 + ) + return piecewise_model + + +@pytest.fixture() +def build_piecewise_model_with_one_T0_piece(model_no_pieces): + # takes the basic model frame and adds 2 non-ovelerlapping pieces to it + piecewise_model = deepcopy(model_no_pieces) + lower_bound = [55000] + upper_bound = [55100] + piecewise_model.add_group_range(lower_bound[0], upper_bound[0], piece_index=0) + piecewise_model.add_piecewise_param( + T0=piecewise_model.T0.value + 1.0e-5, piece_index=0 + ) + return piecewise_model + + +# fine function +@pytest.fixture() +def build_piecewise_model_with_two_pieces(model_no_pieces): + # takes the basic model frame and adds 2 non-ovelerlapping pieces to it + piecewise_model = model_no_pieces + lower_bound = [55000, 55100.000000001] + upper_bound = [55100, 55200] + for i in range(len(lower_bound)): + piecewise_model.add_group_range(lower_bound[i], upper_bound[i], piece_index=i) + piecewise_model.add_piecewise_param( + A1=(piecewise_model.A1.value + (i + 1) * 1e-3) * ls, piece_index=i + ) + piecewise_model.add_piecewise_param( + T0=(piecewise_model.T0.value + (i + 1) * 1e-3) * u.d, piece_index=i + ) + return piecewise_model + + +# fine function +@pytest.fixture() +def make_toas_to_go_with_two_piece_model(build_piecewise_model_with_two_pieces): + # makes toas to go with the two non-overlapping, complete coverage model + m_piecewise = build_piecewise_model_with_two_pieces + lower_bound = [55000, 55100.00001] + upper_bound = [55100, 55200] + toas = make_fake_toas_uniform( + lower_bound[0] + 1, upper_bound[1] - 1, 20, m_piecewise + ) # slightly within group edges to make toas unambiguously contained within groups + return toas + + +# fine function +def add_full_coverage_and_non_overlapping_groups_and_make_toas( + model_no_pieces, build_piecewise_model_with_two_pieces +): + # function to build the models for specific edge cases i.e. distinct groups where all toas fit exactly within a group + model = build_piecewise_model_with_two_pieces + toas = make_generic_toas(model, 55001, 55199) + return model, toas + + +# fine function +def add_partial_coverage_groups_and_make_toas(build_piecewise_model_with_two_pieces): + # function to build the models for specific edge cases i.e. if all toas don't fit exactly within any groups + model3 = build_piecewise_model_with_two_pieces + # known bug: if A1X exists it needs a partner T0X otherwise it breaks can freeze T0X for the time being, just needs a little thought + model3.remove_range(0) + # make sure TOAs are within ranges + toas = make_generic_toas(model3, 55001, 55199) + return model3, toas + + +# fine function +def make_generic_toas(model, lower_bound, upper_bound): + # makes toas to go with the edge cases + return make_fake_toas_uniform(lower_bound, upper_bound, 20, model) + + +def add_offset_in_model_parameter(indexes, param, model): + m_piecewise_temp = deepcopy(model) + parameter_string = f"{param}_{int(indexes):04d}" + if hasattr(m_piecewise_temp, parameter_string): + delta = getattr(m_piecewise_temp, parameter_string).value + 1e-5 + getattr(m_piecewise_temp, parameter_string).value = delta + m_piecewise_temp.setup() + else: + parameter_string = param[0:2] + getattr(m_piecewise_temp, parameter_string).value = ( + getattr(m_piecewise_temp, parameter_string).value + 1e-5 + ) + m_piecewise_temp.setup() + return m_piecewise_temp + + +def add_relative_offset_for_derivatives(index, param, model, offset_size, plus=True): + m_piecewise_temp = deepcopy(model) + parameter_string = f"{param}_{int(index):04d}" + offset_size = offset_size.value + if plus is True: + if hasattr(m_piecewise_temp, parameter_string): + delta = getattr(m_piecewise_temp, parameter_string).value + offset_size + getattr(m_piecewise_temp, parameter_string).value = delta + else: + if hasattr(m_piecewise_temp, parameter_string): + delta = getattr(m_piecewise_temp, parameter_string).value - offset_size + getattr(m_piecewise_temp, parameter_string).value = delta + return m_piecewise_temp + + +# fine function +def test_round_trips_to_parfile(model_no_pieces): + # test: see if the model can be reproduced after piecewise parameters have been added, + # checks by comparing parameter keys in both the old and new file. Should have the number of matches = number of parameters + m_piecewise = model_no_pieces + n = 10 + lower_bounds = [ + 55050, + 55101, + 55151, + 55201, + 55251, + 55301, + 55351, + 55401, + 55451, + 55501, + ] + upper_bounds = [ + 55100, + 55150, + 55200, + 55250, + 55300, + 55350, + 55400, + 55450, + 55500, + 55550, + ] + for i in range(0, n): + m_piecewise.add_group_range(lower_bounds[i], upper_bounds[i], piece_index=i) + m_piecewise.add_piecewise_param( + A1=(m_piecewise.A1.value + i) * ls, piece_index=i + ) + m_piecewise.add_piecewise_param( + T0=(m_piecewise.T0.value + i) * u.d, piece_index=i + ) + m3 = get_model(StringIO(m_piecewise.as_parfile())) + param_dict = m_piecewise.get_params_dict(which="all") + copy_param_dict = m3.get_params_dict(which="all") + number_of_keys = 0 + n_keys_identified = 0 + n_values_preserved = 0 + comparison = 0 + for key, value in param_dict.items(): + number_of_keys = number_of_keys + 1 # iterates up to total number of keys + for copy_key, copy_value in copy_param_dict.items(): + if key == copy_key: # search both pars for identical keys + n_keys_identified = n_keys_identified + 1 + if type(value) == type(copy_value): + if value.value == copy_value.value: + n_values_preserved = n_values_preserved + 1 + assert n_keys_identified == number_of_keys + assert n_values_preserved == number_of_keys + + +# fine function +def test_get_number_of_groups(build_piecewise_model_with_two_pieces): + # test to make sure number of groups matches with number of added piecewise parameters + m_piecewise = build_piecewise_model_with_two_pieces + number_of_groups = m_piecewise.get_number_of_groups() + assert number_of_groups == 2 + + +# fine function +def test_group_assignment_toas_unambiguously_within_group( + build_piecewise_model_with_two_pieces, make_toas_to_go_with_two_piece_model +): + # test to see if the group, for one toa per group, that the BT_piecewise.print_toas_in_group functions as intended. + # operates by sorting the toas by MJD compared against a groups upper/lower edge. + # operates with np.searchsorted so for 1 toa per group, each toa should be uniquely indexed after/before the lower/upper edge + model = build_piecewise_model_with_two_pieces + index = model.which_group_is_toa_in(make_toas_to_go_with_two_piece_model) + should_be_ten_toas_in_each_group = [ + np.unique(index, return_counts=True)[1][0], + np.unique(index, return_counts=True)[1][1], + ] + expected_toas_in_each_group = [10, 10] + is_there_ten_toas_per_group = np.testing.assert_array_equal( + should_be_ten_toas_in_each_group, expected_toas_in_each_group + ) + np.testing.assert_array_equal( + should_be_ten_toas_in_each_group, expected_toas_in_each_group + ) + + +# fine function +@pytest.mark.parametrize("param", ["A1X", "T0X"]) +def test_paramX_per_toa_matches_corresponding_model_value( + param, build_piecewise_model_with_two_pieces, make_toas_to_go_with_two_piece_model +): + # Testing the correct piecewise parameters are being assigned to each toa. + # Operates on the piecewise_parameter_from_information_array function. Requires group_index fn to be run so we have an array of length(ntoas), filled with information on which group a toa belongs to. + # Uses this array to apply T0X_i/A1X_i to corresponding indexes from group_index fn call. i.e. for T0X_i,T0X_j,T0X_k values and group_index return: [i,j,k] the output would be [T0X_i,T0X_j,T0X_k] + m_piecewise = build_piecewise_model_with_two_pieces + toa = make_toas_to_go_with_two_piece_model + expected_piece_1 = np.full(int(len(toa)), True) + expected_piece_1[int(len(toa) / 2) :] = False + + expected_piece_2 = np.full(int(len(toa)), True) + expected_piece_2[: int(len(toa) / 2)] = False + + should_toa_reference_piecewise_parameter = [expected_piece_1, expected_piece_2] + if param == "A1X": + paramX_per_toa = m_piecewise.paramx_per_toa("A1", toa) + test_val = [m_piecewise.A1X_0000.value, m_piecewise.A1X_0001.value] + + elif param == "T0X": + paramX_per_toa = m_piecewise.paramx_per_toa("T0", toa) + test_val = [m_piecewise.T0X_0000.value, m_piecewise.T0X_0001.value] + + do_toas_reference_first_piecewise_parameter = np.isclose( + (paramX_per_toa.value - test_val[0]), 0, atol=1e-6, rtol=0 + ) + + do_toas_reference_second_piecewise_parameter = np.isclose( + (paramX_per_toa.value - test_val[1]), 0, atol=1e-6, rtol=0 + ) + + do_toas_reference_piecewise_parameter = [ + do_toas_reference_first_piecewise_parameter, + do_toas_reference_second_piecewise_parameter, + ] + + np.testing.assert_array_equal( + do_toas_reference_piecewise_parameter, should_toa_reference_piecewise_parameter + ) + + +# fine function +def test_problematic_group_indexes_and_ranges(model_no_pieces): + # Test to flag issues with problematic group indexes + # Could fold this with the next test for a mega-check exceptions are raised test + m_piecewise = model_no_pieces + with pytest.raises(ValueError): + m_piecewise.add_group_range( + m_piecewise.START.value, m_piecewise.FINISH.value, piece_index=-1 + ) + with pytest.raises(ValueError): + m_piecewise.add_group_range( + m_piecewise.FINISH.value, m_piecewise.START.value, piece_index=1 + ) + with pytest.raises(ValueError): + m_piecewise.add_group_range( + m_piecewise.START.value, m_piecewise.FINISH.value, piece_index=1 + ) + m_piecewise.add_group_range( + m_piecewise.START.value, m_piecewise.FINISH.value, piece_index=1 + ) + with pytest.raises(ValueError): + m_piecewise.add_group_range( + m_piecewise.START.value, m_piecewise.FINISH.value, piece_index=10000 + ) + + +def test_group_index_matching(model_no_pieces): + m_piecewise = model_no_pieces + with pytest.raises(ValueError): + # should flag mismatching A1 group and boundary indexes + m_piecewise.add_group_range( + m_piecewise.START.value, m_piecewise.FINISH.value, piece_index=1 + ) + m_piecewise.add_piecewise_param(A1=m_piecewise.A1.value * ls, piece_index=2) + # Errors raised in validate, which is run when groups are "locked in" + m_piecewise.setup() + m_piecewise.validate() + with pytest.raises(ValueError): + # should flag mismatching T0 group and boundary indexes + m_piecewise.add_group_range( + m_piecewise.START.value, m_piecewise.FINISH.value, piece_index=1 + ) + m_piecewise.add_piecewise_param(T0=m_piecewise.T0.value * u.d, piece_index=2) + # Errors raised in validate, which is run when groups are "locked in" + m_piecewise.setup() + m_piecewise.validate() + with pytest.raises(ValueError): + # check whether boundaries are overlapping + m_piecewise.add_group_range(55000, 55200, piece_index=1) + m_piecewise.add_piecewise_param(A1=m_piecewise.A1.value * ls, piece_index=1) + m_piecewise.add_piecewise_param(T0=m_piecewise.T0.value * u.d, piece_index=1) + + m_piecewise.add_group_range(55100, 55300, piece_index=2) + m_piecewise.add_piecewise_param(A1=m_piecewise.A1.value * ls, piece_index=2) + m_piecewise.add_piecewise_param(T0=m_piecewise.T0.value * u.d, piece_index=2) + + m_piecewise.setup() + m_piecewise.validate() + with pytest.raises(ValueError): + # check whether boundaries are equal + m_piecewise.add_group_range(55000, 55000, piece_index=1) + m_piecewise.add_piecewise_param(A1=m_piecewise.A1.value * u.d, piece_index=1) + m_piecewise.add_piecewise_param(T0=m_piecewise.T0.value * u.d, piece_index=1) + m_piecewise.setup() + m_piecewise.validate() + + +@pytest.mark.parametrize( + "param, index", [("T0X", 0), ("T0X", 1), ("A1X", 0), ("A1X", 1)] +) +def test_residuals_in_groups_respond_to_changes_in_corresponding_piecewise_parameter( + model_no_pieces, build_piecewise_model_with_two_pieces, param, index +): + m_piecewise, toa = add_full_coverage_and_non_overlapping_groups_and_make_toas( + model_no_pieces, build_piecewise_model_with_two_pieces + ) + rs_value = pint.residuals.Residuals( + toa, m_piecewise, subtract_mean=False + ).resids_value + param_string = f"{param}_{int(index):04d}" + m_piecewise_temp = add_offset_in_model_parameter(index, param, m_piecewise) + if param == "A1X": + paramX_per_toa = m_piecewise.paramx_per_toa("A1", toa) + if param == "T0X": + paramX_per_toa = m_piecewise.paramx_per_toa("T0", toa) + + test_val = [getattr(m_piecewise, param_string).value] + + rs_temp = pint.residuals.Residuals( + toa, m_piecewise_temp, subtract_mean=False + ).resids_value + have_residuals_changed = rs_temp != rs_value + + are_toas_referencing_paramX = np.isclose( + (paramX_per_toa.value - test_val[0]), 0, atol=1e-6, rtol=0 + ) + + should_residuals_change = are_toas_referencing_paramX + + np.testing.assert_array_equal(have_residuals_changed, should_residuals_change) + + +@pytest.mark.parametrize( + "param, index", [("T0X", 0), ("T0X", 1), ("A1X", 0), ("A1X", 1)] +) +def test_d_delay_in_groups_respond_to_changes_in_corresponding_piecewise_parameter( + param, + index, + model_no_pieces, + build_piecewise_model_with_two_pieces, +): + m_piecewise, toa = add_full_coverage_and_non_overlapping_groups_and_make_toas( + model_no_pieces, build_piecewise_model_with_two_pieces + ) + # m_piecewise_temp = add_offset_in_model_parameter(index, param, m_piecewise) + + param_string = f"{param}_{int(index):04d}" + m_piecewise_temp = add_offset_in_model_parameter(index, param_string, m_piecewise) + if param == "A1X": + paramX_per_toa = m_piecewise_temp.paramx_per_toa("A1", toa) + + if param == "T0X": + paramX_per_toa = m_piecewise_temp.paramx_per_toa("T0", toa) + test_val = [getattr(m_piecewise, param_string).value] + are_toas_referencing_paramX = np.isclose( + (paramX_per_toa.value - test_val[0]), 0, atol=1e-6, rtol=0 + ) + + is_d_delay_changing = np.invert( + np.isclose( + m_piecewise_temp.d_binary_delay_d_xxxx(toa, param_string, None).value, + 0, + atol=1e-11, + rtol=0, + ) + ) + should_d_delay_be_changing = are_toas_referencing_paramX + # assert toas that are in the group have some non-zero delay derivative + np.testing.assert_array_equal(is_d_delay_changing, should_d_delay_be_changing) + + +@pytest.mark.parametrize("param, index", [("T0X", 0), ("A1X", 0)]) +def test_derivatives_in_pieces_are_same_as_BT_piecewise_paramx( + param, + index, + model_no_pieces, + model_BT, + build_piecewise_model_with_one_T0_piece, + build_piecewise_model_with_one_A1_piece, +): + if param == "A1X": + m_piecewise = build_piecewise_model_with_one_A1_piece + elif param == "T0X": + m_piecewise = build_piecewise_model_with_one_T0_piece + + m_non_piecewise = model_BT + toas = make_generic_toas(m_non_piecewise, 55001, 55199) + + param_string = f"{param}_{int(index):04d}" + param_q = getattr(m_non_piecewise, param[0:2]) + setattr(param_q, "value", getattr(m_piecewise, param_string).value) + + piecewise_delays = m_piecewise.d_binary_delay_d_xxxx( + toas, param_string, acc_delay=None + ) + non_piecewise_delays = m_non_piecewise.d_binary_delay_d_xxxx( + toas, param[0:2], acc_delay=None + ) + # gets which toas that should be changing + if param == "A1X": + paramX_per_toa = m_piecewise.paramx_per_toa("A1", toas) + + if param == "T0X": + paramX_per_toa = m_piecewise.paramx_per_toa("T0", toas) + test_val = [getattr(m_piecewise, param_string).value] + are_toas_referencing_paramX = np.isclose( + (paramX_per_toa.value - test_val[0]), 0, atol=1e-6, rtol=0 + ) + where_delays_should_change = are_toas_referencing_paramX + # checks the derivatives wrt T0X is the same as the derivative calc'd in the BT model for T0=T0X, for TOAs within that group + np.testing.assert_array_equal( + piecewise_delays[where_delays_should_change], + non_piecewise_delays[where_delays_should_change], + ) + # checks the derivatives wrt T0X are 0 for toas outside of the group + np.testing.assert_array_equal( + piecewise_delays[~where_delays_should_change], + np.zeros(len(piecewise_delays[~where_delays_should_change])), + ) + + +# This test is a bit of a mess, attempting to manipulate multiple models without breaking anything (i.e. model_1 and model_2 should not be affected by changes made to the other) +def test_interacting_with_multiple_models(model_no_pieces): + m_piecewise_1 = deepcopy(model_no_pieces) + m_piecewise_2 = deepcopy(model_no_pieces) + lower_bound = [55000, 55100.00001] + upper_bound = [55100, 55200] + # just check by creating the models and adding pieces we aren't adding things to the other model + m_piecewise_1.add_group_range(lower_bound[0], upper_bound[0], piece_index=0) + m_piecewise_1.add_piecewise_param(T0=m_piecewise_1.T0.value + 1.0e-3, piece_index=0) + m_piecewise_1.add_piecewise_param(A1=m_piecewise_1.A1.value + 1.0e-3, piece_index=0) + m_piecewise_1.setup() + m_piecewise_1.validate() + m_piecewise_2.add_group_range(lower_bound[1], upper_bound[1], piece_index=0) + m_piecewise_2.add_piecewise_param(T0=m_piecewise_2.T0.value + 3.0e-3, piece_index=0) + m_piecewise_2.add_piecewise_param(A1=m_piecewise_2.A1.value + 3.0e-3, piece_index=0) + m_piecewise_2.setup() + m_piecewise_2.validate() + # not yet interlacing function calls, just some extra sanity checks when it comes to loading more than one model that are yet untested + np.testing.assert_allclose(m_piecewise_1.XR1_0000.value, lower_bound[0]) + np.testing.assert_allclose(m_piecewise_1.XR2_0000.value, upper_bound[0]) + np.testing.assert_allclose(m_piecewise_2.XR1_0000.value, lower_bound[1]) + np.testing.assert_allclose(m_piecewise_2.XR2_0000.value, upper_bound[1]) + + np.testing.assert_allclose( + m_piecewise_1.T0X_0000.value, m_piecewise_1.T0.value + 1.0e-3 + ) + np.testing.assert_allclose( + m_piecewise_1.A1X_0000.value, m_piecewise_1.A1.value + 1.0e-3 + ) + np.testing.assert_allclose( + m_piecewise_2.T0X_0000.value, m_piecewise_2.T0.value + 3.0e-3 + ) + np.testing.assert_allclose( + m_piecewise_2.A1X_0000.value, m_piecewise_2.A1.value + 3.0e-3 + ) + + # just some arithmetic tests to see if they respond to changes for now. + # Need to find a way of listing which parameters are updated during common function calls. + # e.g. creating residuals, why do things like tt0 change to len(1) during the calculation? + # This is just designed to try and confuse the reader (its following a set of stable calculations and checking they match at intervals) + param_string_T0X = "T0X_0000" + param_string_A1X = "A1X_0000" + param_m1_T0 = getattr(m_piecewise_1, param_string_T0X) + param_m1_A1 = getattr(m_piecewise_1, param_string_A1X) + param_m2_T0 = getattr(m_piecewise_2, param_string_T0X) + param_m2_A1 = getattr(m_piecewise_2, param_string_A1X) + + setattr(param_m1_T0, "value", getattr(m_piecewise_2, param_string_T0X).value) + setattr(param_m1_A1, "value", getattr(m_piecewise_2, param_string_A1X).value) + setattr(param_m2_T0, "value", getattr(m_piecewise_2, "T0").value) + setattr(param_m2_A1, "value", getattr(m_piecewise_2, "A1").value) + + np.testing.assert_allclose( + m_piecewise_1.T0X_0000.value, m_piecewise_1.T0.value + 3.0e-3 + ) + np.testing.assert_allclose( + m_piecewise_1.A1X_0000.value, m_piecewise_1.A1.value + 3.0e-3 + ) + np.testing.assert_allclose(m_piecewise_2.T0X_0000.value, m_piecewise_2.T0.value) + np.testing.assert_allclose(m_piecewise_2.A1X_0000.value, m_piecewise_2.A1.value) + + setattr( + param_m1_T0, "value", getattr(m_piecewise_2, param_string_T0X).value + 6.0e-3 + ) + setattr( + param_m1_A1, "value", getattr(m_piecewise_2, param_string_A1X).value + 6.0e-3 + ) + setattr(param_m2_T0, "value", getattr(m_piecewise_2, "T0").value + 3.0e-3) + setattr(param_m2_A1, "value", getattr(m_piecewise_2, "A1").value + 3.0e-3) + + np.testing.assert_allclose( + m_piecewise_1.T0X_0000.value, m_piecewise_1.T0.value + 6.0e-3 + ) + np.testing.assert_allclose( + m_piecewise_1.A1X_0000.value, m_piecewise_1.A1.value + 6.0e-3 + ) + np.testing.assert_allclose( + m_piecewise_2.T0X_0000.value, m_piecewise_2.T0.value + 3.0e-3 + ) + np.testing.assert_allclose( + m_piecewise_2.A1X_0000.value, m_piecewise_2.A1.value + 3.0e-3 + ) + + # can add more suggested tests in here + + +# --Place here for future tests-- +# Wants to check the residuals within the group are the same as those from the model used to generate them which has T0 = T0X_0000 (the only group) +# In the residual calculation there is a mean subtraction/round off occurring in changing the binary parameter/something else. +# This means: test_residuals_in_pieces_are_same_as_BT_piecewise_*, would not have exactly equal residuals. +# In fact the TOAS that are expected to replicate the BT_model residuals are systematically delayed by an amount that is larger than the noise of uniform TOAs. +# Looks like the "noise" about this extra delay matches the noise of the uniform TOAs generated by the non-piecewise model +# Suggests: Don't leave TOAs in undeclared groups, try to cover the whole date range so a TOA lies in a group until explored further + + +# --WIP Tests-- +# This is a wip test to evaluate the residuals using TOAs generated from a non-piecewise model using the BT and BT piecewise model +# The test should pass if the residuals within a piece match those residuals produced by a BT model with the same parameter value as declared within the piece +# i.e. Use BT model to create TOAs with flat residuals -> adjust BT model parameter to match the param value declared within a piece of the piecewise model -> get the residuals of the piecewise and BT model for TOAs that exist within the piece, they should match. +# *Should* work but seems to be unable to produce fake TOAs when run through CI tests +# @pytest.mark.parametrize("param, index", [("T0X", 0), ("A1X", 0)]) +# def test_residuals_in_pieces_are_same_as_BT_piecewise_paramx( +# param, +# index, +# model_no_pieces, +# model_BT, +# build_piecewise_model_with_one_T0_piece, +# build_piecewise_model_with_one_A1_piece, +# ): +# if param == "A1X": +# m_piecewise = build_piecewise_model_with_one_A1_piece +# elif param == "T0X": +# m_piecewise = build_piecewise_model_with_one_T0_piece +# m_non_piecewise = model_BT + +# param_string = f"{param}_{int(index):04d}" +# param_q = getattr(m_non_piecewise, param[0:2]) +# setattr(param_q, "value", getattr(m_piecewise, param_string).value) +# toas = make_generic_toas(m_non_piecewise, 55001, 55099) +# rs_piecewise = pint.residuals.Residuals( +# toas, m_piecewise, subtract_mean=True, use_weighted_mean=False +# ).time_resids +# rs_non_piecewise = pint.residuals.Residuals( +# toas, m_non_piecewise, subtract_mean=True, use_weighted_mean=False +# ).time_resids +# np.testing.assert_allclose(rs_piecewise, rs_non_piecewise) +# +# +# This is a wip test to evaluate the TOA group allocation in the absence of "full-group coverage" (i.e. includes data that exists outside of pieces). +# i.e. Use (either BT/piecewise) model to create TOAs with flat residuals -> check the parameter value the TOAs reference during delay calculations (this should equal the global parameter value when there is no piecewise parameter to reference) +# *Should* work but seems to be unable to produce fake TOAs when run through CI tests +# @pytest.mark.parametrize("param", ["A1X", "T0X"]) +# def test_does_toa_lie_in_group_incomplete_group_coverage( +# param, model_no_pieces, build_piecewise_model_with_two_pieces +# ): +# m_piecewise, toa = add_partial_coverage_groups_and_make_toas(model_no_pieces) +# +# expected_out_piece = np.full(int(len(toa)), True) +# expected_out_piece[int(len(toa) / 2) :] = False +# +# expected_in_piece = np.full(int(len(toa)), True) +# expected_in_piece[: int(len(toa) / 2)] = False +# +# should_toa_reference_piecewise_parameter = [expected_in_piece, expected_out_piece] +# if param == "A1X": +# paramX_per_toa = m_piecewise.paramx_per_toa("A1", toa) +# test_val = [m_piecewise.A1.value, m_piecewise.A1X_0001.value] +# +# elif param == "T0X": +# paramX_per_toa = m_piecewise.paramx_per_toa("T0", toa) +# test_val = [m_piecewise.T0.value, m_piecewise.T0X_0001.value] +# +# are_toas_referencing_global_paramX = np.isclose( +# (paramX_per_toa.value - test_val[0]), 0, atol=1e-6, rtol=0 +# ) +# +# are_toas_referencing_piecewise_paramX = np.isclose( +# (paramX_per_toa.value - test_val[1]), 0, atol=1e-6, rtol=0 +# ) +# +# do_toas_reference_piecewise_parameter = [ +# are_toas_referencing_piecewise_paramX, +# are_toas_referencing_global_paramX, +# ] +# +# np.testing.assert_array_equal( +# do_toas_reference_piecewise_parameter, should_toa_reference_piecewise_parameter +# ) diff --git a/tests/test_zima.py b/tests/test_zima.py index d05664669..bafbb3206 100644 --- a/tests/test_zima.py +++ b/tests/test_zima.py @@ -8,8 +8,10 @@ import matplotlib import pint.scripts.zima as zima -from pint.models import get_model_and_toas +from pint.models import get_model_and_toas, get_model +from pint.simulation import make_fake_toas_uniform from pint.residuals import Residuals +from pint.fitter import DownhillGLSFitter @pytest.mark.parametrize("addnoise", ["", "--addnoise"]) @@ -92,3 +94,41 @@ def test_zima_fuzzdays(tmp_path): lines = sys.stdout.getvalue() finally: sys.stdout = saved_stdout + + +def test_simulate_corrnoise(tmp_path): + parfile = datadir / "B1855+09_NANOGrav_9yv1.gls.par" + + m = get_model(parfile) + + # Simulated TOAs won't have the correct flags for some of these to work. + m.remove_component("ScaleToaError") + m.remove_component("EcorrNoise") + m.remove_component("DispersionDMX") + m.remove_component("PhaseJump") + m.remove_component("FD") + m.PLANET_SHAPIRO.value = False + + t = make_fake_toas_uniform( + m.START.value, + m.FINISH.value, + 1000, + m, + add_noise=True, + add_correlated_noise=True, + ) + + # Check if the created TOAs can be whitened using + # the original timing model. This won't work if the + # noise is not realized correctly. + ftr = DownhillGLSFitter(t, m) + ftr.fit_toas() + rc = sum(ftr.resids.noise_resids.values()) + r = ftr.resids.time_resids + rw = r - rc + sigma = ftr.resids.get_data_error() + + # This should be independent and standard-normal distributed. + x = (rw / sigma).to_value("") + assert np.isclose(np.std(x), 1, atol=0.2) + assert np.isclose(np.mean(x), 0, atol=0.01) diff --git a/versioneer.py b/versioneer.py index 2b5454051..de97d9042 100644 --- a/versioneer.py +++ b/versioneer.py @@ -1,4 +1,4 @@ -# Version: 0.18 +# Version: 0.29 """The Versioneer - like a rocketeer, but for versions. @@ -6,18 +6,14 @@ ============== * like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer +* https://github.com/python-versioneer/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 +* License: Public Domain (Unlicense) +* Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3 +* [![Latest Version][pypi-image]][pypi-url] +* [![Build Status][travis-image]][travis-url] + +This is a tool for managing a recorded version number in setuptools-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 @@ -26,9 +22,38 @@ ## 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 +Versioneer provides two installation modes. The "classic" vendored mode installs +a copy of versioneer into your repository. The experimental build-time dependency mode +is intended to allow you to skip this step and simplify the process of upgrading. + +### Vendored mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) + * Note that you will need to add `tomli; python_version < "3.11"` to your + build-time dependencies if you use `pyproject.toml` +* run `versioneer install --vendor` in your source tree, commit the results +* verify version information with `python setup.py version` + +### Build-time dependency mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) +* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) + to the `requires` key of the `build-system` table in `pyproject.toml`: + ```toml + [build-system] + requires = ["setuptools", "versioneer[toml]"] + build-backend = "setuptools.build_meta" + ``` +* run `versioneer install --no-vendor` in your source tree, commit the results +* verify version information with `python setup.py version` ## Version Identifiers @@ -60,7 +85,7 @@ 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. +uncommitted changes). The version identifier is used for multiple purposes: @@ -165,7 +190,7 @@ 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). +[issues page](https://github.com/python-versioneer/python-versioneer/issues). ### Subprojects @@ -179,7 +204,7 @@ `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. + provide bindings to Python (and perhaps other languages) 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 @@ -193,9 +218,9 @@ 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 +[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the +[PR #61](https://github.com/python-versioneer/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 @@ -223,31 +248,20 @@ 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 +[Bug #83](https://github.com/python-versioneer/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 +* edit `setup.cfg` and `pyproject.toml`, if necessary, + to include any new configuration settings indicated by the release notes. + See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install --[no-]vendor` in your source tree, to replace `SRC/_version.py` * commit any changed files @@ -264,36 +278,70 @@ direction and include code from all supported VCS systems, reducing the number of intermediate scripts. +## Similar projects + +* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time + dependency +* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of + versioneer +* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools + plugin ## 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/ . +Specifically, both are released under the "Unlicense", as described in +https://unlicense.org/. -""" +[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg +[pypi-url]: https://pypi.python.org/pypi/versioneer/ +[travis-image]: +https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg +[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer -from __future__ import print_function +""" +# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring +# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements +# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error +# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with +# pylint:disable=attribute-defined-outside-init,too-many-arguments -try: - import configparser -except ImportError: - import ConfigParser as configparser +import configparser import errno import json import os import re import subprocess import sys +from pathlib import Path +from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union +from typing import NoReturn +import functools + +have_tomllib = True +if sys.version_info >= (3, 11): + import tomllib +else: + try: + import tomli as tomllib + except ImportError: + have_tomllib = False class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + versionfile_source: str + versionfile_build: Optional[str] + parentdir_prefix: Optional[str] + verbose: Optional[bool] + -def get_root(): +def get_root() -> str: """Get the project root directory. We require that all commands are run from the project root, i.e. the @@ -301,13 +349,23 @@ def get_root(): """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") + pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + if not ( + os.path.exists(setup_py) + or os.path.exists(pyproject_toml) + 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") + pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + if not ( + os.path.exists(setup_py) + or os.path.exists(pyproject_toml) + or os.path.exists(versioneer_py) + ): err = ( "Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " @@ -323,46 +381,64 @@ def get_root(): # 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]) + my_path = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: + if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): print( "Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py) + % (os.path.dirname(my_path), versioneer_py) ) except NameError: pass return root -def get_config_from_root(root): +def get_config_from_root(root: str) -> VersioneerConfig: """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or + # This might raise OSError (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 + root_pth = Path(root) + pyproject_toml = root_pth / "pyproject.toml" + setup_cfg = root_pth / "setup.cfg" + section: Union[Dict[str, Any], configparser.SectionProxy, None] = None + if pyproject_toml.exists() and have_tomllib: + try: + with open(pyproject_toml, "rb") as fobj: + pp = tomllib.load(fobj) + section = pp["tool"]["versioneer"] + except (tomllib.TOMLDecodeError, KeyError) as e: + print(f"Failed to load config from {pyproject_toml}: {e}") + print("Try to load it from setup.cfg") + if not section: + parser = configparser.ConfigParser() + with open(setup_cfg) as cfg_file: + parser.read_file(cfg_file) + parser.get("versioneer", "VCS") # raise error if missing + + section = parser["versioneer"] + + # `cast`` really shouldn't be used, but its simplest for the + # common VersioneerConfig users at the moment. We verify against + # `None` values elsewhere where it matters 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.VCS = section["VCS"] + cfg.style = section.get("style", "") + cfg.versionfile_source = cast(str, section.get("versionfile_source")) + cfg.versionfile_build = section.get("versionfile_build") + cfg.tag_prefix = cast(str, section.get("tag_prefix")) + if cfg.tag_prefix in ("''", '""', None): cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") + cfg.parentdir_prefix = section.get("parentdir_prefix") + if isinstance(section, configparser.SectionProxy): + # Make sure configparser translates to bool + cfg.verbose = section.getboolean("verbose") + else: + cfg.verbose = section.get("verbose") + return cfg @@ -371,41 +447,54 @@ class NotThisMethod(Exception): # these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f + HANDLERS.setdefault(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: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, + process = subprocess.Popen( + [command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, ) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -416,28 +505,27 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= if verbose: print("unable to find command, tried %s" % (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode LONG_VERSION_PY[ "git" -] = ''' +] = r''' # 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) +# This file is released into the public domain. +# Generated by versioneer-0.29 +# https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" @@ -446,9 +534,11 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= import re import subprocess import sys +from typing import Any, Callable, Dict, List, Optional, Tuple +import functools -def get_keywords(): +def get_keywords() -> Dict[str, str]: """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 @@ -464,8 +554,15 @@ def get_keywords(): class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + parentdir_prefix: str + versionfile_source: str + verbose: bool + -def get_config(): +def get_config() -> VersioneerConfig: """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py @@ -483,13 +580,13 @@ class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" -LONG_VERSION_PY = {} -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} @@ -498,22 +595,35 @@ def decorate(f): return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -524,18 +634,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -544,15 +656,14 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% @@ -561,41 +672,48 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """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 = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -608,11 +726,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d @@ -621,7 +739,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: @@ -630,6 +748,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue if verbose: print("picking %%s" %% r) return {"version": r, @@ -645,7 +768,12 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, + root: str, + verbose: bool, + runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -656,8 +784,15 @@ 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) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) @@ -665,24 +800,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -699,7 +867,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces @@ -724,26 +892,27 @@ 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) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() + date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -768,23 +937,71 @@ def render_pep440(pieces): return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%%d" %% (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] + rendered = "0.post0.dev%%d" %% pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -811,12 +1028,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -833,7 +1079,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -853,7 +1099,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -873,7 +1119,7 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", @@ -887,10 +1133,14 @@ def render(pieces, style): if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -905,7 +1155,7 @@ def render(pieces, style): "date": pieces.get("date")} -def get_versions(): +def get_versions() -> Dict[str, Any]: """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 @@ -926,7 +1176,7 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, @@ -953,41 +1203,48 @@ def get_versions(): @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """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 = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -1000,11 +1257,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -1013,7 +1270,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = {r for r in refs if re.search(r"\d", r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -1022,6 +1279,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix) :] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r"\d", r): + continue if verbose: print("picking %s" % r) return { @@ -1044,7 +1306,9 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -1055,7 +1319,14 @@ 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) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -1063,7 +1334,7 @@ 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( + describe_out, rc = runner( GITS, [ "describe", @@ -1072,7 +1343,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): "--always", "--long", "--match", - "%s*" % tag_prefix, + f"{tag_prefix}[[:digit:]]*", ], cwd=root, ) @@ -1080,16 +1351,48 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -1106,7 +1409,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces @@ -1132,19 +1435,20 @@ 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) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def do_vcs_install(manifest_in, versionfile_source, ipy): +def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None: """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py @@ -1153,36 +1457,40 @@ def do_vcs_install(manifest_in, versionfile_source, ipy): GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] + files = [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) + if "VERSIONEER_PEP518" not in globals(): + try: + my_path = __file__ + if my_path.endswith((".pyc", ".pyo")): + my_path = os.path.splitext(my_path)[0] + ".py" + versioneer_file = os.path.relpath(my_path) + 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: + with open(".gitattributes", "r") as fobj: + for line in fobj: + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + break + except OSError: pass if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() + with open(".gitattributes", "a+") as fobj: + fobj.write(f"{versionfile_source} export-subst\n") files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -1191,7 +1499,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return { @@ -1201,9 +1509,8 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): "error": None, "date": None, } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: print( @@ -1214,7 +1521,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.18) from +# This file was generated by 'versioneer.py' (0.29) 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. @@ -1231,12 +1538,12 @@ def get_versions(): """ -def versions_from_file(filename): +def versions_from_file(filename: str) -> Dict[str, Any]: """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() - except EnvironmentError: + except OSError: raise NotThisMethod("unable to read _version.py") mo = re.search( r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S @@ -1250,9 +1557,8 @@ def versions_from_file(filename): return json.loads(mo.group(1)) -def write_to_version_file(filename, versions): +def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: """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) @@ -1260,14 +1566,14 @@ def write_to_version_file(filename, versions): print("set %s to '%s'" % (filename, versions["version"])) -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -1291,23 +1597,70 @@ def render_pep440(pieces): return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] + rendered = "0.post0.dev%d" % pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -1334,12 +1687,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -1356,7 +1738,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -1376,7 +1758,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -1396,7 +1778,7 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return { @@ -1412,10 +1794,14 @@ def render(pieces, style): if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -1438,7 +1824,7 @@ class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" -def get_versions(verbose=False): +def get_versions(verbose: bool = False) -> Dict[str, Any]: """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. @@ -1453,7 +1839,7 @@ def get_versions(verbose=False): 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 + verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` assert ( cfg.versionfile_source is not None ), "please set versioneer.versionfile_source" @@ -1519,13 +1905,17 @@ def get_versions(verbose=False): } -def get_version(): +def get_version() -> str: """Get the short version string for this project.""" return get_versions()["version"] -def get_cmdclass(): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" +def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None): + """Get the custom setuptools subclasses used by Versioneer. + + If the package uses a different cmdclass (e.g. one from numpy), it + should be provide as an argument. + """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and @@ -1539,25 +1929,25 @@ def get_cmdclass(): # 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 + # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - cmds = {} + cmds = {} if cmdclass is None else cmdclass.copy() - # we add "version" to both distutils and setuptools - from distutils.core import Command + # we add "version" to setuptools + from setuptools import Command class cmd_version(Command): description = "report generated version string" - user_options = [] - boolean_options = [] + user_options: List[Tuple[str, str, str]] = [] + boolean_options: List[str] = [] - def initialize_options(self): + def initialize_options(self) -> None: pass - def finalize_options(self): + def finalize_options(self) -> None: pass - def run(self): + def run(self) -> None: vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) @@ -1568,7 +1958,7 @@ def run(self): cmds["version"] = cmd_version - # we override "build_py" in both distutils and setuptools + # we override "build_py" in setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py @@ -1583,18 +1973,25 @@ def run(self): # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? + # pip install -e . and setuptool/editable_wheel will invoke build_py + # but the build_py command is not expected to copy any files. + # 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 + if "build_py" in cmds: + _build_py: Any = cmds["build_py"] else: - from distutils.command.build_py import build_py as _build_py + from setuptools.command.build_py import build_py as _build_py class cmd_build_py(_build_py): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) + if getattr(self, "editable_mode", False): + # During editable installs `.py` and data files are + # not copied to build_lib + return # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: @@ -1604,8 +2001,42 @@ def run(self): cmds["build_py"] = cmd_build_py + if "build_ext" in cmds: + _build_ext: Any = cmds["build_ext"] + else: + from setuptools.command.build_ext import build_ext as _build_ext + + class cmd_build_ext(_build_ext): + def run(self) -> None: + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_ext.run(self) + if self.inplace: + # build_ext --inplace will only build extensions in + # build/lib<..> dir with no _version.py to write to. + # As in place builds will already have a _version.py + # in the module dir, we do not need to write one. + return + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if not cfg.versionfile_build: + return + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) + if not os.path.exists(target_versionfile): + print( + f"Warning: {target_versionfile} does not exist, skipping " + "version update. This can happen if you are running build_ext " + "without first running build_py." + ) + return + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + cmds["build_ext"] = cmd_build_ext + if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe + from cx_Freeze.dist import build_exe as _build_exe # type: ignore # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. @@ -1615,7 +2046,7 @@ def run(self): # ... class cmd_build_exe(_build_exe): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() @@ -1643,12 +2074,12 @@ def run(self): if "py2exe" in sys.modules: # py2exe enabled? try: - from py2exe.distutils_buildexe import py2exe as _py2exe # py3 + from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore except ImportError: - from py2exe.build_exe import py2exe as _py2exe # py2 + from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore class cmd_py2exe(_py2exe): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() @@ -1673,14 +2104,54 @@ def run(self): cmds["py2exe"] = cmd_py2exe + # sdist farms its file list building out to egg_info + if "egg_info" in cmds: + _egg_info: Any = cmds["egg_info"] + else: + from setuptools.command.egg_info import egg_info as _egg_info + + class cmd_egg_info(_egg_info): + def find_sources(self) -> None: + # egg_info.find_sources builds the manifest list and writes it + # in one shot + super().find_sources() + + # Modify the filelist and normalize it + root = get_root() + cfg = get_config_from_root(root) + self.filelist.append("versioneer.py") + if cfg.versionfile_source: + # There are rare cases where versionfile_source might not be + # included by default, so we must be explicit + self.filelist.append(cfg.versionfile_source) + self.filelist.sort() + self.filelist.remove_duplicates() + + # The write method is hidden in the manifest_maker instance that + # generated the filelist and was thrown away + # We will instead replicate their final normalization (to unicode, + # and POSIX-style paths) + from setuptools import unicode_utils + + normalized = [ + unicode_utils.filesys_decode(f).replace(os.sep, "/") + for f in self.filelist.files + ] + + manifest_filename = os.path.join(self.egg_info, "SOURCES.txt") + with open(manifest_filename, "w") as fobj: + fobj.write("\n".join(normalized)) + + cmds["egg_info"] = cmd_egg_info + # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist + if "sdist" in cmds: + _sdist: Any = cmds["sdist"] else: - from distutils.command.sdist import sdist as _sdist + from setuptools.command.sdist import sdist as _sdist class cmd_sdist(_sdist): - def run(self): + def run(self) -> None: versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old @@ -1688,7 +2159,7 @@ def run(self): self.distribution.metadata.version = versions["version"] return _sdist.run(self) - def make_release_tree(self, base_dir, files): + def make_release_tree(self, base_dir: str, files: List[str]) -> None: root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) @@ -1743,24 +2214,25 @@ def make_release_tree(self, base_dir, files): """ -INIT_PY_SNIPPET = """ +OLD_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ +INIT_PY_SNIPPET = """ +from . import {0} +__version__ = {0}.get_versions()['version'] +""" + -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" +def do_setup() -> int: + """Do 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)): + except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: + if isinstance(e, (OSError, 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) @@ -1782,64 +2254,37 @@ def do_setup(): ) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") + maybe_ipy: Optional[str] = ipy if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() - except EnvironmentError: + except OSError: old = "" - if INIT_PY_SNIPPET not in old: + module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] + snippet = INIT_PY_SNIPPET.format(module) + if OLD_SNIPPET in old: + print(" replacing boilerplate in %s" % ipy) + with open(ipy, "w") as f: + f.write(old.replace(OLD_SNIPPET, snippet)) + elif snippet not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) + f.write(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") + maybe_ipy = None # 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) + do_vcs_install(cfg.versionfile_source, maybe_ipy) return 0 -def scan_setup_py(): +def scan_setup_py() -> int: """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False @@ -1876,10 +2321,14 @@ def scan_setup_py(): return errors +def setup_command() -> NoReturn: + """Set up Versioneer and exit with appropriate error code.""" + errors = do_setup() + errors += scan_setup_py() + sys.exit(1 if errors else 0) + + if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1) + setup_command()