diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..231a000 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# a few things we don't want to include in the repo -- based on github's +# default .gitignore for python repos +.coverage +__pycache__/ +*.egg-info/ diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..2ca9c1a --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +include README.md +include COPYING.txt +include q2_FEAST/citations.bib diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8390056 --- /dev/null +++ b/Makefile @@ -0,0 +1,4 @@ +.PHONY: test + +test: + nosetests -v -s q2_feast --with-coverage --cover-package=q2_feast diff --git a/R/FEAST.R b/R/FEAST.R index 149be09..dc2e1d8 100644 --- a/R/FEAST.R +++ b/R/FEAST.R @@ -19,9 +19,6 @@ #' @param COVERAGE A numeric value indicating the rarefaction depth (default = minimal sequencing depth within each group of sink #' and its corresponding sources). #' @param different_sources_flag A boolian value indicating the source-sink assignment. -#' @param dir_path A path to an output .txt file. -#' @param outfile the prefix for saving the output file. -#' different_sources_flag = 1 if different sources are assigned to each sink , otherwise = 0. #' @return P - an \eqn{S1} by \eqn{S2} matrix, where \eqn{S1} is the number sinks and \eqn{S2} #' is the number of sources (including an unknown source). Each row in matrix \eqn{P} sums to 1. #' \eqn{Pij} is the contribution of source j to sink i. @@ -41,8 +38,7 @@ #' } #' #' @export -FEAST <- function(C, metadata, EM_iterations = 1000, COVERAGE = NULL ,different_sources_flag, - dir_path, outfile){ +FEAST <- function(C, metadata, EM_iterations = 1000, COVERAGE = NULL ,different_sources_flag){ ###1. Parse metadata and check it has the correct hearer (i.e., Env, SourceSink, id) if(sum(colnames(metadata)=='Env')==0) stop("The metadata file must contain an 'Env' column naming the source environment for each sample.") @@ -143,9 +139,6 @@ FEAST <- function(C, metadata, EM_iterations = 1000, COVERAGE = NULL ,different_ colnames(proportions_mat) <- c(envs_sources, "Unknown") rownames(proportions_mat) <- envs_sink # proportions_mat[is.na(proportions_mat)] <- 999 - - setwd(dir_path) - write.table(proportions_mat, file = paste0(outfile,"_source_contributions_matrix.txt"), sep = "\t") return(proportions_mat) } diff --git a/README.md b/README.md index de40135..0e502d4 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,6 @@ Software Requirements and dependencies Packages <- c("Rcpp", "RcppArmadillo", "vegan", "dplyr", "reshape2", "gridExtra", "ggplot2", "ggthemes") install.packages(Packages) lapply(Packages, library, character.only = TRUE) - ``` @@ -147,7 +146,3 @@ Output - | infant gut 2 |Adult gut 1 | Adult gut 2| Adult gut 3| Adult skin 1 | Adult skin 2| Adult skin 3| Soil 1 | Soil 2 | unknown| | ------------- | ------------- |------------- |------------- |------------- |------------- |------------- |------------- |------------- |------------- | | 5.108461e-01 | 9.584116e-23 | 4.980321e-12 | 2.623358e-02|5.043635e-13 | 8.213667e-59| 1.773058e-10 | 2.704118e-14 | 3.460067e-02 | 4.283196e-01 | - - - - diff --git a/q2_feast/README.md b/q2_feast/README.md new file mode 100644 index 0000000..f940def --- /dev/null +++ b/q2_feast/README.md @@ -0,0 +1,97 @@ +# FEAST QIIME 2 Plugin + + +One critical challenge in analyzing microbiome communities is due to their composition; each of them is typically comprised of several source environments, including different contaminants as well as other microbial communities that interacted with the sampled habitat. To account for this structure, we developed FEAST (Fast Expectation-mAximization microbial Source Tracking), a ready-to-use scalable framework that can simultaneously estimate the contribution of thousands of potential source environments in a timely manner, thereby helping unravel the origins of complex microbial communities. Specifically, FEAST is quantifying the fraction, or proportion, of different microbial samples (sources) in a target microbial community (sink), by leveraging its structure and measuring the respective similarities between a sink community and potential source environments. For more details see Shenhav et al., Nature Methods 2019 (https://www.nature.com/articles/s41592-019-0431-x). + +## Installation + +If you have not already done so, activate your QIIME environment. + +```shell +source activate qiime2-20xx.x +``` +Next we will need to ensure some dependancies are installed. + +```shell +conda install -c bioconda -c conda-forge -c r bioconductor-phyloseq r-devtools r-magrittr r-dplyr r-vgam r-tidyr r-vegan r-reshape2 r-rcpp r-rcpparmadillo r-gridextra r-ggplot2 r-ggthemes +``` + +Now we will install FEAST and the q2-plugin. + +```R +# the main FEAST package +> R +> devtools::install_github("cozygene/FEAST") +> quit() +``` +```shell +# the QIIME2 plugin +pip install git+https://github.com/cozygene/FEAST.git +``` + +## Tutorial + +A QIIME2 tutorial is available [here](https://github.com/cozygene/FEAST/q2_feast/tutorials/DIABIMMUNE.md) + +## The q2-FEAST commands + +The QIIME 2 implementation of FEAST contains two steps. + +1. The first step, called `microbialtracking`, performs the tracking and + outputs a table of mixing proportions of the semantic type + `FeatureTable[Frequency]`. + +2. The second command, `barplot`, takes the output from the previous step and + creates an interactive stacked barplot of source-contributions to each sink. + + Note that this command just creates a visualization from a single + mixing proportions table. However, if you have lots of samples in your + proportions table, you can create multiple visualizations by splitting up + your proportions table using the `qiime feature-table filter-samples` command + in QIIME 2. + +![](tutorials/etc/backhed-barplot.png) + +## Setting up a development environment for q2-FEAST + +This section contains instructions on how to set up a development environment +of q2-FEAST, at least as of writing. + +1. Activate your QIIME 2 conda environment. + +2. Fork this git repository, then clone your fork to your system. + +3. Install the R dependencies as shown in the installation instructions at the + top of this file (`conda install -c bioconda ...`). + However, don't install FEAST using `devtools::install_github()` quite yet. + +4. Using your favorite shell (e.g. bash), navigate into the folder this fork + was installed into (the folder that contains this `README.md`). + +5. Open up R, then run the + [following command](https://stackoverflow.com/a/34513358/10730311): + ```r + > devtools::install() + ``` + This will install the FEAST R package from the current directory. + If you get prompted to update package versions, it's probably fine to do + that. + +6. We've installed FEAST's R prerequisites, as well as the actual FEAST R + package, but we haven't installed the Python infrastructure needed to + get this working with QIIME 2 yet. Let's do that! + + Exit out of R back to the shell. Run the following command: + ```bash + $ pip install -e .[dev] + ``` + This will install the q2-FEAST package from the current directory, along +with its `dev` requirements (which are needed to run its tests). + +7. We're almost done! Run the following commands to test that FEAST and + q2-FEAST are properly installed: + ```bash + $ qiime dev refresh-cache + $ make test + ``` + If these commands succeed, you should be good to start developing! diff --git a/q2_feast/__init__.py b/q2_feast/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/q2_feast/_feast_defaults.py b/q2_feast/_feast_defaults.py new file mode 100644 index 0000000..7249662 --- /dev/null +++ b/q2_feast/_feast_defaults.py @@ -0,0 +1,35 @@ +# Configuration file where you can set the parameter default values and +# descriptions. +DEFAULT_SHARED = None +DEFAULT_EMITR = 1000 +DEFAULT_DIFFS = True + +DESC_META = ('Sample metadata file containing sources' + ' and sinks for source tracking.') +DESC_TBL = ('Feature table file containing sources' + ' and sinks for source tracking.') +DESC_MP = ('The mixing proportions returned from FEAST.' + ' The mixing proportions table is an S1 by ' + 'S2 matrix P, where S1 is the number sinks ' + 'and S2 is the number of sources (including ' + 'an unknown source). Each row in matrix P sums' + ' to 1. Pij is the contribution of source j to ' + 'sink i. If Pij == NA it indicates that source ' + 'j was not used in the analysis of sink i.') +DESC_ENVC = ('Sample metadata column with a description ' + 'of the sampled environment (e.g., human gut).') +DESC_SSC = ('Sample metadata column with labels for source or a sink.' + 'All the sub-classes in this column must be in' + ' either source_ids or sink_ids.') +DESC_SOURCEID = ( + 'Comma-separated list (without spaces) of class ids ' + 'contained in source_sink_column to be considered as sources.') +DESC_SINKID = ('Comma-separated list (without spaces) of class ids ' + 'contained in source_sink_column to be considered as sinks.') +DESC_SHARED = ('Sample metadata column with the Sink-Source id.' + ' When using multiple sinks, each tested with the ' + 'same group of sources') +DESC_EMITR = ('A numeric value indicating the number of EM iterations.') +DESC_DIFFS = ('A Boolean value indicating the source-sink assignment.' + 'Different-sources is True if different sources are assigned' + 'to each sink, otherwise different-sources should be False.') diff --git a/q2_feast/_method.py b/q2_feast/_method.py new file mode 100644 index 0000000..e350207 --- /dev/null +++ b/q2_feast/_method.py @@ -0,0 +1,178 @@ +import os +import tempfile +import subprocess +import pandas as pd +from qiime2 import Metadata +from ._feast_defaults import (DEFAULT_DIFFS, + DEFAULT_EMITR) + + +def run_commands(cmds, verbose=True): + """ + This function is a script runner. + It was obtained from https://github.com/ggloor + /q2-aldex2/blob/master/q2_aldex2/_method.py + """ + if verbose: + print("Running external command line application(s). This may print " + "messages to stdout and/or stderr.") + print("The command(s) being run are below. These commands cannot " + "be manually re-run as they will depend on temporary files that " + "no longer exist.") + for cmd in cmds: + if verbose: + print("\nCommand:", end=' ') + print(" ".join(cmd), end='\n\n') + subprocess.run(cmd, check=True) + + +def feast_format(fmeta: pd.DataFrame, + source_sink_column: str, + source_ids: list, + sink_ids: list,) -> pd.DataFrame: + """ + Helper function to format metadata for FEAST. + """ + + # ensure that all sub-cats in SourceSink are represented + missing_ = list(set(fmeta[source_sink_column]) + - set(source_ids + sink_ids)) + if len(missing_) > 0: + raise ValueError(('All of the sub-classes of %s must' + ' be given as a source or sink' + 'the sub-class(es) [%s] are missing.') + % (str(source_sink_column), + ', '.join(map(str, missing_)))) + # rename ids in source and sink columns (only if all rep.) + rename_ = {**{id_: 'Source' for id_ in source_ids}, + **{id_: 'Sink' for id_ in sink_ids}} + fmeta[source_sink_column].replace(to_replace=rename_, + inplace=True) + + return fmeta + + +def microbialtracking(table: pd.DataFrame, + metadata: Metadata, + environment_column: str, + source_sink_column: str, + source_ids: list, + sink_ids: list, + shared_id_column: str, + em_iterations: int = DEFAULT_EMITR, + different_sources: bool = DEFAULT_DIFFS) -> pd.DataFrame: + + # split the ids used for sources and sinks + source_ids = source_ids.split(",") + sink_ids = sink_ids.split(",") + + # create metadata formatted for FEAST + # check if there are shared ids. + # currently FEAST requires an id + # column but in future versions it will + # be an optional peram. + if shared_id_column is not None: + keep_cols = [environment_column, + source_sink_column, + shared_id_column] + rename_cols = ['Env', 'SourceSink', 'id'] + else: + keep_cols = [environment_column, + source_sink_column] + rename_cols = ['Env', 'SourceSink'] + + # import and check all columns given are in dataframe + metadata = metadata.to_dataframe() + # replace seperation character in metadata + metadata = metadata.replace('_', '-', + regex=True) + metadata.index = metadata.index.astype(str) + metadata.index = [ind.replace('_', '-') + for ind in metadata.index] + # check columns are in metadata + if not all([col_ in metadata.columns for col_ in keep_cols]): + raise ValueError('Not all columns given are present in the' + ' sample metadata file. Please check that' + ' the input columns are in the given metdata.') + + # keep only those columns + feast_meta = metadata.dropna(subset=keep_cols) + feast_meta = feast_meta.loc[:, keep_cols] + + # filter the metadata & table so they are matched + table = table.T + shared_index = list(set(table.columns) & set(feast_meta.index)) + feast_meta = feast_meta.reindex(shared_index) + table = table.loc[:, shared_index] + + # format the sub-classes for source-sink + feast_meta = feast_format(feast_meta, + source_sink_column, + source_ids, + sink_ids) + if shared_id_column is not None: + # encode the shared SourceSink id column + # with numerics ranging from 1-N + shared_ = set(metadata[shared_id_column]) + rename_ = {id_: str(int(i) + 1) for i, id_ in enumerate(shared_)} + feast_meta[shared_id_column].replace(to_replace=rename_, + inplace=True) + if not different_sources or shared_id_column is None: + # get source-sink + source_index = feast_meta[feast_meta[source_sink_column] == 'Source'].index + sink_index = feast_meta[feast_meta[source_sink_column] == 'Sink'].index + # set sources IDs to NA + feast_meta.loc[source_index, shared_id_column] = 'NA' + # give sinks IDs (each sink gets a different ID) + for i, sid_ in enumerate(sink_index): + feast_meta.loc[sid_, shared_id_column] = str(int(i) + 1) + #shared_ = set(metadata.loc[sink_index, shared_id_column].values) + #rename_ = {id_: str(int(i)) for i, id_ in enumerate(shared_)} + #feast_meta[shared_id_column].replace(to_replace=rename_, + # inplace=True) + + # make sure that if no "shared_id_column" supplied IDs not used + different_sources = False + + # rename those columns for FEAST + feast_meta.columns = rename_cols + + # if there are different sources + if different_sources: + different_sources = 1 + else: + different_sources = 0 + + # save all intermediate files into tmp dir + with tempfile.TemporaryDirectory() as temp_dir_name: + # save the tmp dir locations + biom_fp = os.path.join(temp_dir_name, 'input.tsv') + map_fp = os.path.join(temp_dir_name, 'input.map.txt') + summary_fp = os.path.join(temp_dir_name, 'output.proportions.txt') + + # Need to manually specify header=True for Series (i.e. "meta"). It's + # already the default for DataFrames (i.e. "table"), but we manually + # specify it here anyway to alleviate any potential confusion. + table.to_csv(biom_fp, sep='\t', header=True) + feast_meta.to_csv(map_fp, sep='\t', header=True) + + # build command for FEAST + cmd = ['source_tracking.R', + biom_fp, + map_fp, + different_sources, + summary_fp] + cmd = list(map(str, cmd)) + + try: + run_commands([cmd]) + except subprocess.CalledProcessError as e: + raise Exception("An error was encountered while running FEAST" + " in R (return code %d), please inspect stdout" + " and stderr to learn more." % e.returncode) + + # if run was sucessfull import the data and return + proportions = pd.read_csv(summary_fp, index_col=0).T + proportions.index.name = "sampleid" + + return proportions \ No newline at end of file diff --git a/q2_feast/_version.py b/q2_feast/_version.py new file mode 100755 index 0000000..4f33681 --- /dev/null +++ b/q2_feast/_version.py @@ -0,0 +1,506 @@ +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.18 (https://github.com/warner/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "$Format:%d$" + git_full = "$Format:%H$" + git_date = "$Format:%ci$" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "pep440" + cfg.tag_prefix = "" + cfg.parentdir_prefix = "q2-composition-" + cfg.versionfile_source = "q2_composition/_version.py" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs - tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + The ".dev0" means dirty. + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + Like 'git describe --tags --dirty --always'. + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} diff --git a/q2_feast/_visualizer.py b/q2_feast/_visualizer.py new file mode 100644 index 0000000..fa6e7f3 --- /dev/null +++ b/q2_feast/_visualizer.py @@ -0,0 +1,59 @@ +import os +import shutil +import pandas as pd +from qiime2 import Artifact, Metadata +from q2_taxa._visualizer import barplot as _barplot + +def barplot(output_dir: str, + mixing_proportions: pd.DataFrame, + metadata: Metadata) -> None: + + # fix identifiers + mixing_proportions.index = [ind.split('_')[0] + for ind in mixing_proportions.index] + mixing_proportions.columns = [col.split('_')[0] + for col in mixing_proportions.columns] + + # import and check all columns given are in dataframe + metadata = metadata.to_dataframe() + + # replace seperation character in metadata + metadata = metadata.replace('_', '-', + regex=True) + metadata.index = metadata.index.astype(str) + metadata.index = [ind.replace('_', '-') + for ind in metadata.index] + + # make "Sink" metadata (columns of mixing_proportions) + sink_metadata = metadata.reindex(mixing_proportions.columns) + sink_metadata.index.name = 'sampleid' + sink_metadata = Metadata(sink_metadata) + + # make "Source" metadata (index of mixing_proportions) + source_metadata = metadata.reindex(mixing_proportions.index).fillna('Unkown-Source') + source_metadata = source_metadata.astype(str).apply(lambda x: '; '.join(x), axis=1) + source_metadata = pd.DataFrame(source_metadata, + columns = ['Taxon']) + source_metadata.index.name = 'Feature ID' + + # make barplot + _barplot(output_dir, + mixing_proportions.T, + pd.Series(source_metadata.Taxon), + sink_metadata) + + # grab bundle location to fix + bundle = os.path.join(output_dir, + 'dist', + 'bundle.js') + # bundle terms to fix for our purpose + bundle_rplc = {'Relative Frequency':'Source Contribution', + 'Taxonomic Level':'Source Grouping', + 'Sample':'Sink'} + # make small text chnage to bundle + with open(bundle) as f: + newText=f.read() + for prev, repl in bundle_rplc.items(): + newText = newText.replace(prev, repl) + with open(bundle, "w") as f: + f.write(newText) diff --git a/q2_feast/assets/source_tracking.R b/q2_feast/assets/source_tracking.R new file mode 100644 index 0000000..93ba407 --- /dev/null +++ b/q2_feast/assets/source_tracking.R @@ -0,0 +1,37 @@ +#!/usr/bin/env Rscript + +cat(R.version$version.string, "\n") + +# load arguments --------------------------------------------------------- +args <- commandArgs(TRUE) +inp.abundances.path <- args[[1]] # OTU table file +inp.metadata.path <- args[[2]] # Metadata file +diffsource <- args[[3]] # diff source (0,1) +output <- args[[4]] # to write to temp file + +# load libraries ---------------------------------------------------------- +suppressWarnings(library(FEAST)) + +# load data --------------------------------------------------------------- + +# table import +if(!file.exists(inp.abundances.path)) { + errQuit("Input count table file does not exist.") +} else { + table <- Load_CountMatrix(CountMatrix_path = inp.abundances.path) +} +# map import +if(!file.exists(inp.metadata.path)) { + errQuit("Input mapping file does not exist.") +} else { + meta <- Load_metadata(metadata_path = inp.metadata.path) +} + +# analysis ---------------------------------------------------------------- +proportions <- FEAST(C = table, + metadata = meta, + different_sources_flag = diffsource) + +# output ---------------------------------------------------------------- +proportions <- as.data.frame(proportions) +write.csv(proportions, file=output) \ No newline at end of file diff --git a/q2_feast/citations.bib b/q2_feast/citations.bib new file mode 100644 index 0000000..4179eb1 --- /dev/null +++ b/q2_feast/citations.bib @@ -0,0 +1,26 @@ +@ARTICLE{Shenhav2019-ca, + title = "{FEAST}: fast expectation-maximization for microbial source + tracking", + author = "Shenhav, Liat and Thompson, Mike and Joseph, Tyler A and Briscoe, + Leah and Furman, Ori and Bogumil, David and Mizrahi, Itzhak and + Pe'er, Itsik and Halperin, Eran", + abstract = "A major challenge of analyzing the compositional structure of + microbiome data is identifying its potential origins. Here, we + introduce fast expectation-maximization microbial source tracking + (FEAST), a ready-to-use scalable framework that can + simultaneously estimate the contribution of thousands of + potential source environments in a timely manner, thereby helping + unravel the origins of complex microbial communities ( + https://github.com/cozygene/FEAST ). The information gained from + FEAST may provide insight into quantifying contamination, + tracking the formation of developing microbial communities, as + well as distinguishing and characterizing bacteria-related health + conditions.", + journal = "Nat. Methods", + volume = 16, + number = 7, + pages = "627--632", + month = "july", + year = 2019, + language = "en" +} diff --git a/q2_feast/plugin_setup.py b/q2_feast/plugin_setup.py new file mode 100644 index 0000000..8781989 --- /dev/null +++ b/q2_feast/plugin_setup.py @@ -0,0 +1,92 @@ + +import qiime2.sdk +import qiime2.plugin +from qiime2.plugin import (Int, Metadata, + Str, Bool) +from q2_types.feature_table import (FeatureTable, + Frequency, + RelativeFrequency) +from q2_types.feature_data import (FeatureData, + Taxonomy) + +from ._visualizer import barplot +from ._method import microbialtracking +from ._feast_defaults import (DESC_META, DESC_ENVC, + DESC_SSC, DESC_SOURCEID, + DESC_SINKID, DESC_SHARED, + DESC_EMITR, DESC_DIFFS, + DESC_MP, DESC_TBL) + +# TODO: will need to fix the version number +__version__ = '0.1.0' + +# perams types +PARAMETERS = {'metadata': Metadata, + 'environment_column': Str, + 'source_sink_column': Str, + 'source_ids': Str, + 'sink_ids': Str, + 'shared_id_column': Str, + 'em_iterations': Int, + 'different_sources': Bool} +# perams descriptions +PARAMETERDESC = {'metadata': DESC_META, + 'environment_column': DESC_ENVC, + 'source_sink_column': DESC_SSC, + 'source_ids': DESC_SOURCEID, + 'sink_ids': DESC_SINKID, + 'shared_id_column': DESC_SHARED, + 'em_iterations': DESC_EMITR, + 'different_sources': DESC_DIFFS} + +citations = qiime2.plugin.Citations.load('citations.bib', + package='q2_feast') + +plugin = qiime2.plugin.Plugin( + name='feast', + version=__version__, + website="https://github.com/cozygene/FEAST", + citations=[citations['Shenhav2019-ca']], + short_description=('Plugin for FEAST source-tracking'), + description=('This is a QIIME 2 plugin supporting microbial' + ' source-tracking through FEAST.'), + package='q2_feast') + +plugin.methods.register_function( + function=microbialtracking, + inputs={'table': FeatureTable[Frequency]}, + parameters=PARAMETERS, + outputs=[('proportions', FeatureTable[Frequency])], + input_descriptions={'table': DESC_TBL}, + parameter_descriptions=PARAMETERDESC, + output_descriptions={'proportions': DESC_MP}, + name='microbial source-tracking', + description=('A major challenge of analyzing the compositional ' + 'structure of microbiome data is identifying its ' + 'potential origins. Here, we introduce fast ' + 'expectation-maximization microbial source ' + 'tracking (FEAST), a ready-to-use scalable ' + 'framework that can simultaneously estimate ' + 'the contribution of thousands of potential ' + 'source environments in a timely manner, ' + 'thereby helping unravel the ' + 'origins of complex microbial communities. ' + 'The information gained from ' + 'FEAST may provide insight into quantifying' + ' contamination, tracking the formation of developing' + ' microbial communities, as well as distinguishing ' + 'and characterizing bacteria-related health conditions.'), +) + +plugin.visualizers.register_function( + function=barplot, + inputs={'mixing_proportions': FeatureTable[Frequency]}, + parameters={'metadata': Metadata}, + input_descriptions={'mixing_proportions': DESC_MP}, + parameter_descriptions={'metadata': DESC_META}, + name='Visualize source-contributions with an interactive bar plot', + description='This visualizer produces an interactive barplot visualization' + ' of sources. Interactive features include multi-level ' + 'sorting, plot recoloring, sample relabeling, and SVG ' + 'figure export.' +) \ No newline at end of file diff --git a/q2_feast/tests/data/exp-mixed-mp.tsv b/q2_feast/tests/data/exp-mixed-mp.tsv new file mode 100644 index 0000000..03ec7b1 --- /dev/null +++ b/q2_feast/tests/data/exp-mixed-mp.tsv @@ -0,0 +1,292 @@ +sampleid ERR525850_Env-1 ERR525745_Env-1 ERR526054_Env-1 ERR525790_Env-1 ERR525778_Env-1 ERR525834_Env-1 ERR526078_Env-1 ERR526058_Env-1 ERR525927_Env-1 ERR525728_Env-1 ERR525982_Env-1 ERR526002_Env-1 ERR525958_Env-1 ERR525902_Env-1 ERR525749_Env-1 ERR525962_Env-1 ERR525786_Env-1 ERR526062_Env-1 ERR525830_Env-1 ERR525758_Env-1 ERR525838_Env-1 ERR526010_Env-1 ERR526042_Env-1 ERR525894_Env-1 ERR525711_Env-1 ERR525888_Env-1 ERR526014_Env-1 ERR525770_Env-1 ERR525826_Env-1 ERR525696_Env-1 ERR525808_Env-1 ERR525803_Env-1 ERR525966_Env-1 ERR525846_Env-1 ERR525874_Env-1 ERR525922_Env-1 ERR525900_Env-1 ERR525970_Env-1 ERR525766_Env-1 ERR525756_Env-1 ERR526050_Env-1 ERR525762_Env-1 ERR526018_Env-1 ERR525698_Env-1 ERR526034_Env-1 ERR526082_Env-1 ERR526072_Env-1 ERR525782_Env-1 ERR525938_Env-1 ERR525883_Env-1 ERR525906_Env-1 ERR526066_Env-1 ERR525878_Env-1 ERR525942_Env-1 ERR525910_Env-1 ERR525736_Env-1 ERR525952_Env-1 ERR525705_Env-1 ERR525732_Env-1 ERR525822_Env-1 ERR525974_Env-1 ERR525715_Env-1 ERR526026_Env-1 ERR525774_Env-1 ERR525930_Env-1 ERR525794_Env-1 ERR525892_Env-1 ERR525707_Env-1 ERR525947_Env-1 ERR525998_Env-1 ERR526022_Env-1 ERR526086_Env-1 ERR526006_Env-1 ERR525691_Env-1 ERR525818_Env-1 ERR525814_Env-1 ERR525990_Env-1 ERR525870_Env-1 ERR526030_Env-1 ERR525994_Env-1 ERR525740_Env-1 ERR525914_Env-1 ERR525858_Env-1 ERR525724_Env-1 ERR525812_Env-1 ERR525954_Env-1 ERR525854_Env-1 ERR526046_Env-1 ERR525719_Env-1 ERR525752_Env-1 ERR525986_Env-1 ERR526038_Env-1 ERR525798_Env-1 ERR525918_Env-1 ERR525934_Env-1 ERR525866_Env-1 ERR525862_Env-1 +ERR525980_Env-3 0.7648952207918059 +ERR525690_Env-2 0.41225292235793703 +ERR525940_Env-3 0.000242266693300367 +ERR525921_Env-2 0.940265813090756 +ERR525806_Env-3 0.832692441383101 +ERR525913_Env-2 0.9601052681745759 +ERR525720_Env-4 0.000328363575651735 +ERR525802_Env-2 0.9505553034424309 +ERR526059_Env-4 8.82270709621391e-05 +ERR525925_Env-3 0.000581076741436747 +ERR525915_Env-4 0.000409787883626844 +ERR525884_Env-4 6.37710769026074e-05 +ERR526035_Env-4 0.000237341673299767 +ERR526051_Env-4 0.9310563231493678 +ERR525890_Env-3 0.573881055394697 +ERR525791_Env-4 0.0574126420737158 +ERR525907_Env-4 3.14500971098373e-06 +ERR525946_Env-2 0.327131360717316 +ERR525836_Env-3 0.0804961336282237 +ERR526029_Env-2 0.360513851973206 +ERR525964_Env-3 0.702096364103042 +ERR525729_Env-4 0.00296460164633392 +ERR525985_Env-2 0.9966095199130021 +ERR525929_Env-2 0.888711284884247 +ERR525710_Env-2 0.9925071670363559 +ERR525823_Env-4 0.000407894590747542 +ERR525693_Env-2 0.987909087704604 +ERR525844_Env-3 0.0489285773386049 +ERR525689_Env-3 0.13958159509269102 +ERR525896_Env-3 0.0142077682444724 +ERR525848_Env-3 0.367366752366729 +ERR526003_Env-4 0.8640539078520691 +ERR525981_Env-2 0.196627851301804 +ERR525996_Env-3 0.995545208336861 +ERR525865_Env-2 0.9465399059495029 +ERR525815_Env-4 0.950021153383957 +ERR525889_Env-4 0.000253483821466419 +ERR526039_Env-4 0.985257325387897 +ERR525760_Env-3 0.67303882651858 +ERR525692_Env-4 0.19052981335000102 +ERR525780_Env-3 0.000799893846397813 +ERR526087_Env-4 0.0126170311446961 +ERR525877_Env-2 0.951619801707692 +ERR525879_Env-4 0.0397775669986009 +ERR525951_Env-2 0.8204441124789391 +ERR525953_Env-4 7.400118807881959e-05 +ERR525737_Env-4 0.327007823037831 +ERR525816_Env-3 0.0046248579994095105 +ERR525731_Env-2 0.399950579136826 +ERR526028_Env-3 0.549948772131014 +ERR525735_Env-2 0.386025915471632 +ERR525991_Env-4 0.19857146376465198 +ERR525963_Env-4 8.549861419397159e-05 +ERR526080_Env-3 0.00471574370654979 +ERR525769_Env-2 0.912422746377885 +ERR526049_Env-2 0.0006730469809021941 +ERR525855_Env-4 0.0008543943857372481 +ERR525849_Env-2 0.613924098227578 +ERR526020_Env-3 4.4117304057583104e-07 +ERR525992_Env-3 3.8718944483990506e-05 +ERR526041_Env-2 0.9628078537423199 +ERR525959_Env-4 0.207363229764928 +ERR526085_Env-2 0.9858522913694749 +ERR525825_Env-2 0.012143335828439 +ERR525712_Env-4 0.00019466517280966201 +ERR525709_Env-3 0.000588945967398522 +ERR525726_Env-3 0.00024217664900629503 +ERR525717_Env-3 0.436513646125508 +ERR526008_Env-3 0.138155886819504 +ERR526071_Env-2 0.963006825398657 +ERR525923_Env-4 0.000249703961108615 +ERR525895_Env-4 0.9480473206385029 +ERR526044_Env-3 0.171666766490764 +ERR525857_Env-2 0.8718526923597769 +ERR526055_Env-4 0.00139635143001231 +ERR525784_Env-3 0.0053036081658297 +ERR526011_Env-4 0.00293122194245511 +ERR526024_Env-3 0.000776701494341227 +ERR525824_Env-3 0.000652122457952136 +ERR525797_Env-2 0.9722245110255051 +ERR525820_Env-3 2.5917923160107e-07 +ERR525753_Env-4 0.0186921053815716 +ERR525955_Env-4 0.000310312909603683 +ERR525932_Env-3 0.9918554754160669 +ERR525800_Env-3 0.0155776519431246 +ERR525789_Env-2 0.9098050456359928 +ERR525773_Env-2 0.938320417697722 +ERR525861_Env-2 0.9355844975087859 +ERR525867_Env-4 0.00423346804073803 +ERR525984_Env-3 0.0022447147535472 +ERR525869_Env-2 0.6652037469970921 +ERR525819_Env-4 0.0013070299893527802 +ERR525768_Env-3 0.0679515193968326 +ERR525893_Env-4 0.0017296197268919199 +ERR526012_Env-3 0.130198531961849 +ERR525851_Env-4 0.0139826626858696 +ERR525864_Env-3 0.0117521930049502 +ERR525804_Env-4 0.000944645006005467 +ERR525939_Env-4 0.156240474903304 +ERR526007_Env-4 0.0023671749741437 +ERR526052_Env-3 0.0022191855076023 +ERR525694_Env-3 7.317485685123149e-05 +ERR525968_Env-3 0.394393018203064 +ERR526015_Env-4 0.147558950120395 +ERR525708_Env-4 0.5575620506081079 +ERR525971_Env-4 3.9178996311860104e-05 +ERR526056_Env-3 0.0731237239089728 +ERR525809_Env-4 0.000514131999837591 +ERR525885_Env-2 7.12787603798185e-13 +ERR525831_Env-4 0.000438463658640241 +ERR526083_Env-4 0.000698827850502771 +ERR525904_Env-3 0.000996863131010379 +ERR526073_Env-4 0.00282381048266361 +ERR525898_Env-3 7.62058977638725e-05 +ERR525873_Env-2 0.670454311485908 +ERR525837_Env-2 0.6824930802136421 +ERR525775_Env-4 0.0312227062007195 +ERR525875_Env-4 0.000531048084507164 +ERR525995_Env-4 0.815221292124861 +ERR525880_Env-3 0.0463018565708358 +ERR525742_Env-3 9.35373600358255e-08 +ERR526036_Env-3 0.000430997878535045 +ERR525839_Env-4 0.227719345917475 +ERR526040_Env-3 0.00634903714767579 +ERR525956_Env-3 0.00018313714737223 +ERR525847_Env-4 0.415789302281795 +ERR525899_Env-2 0.980791210166695 +ERR525944_Env-3 0.00481283928896039 +ERR525965_Env-2 0.29637850550546996 +ERR526043_Env-4 0.0051142306286561 +ERR525856_Env-3 0.00023529179642507402 +ERR525796_Env-3 0.00392084778560688 +ERR525928_Env-4 0.00059982295918604 +ERR526009_Env-2 0.8124806488174191 +ERR526031_Env-4 0.000356675632109207 +ERR525916_Env-3 0.000884682954892217 +ERR526063_Env-4 9.717653404142671e-05 +ERR525926_Env-2 0.9893050220382941 +ERR525817_Env-2 0.977518451371253 +ERR525863_Env-4 0.0233865327941872 +ERR526047_Env-4 0.0156672804016146 +ERR525701_Env-3 0.400062816147969 +ERR526070_Env-3 0.00105796480988151 +ERR525744_Env-2 0.38466770106452597 +ERR525741_Env-4 0.0037365893643336204 +ERR525961_Env-2 0.9568718653200501 +ERR526000_Env-3 0.00219403262262638 +ERR525832_Env-3 0.192020826445325 +ERR526017_Env-2 0.8699891475522471 +ERR525852_Env-3 0.000157365263508702 +ERR525754_Env-3 0.00011677064899528401 +ERR525999_Env-4 0.00138486986830181 +ERR525750_Env-2 0.7925608139867478 +ERR525917_Env-2 0.9881179620886129 +ERR526053_Env-2 0.991715685077848 +ERR525764_Env-3 0.197723196567547 +ERR525807_Env-2 0.13845001338527402 +ERR525973_Env-2 0.699281451376388 +ERR525903_Env-4 0.0385941808540416 +ERR525975_Env-4 0.00207709102500715 +ERR525924_Env-3 0.00813444942736783 +ERR525734_Env-3 0.25869798169914304 +ERR526021_Env-2 0.6605435427714891 +ERR526057_Env-2 0.918130418474039 +ERR525714_Env-2 0.912022167075607 +ERR526081_Env-2 0.979458585731036 +ERR526005_Env-2 0.9820521209415899 +ERR525781_Env-2 0.934900328409133 +ERR525727_Env-2 0.9505377537167791 +ERR525993_Env-2 0.172348016632078 +ERR525829_Env-2 0.698950784196295 +ERR525813_Env-4 0.0217900062857517 +ERR525738_Env-3 0.762489361371696 +ERR525972_Env-3 0.286005927168764 +ERR526013_Env-2 0.7203875894956149 +ERR525882_Env-2 0.9406447582919342 +ERR525763_Env-4 0.0628978052505725 +ERR525920_Env-3 0.023529963872742 +ERR525945_Env-3 9.070825315031079e-05 +ERR525699_Env-4 0.0031166035946699803 +ERR525868_Env-3 0.281198949184651 +ERR525751_Env-4 0.770080024099735 +ERR525776_Env-3 0.9302518380271592 +ERR525933_Env-2 6.110418654404489e-27 +ERR526032_Env-3 0.8699345999795429 +ERR526060_Env-3 0.0439479868618092 +ERR526023_Env-4 0.31675280523417 +ERR525989_Env-2 0.798833699748292 +ERR525787_Env-4 0.000741642796472786 +ERR525783_Env-4 0.000328819988894375 +ERR526037_Env-2 0.000352055193260593 +ERR525905_Env-2 0.9722979600424699 +ERR525983_Env-4 0.00048499077731255897 +ERR525937_Env-2 9.59532614132654e-05 +ERR526067_Env-4 0.244712593335898 +ERR525950_Env-3 0.0837323838620132 +ERR525997_Env-2 0.000549458987571166 +ERR525811_Env-2 0.951924284876578 +ERR525886_Env-3 0.895861424634708 +ERR525805_Env-2 0.00642890817178183 +ERR525935_Env-4 0.00031825644357383196 +ERR525743_Env-3 0.16584909759858302 +ERR526004_Env-3 0.0114357870797856 +ERR525821_Env-2 0.938826770250408 +ERR525876_Env-3 9.71762287016989e-05 +ERR526027_Env-4 0.00165056490961907 +ERR525765_Env-2 0.465730763112314 +ERR525793_Env-2 0.9871796354004949 +ERR525759_Env-4 0.0250146158983623 +ERR525859_Env-4 0.0853857577255236 +ERR525739_Env-2 0.18201065088775303 +ERR526033_Env-2 0.0625883853977458 +ERR526045_Env-2 0.8055963212716379 +ERR525941_Env-2 0.9749727839850691 +ERR525936_Env-3 0.8039683436133441 +ERR525901_Env-4 0.00102896150583616 +ERR525733_Env-4 0.0011653799429770001 +ERR525897_Env-2 0.932896509941306 +ERR525909_Env-2 0.86811954572686 +ERR525967_Env-4 0.000407308561291885 +ERR525801_Env-3 0.0118568145482481 +ERR525891_Env-2 0.41409396766659706 +ERR526084_Env-3 0.000195282475918801 +ERR525835_Env-4 0.000194311124946371 +ERR525788_Env-3 0.00305372172262443 +ERR525702_Env-2 0.0391768674088533 +ERR525757_Env-4 0.700394983937609 +ERR525845_Env-2 0.525177397466298 +ERR525949_Env-2 0.990038367021639 +ERR525911_Env-4 0.0410143832963994 +ERR525730_Env-3 0.581982735954271 +ERR525779_Env-4 0.00011433191897853501 +ERR525767_Env-4 0.30377184049923 +ERR526064_Env-3 0.7084599140050459 +ERR525960_Env-3 0.00227884603818955 +ERR526079_Env-4 0.000108495358358547 +ERR525792_Env-3 0.00132179493582339 +ERR525969_Env-2 0.39957442830244505 +ERR526025_Env-2 0.886547005402008 +ERR525943_Env-4 0.000412344180010677 +ERR525948_Env-4 0.60916777722213 +ERR525931_Env-4 0.000140908215647153 +ERR525887_Env-2 0.0873152785211244 +ERR525827_Env-4 0.9785152417985201 +ERR525912_Env-3 0.000904551219010985 +ERR525795_Env-4 0.000249993580278431 +ERR525725_Env-4 0.00116037189744996 +ERR525771_Env-4 0.000114047296973777 +ERR525919_Env-4 0.00157559898240958 +ERR525723_Env-2 0.9850920895539691 +ERR525697_Env-4 0.0123094096417573 +ERR525860_Env-3 3.73380193409034e-05 +ERR526061_Env-2 0.8795882556039859 +ERR525777_Env-2 0.0627160474633871 +ERR525700_Env-3 0.275195248296836 +ERR525703_Env-3 0.17406000790047102 +ERR526048_Env-3 0.0605050934190865 +ERR525718_Env-2 0.558493929032184 +ERR526019_Env-4 0.0829439363498567 +ERR525871_Env-4 0.0006208433860047269 +ERR525987_Env-4 0.0004353909069304 +ERR525704_Env-2 0.822208869801631 +ERR525716_Env-4 2.10837383878511e-05 +ERR526016_Env-3 0.0012993440731919699 +ERR525748_Env-2 0.19842301875732396 +ERR526076_Env-3 0.147733996327359 +ERR525713_Env-3 0.00128294557254249 +ERR525722_Env-3 0.00016092137700776202 +ERR526065_Env-2 0.0312078523894724 +ERR525695_Env-2 0.955670553390244 +ERR525853_Env-2 0.970802578644004 +ERR525828_Env-3 0.296389313884037 +ERR525746_Env-4 0.6033832737994511 +ERR525881_Env-3 3.1244927624014e-05 +ERR525721_Env-2 0.695448782865369 +ERR525761_Env-2 0.258286966189466 +ERR525872_Env-3 0.31115078627993703 +ERR525785_Env-2 0.9573031744792031 +ERR525810_Env-3 9.060822628322741e-05 +ERR525908_Env-3 0.0874862172896512 +ERR525988_Env-3 0.00015425664409385602 +ERR525957_Env-2 0.5100685352713801 +ERR525799_Env-4 0.00469522119648444 +ERR525833_Env-2 0.8002260833899421 +ERR525772_Env-3 0.0188503794049421 +ERR525747_Env-3 0.000839964334550503 +ERR525755_Env-2 0.29739202063094394 +ERR525688_Env-3 0.00634189619262838 +ERR526077_Env-2 0.8474752841264359 +ERR526001_Env-2 0.08554564325128701 +Unknown 0.0379919371290767 0.257635669199371 0.0243726051416195 0.0359545190753939 0.0283434132317872 0.0385803927227859 0.00472648671982363 0.00466406126665634 0.0119489315986629 0.00466877798453709 0.0366432370033155 0.00865763054602605 0.110566730158669 0.0297285905676666 0.0592602257035396 0.0672396729494114 0.007765536450643459 0.0102953572118142 0.00691778259047549 0.0075587790397863 0.0267020318168091 0.0636101538074034 0.00929144024065954 0.08918070026367098 0.00111782183019574 0.0462554679878809 0.000710374426520645 0.00670922182343554 0.00468222418784583 0.0607650759796132 0.00263241250809775 0.0101047229133018 0.014301540960180001 0.0482064162740177 0.00252046280726563 0.0374744330048085 0.0279722865011367 0.0165698130227008 0.0139596215403077 0.0057764020413815795 0.0019607055751520697 0.0639709577555751 0.00133539500991025 0.282385097816319 0.00850545506500545 0.0306569928083903 0.040763790027567 0.0957495024709689 0.0366515745584945 0.0282682797913936 0.0165496606399842 0.0169013049659259 0.0763665810001636 0.00422143826102803 0.00244057984296273 0.00434135293943321 0.0464322424206222 0.0257288784813483 0.015126842711911002 0.0195116869283089 0.0281856617067504 0.0227032108213009 0.0123919722985769 0.0056508227899485 0.00868929991508863 0.00185492842214148 0.0331113993087981 0.007069631835982709 0.0425262581182741 0.0319468621111475 0.11102572819403199 0.0191594199924037 0.0228979830330969 0.00483848077979709 0.00782626814035962 0.0116064966966166 0.0409916316776856 0.0529764604322524 0.0178638541496479 0.039695228221938994 0.0041449170044807705 0.205993374498179 0.0031982658350694602 0.0181036224297054 0.0327741998209088 0.0020962247824514 0.0457675720247047 0.00942175597408536 0.0517633983762169 0.0126355304298411 0.0866738036134624 0.0261951006113872 0.0156196402695838 0.0033798536870896603 0.00373112229789754 0.0112485760834034 0.0135866171715736 diff --git a/q2_feast/tests/test_method.py b/q2_feast/tests/test_method.py new file mode 100644 index 0000000..d8fbfa1 --- /dev/null +++ b/q2_feast/tests/test_method.py @@ -0,0 +1,86 @@ +import os +import unittest +import pandas as pd +from biom import Table +from qiime2 import Artifact, Metadata +from q2_feast._method import microbialtracking +from numpy.testing import assert_allclose + + +class TestFEAST(unittest.TestCase): + + def setUp(self): + + in_dir = os.path.dirname(os.path.abspath(__file__)) + # path goes to tutorial data + def get_file(dir_, file_): return os.path.join(dir_, + os.pardir, + 'tutorials', + 'data', + 'backhed', + file_) + # path goes to tutorial data + def get_test(dir_, file_): return os.path.join(dir_, + 'data', + file_) + + # import multi test data + q2bt_multi = Artifact.load(get_file(in_dir, 'table-multi.qza')) + self.q2bt_multi = q2bt_multi.view(Table).to_dataframe().T + self.q2mf_multi = Metadata.load( + get_file(in_dir, 'metadata-multi.tsv')) + # perams + self.envcol = 'Env' + self.sourcesinkcol = 'SourceSink' + self.sourceids = 'Source' + self.sinkids = 'Sink' + self.sharedidcolumn = 'host_subject_id' + # expected + self.exp_mixed = pd.read_csv(get_test(in_dir, 'exp-mixed-mp.tsv'), + sep='\t', + index_col=0) + + def test_sourcetrack_multi(self): + + # run FEAST mixed source tracker (False is slow) + res_mpdf = microbialtracking(self.q2bt_multi, + self.q2mf_multi, + self.envcol, + self.sourcesinkcol, + self.sourceids, + self.sinkids, + self.sharedidcolumn, + different_sources = True, + em_iterations = 5000) + #tres_all.to_csv('/Users/cameronmartino/Downloads/testing-feast.tsv', sep='\t') + res_ = res_mpdf.loc['Unknown', + self.exp_mixed.columns].values + exp_ = self.exp_mixed.loc['Unknown', :].values + assert_allclose(res_, exp_, atol=.50) + + def test_sourcetrack_value_errors(self): + + # test missing id + with self.assertRaises(ValueError): + microbialtracking(self.q2bt_multi, + self.q2mf_multi, + self.envcol, + self.sourcesinkcol, + 'Sour', + self.sinkids, + self.sharedidcolumn) + + # test bad column + with self.assertRaises(ValueError): + microbialtracking(self.q2bt_multi, + self.q2mf_multi, + 'oh-no-bad-bad', + self.sourcesinkcol, + self.sourceids, + self.sinkids, + self.sharedidcolumn, + em_iterations=100) + + +if __name__ == "__main__": + unittest.main() diff --git a/q2_feast/tutorials/backhed-tutorial.md b/q2_feast/tutorials/backhed-tutorial.md new file mode 100644 index 0000000..facb995 --- /dev/null +++ b/q2_feast/tutorials/backhed-tutorial.md @@ -0,0 +1,48 @@ + +# Tutorial +**Note**: This guide assumes you have installed QIIME2 using one of the procedures in the [install documents](https://docs.qiime2.org/2019.7/install/) and have installed FEAST. + + +## Introduction + +In this tutorial you will learn how to perform and interpert microbial source tracking through QIIME2. + +FEAST is a highly efficient Expectation-Maximization-based method that takes as input a microbial community (called the sink) as well as a separate group of potential source environments (called the sources) and estimates the fraction of the sink community that was contributed by each of the source environments. By virtue of these mixing proportions often summing to less than the entire sink, FEAST also reports the potential fraction of the sink attributed to other origins, collectively referred to as the unknown source. The statistical model used by FEAST assumes each sink is a convex combination of known and unknown sources. FEAST is agnostic to the sequencing data type (i.e., 16s rRNA or shotgun sequencing), and can efficiently estimate up to thousands of source contributions to a sample. In this tutorial we applied FEAST to two real datasets in order to demonstrate the utility of microbial source tracking methods across different contexts. + + +### Example 1 +We first use FEAST in the context of a time-series. Using FEAST for time-series analysis offers a quantitative way to characterize developmental microbial populations, such as the infant gut. In this context, we can leverage previous time-points and external sources to understand the origins of a specific, temporal community state. For instance, we can estimate if taxa in the infant gut originate from the birth canal, or if they are derived from some other external source at a later time point. To demonstrate this capability, we used a subset of the longitudinal data from Backhed et al. 2015, which contains gut microbiome samples from infants as well as from their corresponding mothers. In this analysis, we treated samples taken from the infants at age 12 months as sinks, considering respective earlier time points and maternal samples as sources. + + +We provide a dataset for this example. Download the demo files here. + +To run FEAST with this example data: + +```shell +qiime feast microbialtracking \ + --i-table data/backhed/table-multi.qza \ + --m-metadata-file data/backhed/metadata-multi.tsv \ + --p-environment-column Env \ + --p-source-sink-column SourceSink \ + --p-source-ids Source \ + --p-sink-ids Sink \ + --p-shared-id-column host_subject_id \ + --p-em-iterations 1000 \ + --p-different-sources \ + --o-proportions data/backhed/mixing-proportions.qza +``` +```Saved FeatureTable[Frequency] to: data/backhed/tackingresults.qza``` + +The output is an S1 by S2 matrix P, where S1 is the number sinks and S2 is the number of sources (including an unknown source). Each row in matrix P sums to 1. + +We can visualize these results using a stacked barplot provided in FEAST. + +```shell +qiime feast barplot \ + --i-mixing-proportions data/backhed/mixing-proportions.qza\ + --m-metadata-file data/backhed/metadata-multi.tsv \ + --o-visualization data/backhed/barplot.qzv +``` +```Saved FeatureTable[Frequency] to: data/backhed/barplot.qzv``` + +![](etc/backhed-barplot.png) diff --git a/q2_feast/tutorials/data/backhed/barplot.qzv b/q2_feast/tutorials/data/backhed/barplot.qzv new file mode 100644 index 0000000..7e289db Binary files /dev/null and b/q2_feast/tutorials/data/backhed/barplot.qzv differ diff --git a/q2_feast/tutorials/data/backhed/metadata-multi.tsv b/q2_feast/tutorials/data/backhed/metadata-multi.tsv new file mode 100644 index 0000000..425394e --- /dev/null +++ b/q2_feast/tutorials/data/backhed/metadata-multi.tsv @@ -0,0 +1,389 @@ +#SampleID Env SourceSink host_subject_id +#q2:types categorical categorical numeric +ERR525698 Env_1 Sink 1 +ERR525693 Env_2 Source 1 +ERR525688 Env_3 Source 1 +ERR525699 Env_4 Source 1 +ERR525910 Env_1 Sink 2 +ERR525909 Env_2 Source 2 +ERR525908 Env_3 Source 2 +ERR525911 Env_4 Source 2 +ERR525954 Env_1 Sink 3 +ERR525949 Env_2 Source 3 +ERR525944 Env_3 Source 3 +ERR525955 Env_4 Source 3 +ERR526078 Env_1 Sink 4 +ERR526077 Env_2 Source 4 +ERR526076 Env_3 Source 4 +ERR526079 Env_4 Source 4 +ERR525719 Env_1 Sink 5 +ERR525718 Env_2 Source 5 +ERR525717 Env_3 Source 5 +ERR525720 Env_4 Source 5 +ERR525846 Env_1 Sink 6 +ERR525845 Env_2 Source 6 +ERR525844 Env_3 Source 6 +ERR525847 Env_4 Source 6 +ERR525966 Env_1 Sink 7 +ERR525965 Env_2 Source 7 +ERR525964 Env_3 Source 7 +ERR525967 Env_4 Source 7 +ERR525998 Env_1 Sink 8 +ERR525997 Env_2 Source 8 +ERR525996 Env_3 Source 8 +ERR525999 Env_4 Source 8 +ERR525691 Env_1 Sink 9 +ERR525690 Env_2 Source 9 +ERR525689 Env_3 Source 9 +ERR525692 Env_4 Source 9 +ERR525707 Env_1 Sink 10 +ERR525702 Env_2 Source 10 +ERR525701 Env_3 Source 10 +ERR525708 Env_4 Source 10 +ERR525724 Env_1 Sink 11 +ERR525723 Env_2 Source 11 +ERR525722 Env_3 Source 11 +ERR525725 Env_4 Source 11 +ERR525732 Env_1 Sink 12 +ERR525731 Env_2 Source 12 +ERR525730 Env_3 Source 12 +ERR525733 Env_4 Source 12 +ERR525752 Env_1 Sink 13 +ERR525750 Env_2 Source 13 +ERR525743 Env_3 Source 13 +ERR525753 Env_4 Source 13 +ERR525803 Env_1 Sink 14 +ERR525802 Env_2 Source 14 +ERR525801 Env_3 Source 14 +ERR525804 Env_4 Source 14 +ERR525818 Env_1 Sink 15 +ERR525817 Env_2 Source 15 +ERR525816 Env_3 Source 15 +ERR525819 Env_4 Source 15 +ERR525838 Env_1 Sink 16 +ERR525837 Env_2 Source 16 +ERR525836 Env_3 Source 16 +ERR525839 Env_4 Source 16 +ERR525870 Env_1 Sink 18 +ERR525869 Env_2 Source 18 +ERR525868 Env_3 Source 18 +ERR525871 Env_4 Source 18 +ERR525906 Env_1 Sink 19 +ERR525905 Env_2 Source 19 +ERR525904 Env_3 Source 19 +ERR525907 Env_4 Source 19 +ERR525990 Env_1 Sink 20 +ERR525989 Env_2 Source 20 +ERR525988 Env_3 Source 20 +ERR525991 Env_4 Source 20 +ERR526006 Env_1 Sink 21 +ERR526005 Env_2 Source 21 +ERR526004 Env_3 Source 21 +ERR526007 Env_4 Source 21 +ERR526010 Env_1 Sink 22 +ERR526009 Env_2 Source 22 +ERR526008 Env_3 Source 22 +ERR526011 Env_4 Source 22 +ERR526022 Env_1 Sink 23 +ERR526021 Env_2 Source 23 +ERR526020 Env_3 Source 23 +ERR526023 Env_4 Source 23 +ERR526026 Env_1 Sink 24 +ERR526025 Env_2 Source 24 +ERR526024 Env_3 Source 24 +ERR526027 Env_4 Source 24 +ERR526030 Env_1 Sink 25 +ERR526029 Env_2 Source 25 +ERR526028 Env_3 Source 25 +ERR526031 Env_4 Source 25 +ERR526058 Env_1 Sink 26 +ERR526057 Env_2 Source 26 +ERR526056 Env_3 Source 26 +ERR526059 Env_4 Source 26 +ERR526066 Env_1 Sink 27 +ERR526065 Env_2 Source 27 +ERR526064 Env_3 Source 27 +ERR526067 Env_4 Source 27 +ERR526082 Env_1 Sink 28 +ERR526081 Env_2 Source 28 +ERR526080 Env_3 Source 28 +ERR526083 Env_4 Source 28 +ERR525758 Env_1 Sink 29 +ERR525721 Env_2 Source 29 +ERR525700 Env_3 Source 29 +ERR525759 Env_4 Source 29 +ERR525696 Env_1 Sink 30 +ERR525695 Env_2 Source 30 +ERR525694 Env_3 Source 30 +ERR525697 Env_4 Source 30 +ERR525705 Env_1 Sink 31 +ERR525704 Env_2 Source 31 +ERR525703 Env_3 Source 31 +ERR525715 Env_1 Sink 32 +ERR525714 Env_2 Source 32 +ERR525713 Env_3 Source 32 +ERR525716 Env_4 Source 32 +ERR525736 Env_1 Sink 33 +ERR525735 Env_2 Source 33 +ERR525734 Env_3 Source 33 +ERR525737 Env_4 Source 33 +ERR525745 Env_1 Sink 34 +ERR525744 Env_2 Source 34 +ERR525742 Env_3 Source 34 +ERR525746 Env_4 Source 34 +ERR525749 Env_1 Sink 35 +ERR525748 Env_2 Source 35 +ERR525747 Env_3 Source 35 +ERR525751 Env_4 Source 35 +ERR525756 Env_1 Sink 36 +ERR525755 Env_2 Source 36 +ERR525754 Env_3 Source 36 +ERR525757 Env_4 Source 36 +ERR525762 Env_1 Sink 37 +ERR525761 Env_2 Source 37 +ERR525760 Env_3 Source 37 +ERR525763 Env_4 Source 37 +ERR525770 Env_1 Sink 38 +ERR525769 Env_2 Source 38 +ERR525768 Env_3 Source 38 +ERR525771 Env_4 Source 38 +ERR525774 Env_1 Sink 39 +ERR525773 Env_2 Source 39 +ERR525772 Env_3 Source 39 +ERR525775 Env_4 Source 39 +ERR525778 Env_1 Sink 40 +ERR525777 Env_2 Source 40 +ERR525776 Env_3 Source 40 +ERR525779 Env_4 Source 40 +ERR525786 Env_1 Sink 41 +ERR525785 Env_2 Source 41 +ERR525784 Env_3 Source 41 +ERR525787 Env_4 Source 41 +ERR525790 Env_1 Sink 42 +ERR525789 Env_2 Source 42 +ERR525788 Env_3 Source 42 +ERR525791 Env_4 Source 42 +ERR525794 Env_1 Sink 43 +ERR525793 Env_2 Source 43 +ERR525792 Env_3 Source 43 +ERR525795 Env_4 Source 43 +ERR525798 Env_1 Sink 44 +ERR525797 Env_2 Source 44 +ERR525796 Env_3 Source 44 +ERR525799 Env_4 Source 44 +ERR525808 Env_1 Sink 45 +ERR525807 Env_2 Source 45 +ERR525806 Env_3 Source 45 +ERR525809 Env_4 Source 45 +ERR525812 Env_1 Sink 46 +ERR525811 Env_2 Source 46 +ERR525810 Env_3 Source 46 +ERR525813 Env_4 Source 46 +ERR525822 Env_1 Sink 47 +ERR525821 Env_2 Source 47 +ERR525820 Env_3 Source 47 +ERR525823 Env_4 Source 47 +ERR525830 Env_1 Sink 48 +ERR525829 Env_2 Source 48 +ERR525828 Env_3 Source 48 +ERR525831 Env_4 Source 48 +ERR525834 Env_1 Sink 49 +ERR525833 Env_2 Source 49 +ERR525832 Env_3 Source 49 +ERR525835 Env_4 Source 49 +ERR525850 Env_1 Sink 50 +ERR525849 Env_2 Source 50 +ERR525848 Env_3 Source 50 +ERR525851 Env_4 Source 50 +ERR525854 Env_1 Sink 51 +ERR525853 Env_2 Source 51 +ERR525852 Env_3 Source 51 +ERR525855 Env_4 Source 51 +ERR525858 Env_1 Sink 52 +ERR525857 Env_2 Source 52 +ERR525856 Env_3 Source 52 +ERR525859 Env_4 Source 52 +ERR525862 Env_1 Sink 53 +ERR525861 Env_2 Source 53 +ERR525860 Env_3 Source 53 +ERR525863 Env_4 Source 53 +ERR525874 Env_1 Sink 54 +ERR525873 Env_2 Source 54 +ERR525872 Env_3 Source 54 +ERR525875 Env_4 Source 54 +ERR525878 Env_1 Sink 55 +ERR525877 Env_2 Source 55 +ERR525876 Env_3 Source 55 +ERR525879 Env_4 Source 55 +ERR525894 Env_1 Sink 56 +ERR525885 Env_2 Source 56 +ERR525880 Env_3 Source 56 +ERR525895 Env_4 Source 56 +ERR525902 Env_1 Sink 57 +ERR525897 Env_2 Source 57 +ERR525896 Env_3 Source 57 +ERR525903 Env_4 Source 57 +ERR525900 Env_1 Sink 58 +ERR525899 Env_2 Source 58 +ERR525898 Env_3 Source 58 +ERR525901 Env_4 Source 58 +ERR525914 Env_1 Sink 59 +ERR525913 Env_2 Source 59 +ERR525912 Env_3 Source 59 +ERR525915 Env_4 Source 59 +ERR525922 Env_1 Sink 60 +ERR525921 Env_2 Source 60 +ERR525920 Env_3 Source 60 +ERR525923 Env_4 Source 60 +ERR525934 Env_1 Sink 61 +ERR525933 Env_2 Source 61 +ERR525932 Env_3 Source 61 +ERR525935 Env_4 Source 61 +ERR525938 Env_1 Sink 62 +ERR525937 Env_2 Source 62 +ERR525936 Env_3 Source 62 +ERR525939 Env_4 Source 62 +ERR525947 Env_1 Sink 63 +ERR525946 Env_2 Source 63 +ERR525945 Env_3 Source 63 +ERR525948 Env_4 Source 63 +ERR525958 Env_1 Sink 64 +ERR525957 Env_2 Source 64 +ERR525956 Env_3 Source 64 +ERR525959 Env_4 Source 64 +ERR525962 Env_1 Sink 65 +ERR525961 Env_2 Source 65 +ERR525960 Env_3 Source 65 +ERR525963 Env_4 Source 65 +ERR525970 Env_1 Sink 66 +ERR525969 Env_2 Source 66 +ERR525968 Env_3 Source 66 +ERR525971 Env_4 Source 66 +ERR525974 Env_1 Sink 67 +ERR525973 Env_2 Source 67 +ERR525972 Env_3 Source 67 +ERR525975 Env_4 Source 67 +ERR525982 Env_1 Sink 68 +ERR525981 Env_2 Source 68 +ERR525980 Env_3 Source 68 +ERR525983 Env_4 Source 68 +ERR525986 Env_1 Sink 69 +ERR525985 Env_2 Source 69 +ERR525984 Env_3 Source 69 +ERR525987 Env_4 Source 69 +ERR526014 Env_1 Sink 70 +ERR526013 Env_2 Source 70 +ERR526012 Env_3 Source 70 +ERR526015 Env_4 Source 70 +ERR526018 Env_1 Sink 71 +ERR526017 Env_2 Source 71 +ERR526016 Env_3 Source 71 +ERR526019 Env_4 Source 71 +ERR526034 Env_1 Sink 72 +ERR526033 Env_2 Source 72 +ERR526032 Env_3 Source 72 +ERR526035 Env_4 Source 72 +ERR526042 Env_1 Sink 73 +ERR526041 Env_2 Source 73 +ERR526040 Env_3 Source 73 +ERR526043 Env_4 Source 73 +ERR526046 Env_1 Sink 74 +ERR526045 Env_2 Source 74 +ERR526044 Env_3 Source 74 +ERR526047 Env_4 Source 74 +ERR526054 Env_1 Sink 75 +ERR526053 Env_2 Source 75 +ERR526052 Env_3 Source 75 +ERR526055 Env_4 Source 75 +ERR526072 Env_1 Sink 76 +ERR526071 Env_2 Source 76 +ERR526070 Env_3 Source 76 +ERR526073 Env_4 Source 76 +ERR525711 Env_1 Sink 77 +ERR525710 Env_2 Source 77 +ERR525709 Env_3 Source 77 +ERR525712 Env_4 Source 77 +ERR525728 Env_1 Sink 78 +ERR525727 Env_2 Source 78 +ERR525726 Env_3 Source 78 +ERR525729 Env_4 Source 78 +ERR525766 Env_1 Sink 79 +ERR525765 Env_2 Source 79 +ERR525764 Env_3 Source 79 +ERR525767 Env_4 Source 79 +ERR525782 Env_1 Sink 80 +ERR525781 Env_2 Source 80 +ERR525780 Env_3 Source 80 +ERR525783 Env_4 Source 80 +ERR525866 Env_1 Sink 81 +ERR525865 Env_2 Source 81 +ERR525864 Env_3 Source 81 +ERR525867 Env_4 Source 81 +ERR525927 Env_1 Sink 82 +ERR525926 Env_2 Source 82 +ERR525924 Env_3 Source 82 +ERR525928 Env_4 Source 82 +ERR525994 Env_1 Sink 83 +ERR525993 Env_2 Source 83 +ERR525992 Env_3 Source 83 +ERR525995 Env_4 Source 83 +ERR526038 Env_1 Sink 84 +ERR526037 Env_2 Source 84 +ERR526036 Env_3 Source 84 +ERR526039 Env_4 Source 84 +ERR526086 Env_1 Sink 85 +ERR526085 Env_2 Source 85 +ERR526084 Env_3 Source 85 +ERR526087 Env_4 Source 85 +ERR525740 Env_1 Sink 86 +ERR525739 Env_2 Source 86 +ERR525738 Env_3 Source 86 +ERR525741 Env_4 Source 86 +ERR525814 Env_1 Sink 87 +ERR525805 Env_2 Source 87 +ERR525800 Env_3 Source 87 +ERR525815 Env_4 Source 87 +ERR525826 Env_1 Sink 88 +ERR525825 Env_2 Source 88 +ERR525824 Env_3 Source 88 +ERR525827 Env_4 Source 88 +ERR525883 Env_1 Sink 89 +ERR525882 Env_2 Source 89 +ERR525881 Env_3 Source 89 +ERR525884 Env_4 Source 89 +ERR525888 Env_1 Sink 90 +ERR525887 Env_2 Source 90 +ERR525886 Env_3 Source 90 +ERR525889 Env_4 Source 90 +ERR525892 Env_1 Sink 91 +ERR525891 Env_2 Source 91 +ERR525890 Env_3 Source 91 +ERR525893 Env_4 Source 91 +ERR525918 Env_1 Sink 92 +ERR525917 Env_2 Source 92 +ERR525916 Env_3 Source 92 +ERR525919 Env_4 Source 92 +ERR525930 Env_1 Sink 93 +ERR525929 Env_2 Source 93 +ERR525925 Env_3 Source 93 +ERR525931 Env_4 Source 93 +ERR525942 Env_1 Sink 94 +ERR525941 Env_2 Source 94 +ERR525940 Env_3 Source 94 +ERR525943 Env_4 Source 94 +ERR525952 Env_1 Sink 95 +ERR525951 Env_2 Source 95 +ERR525950 Env_3 Source 95 +ERR525953 Env_4 Source 95 +ERR526002 Env_1 Sink 96 +ERR526001 Env_2 Source 96 +ERR526000 Env_3 Source 96 +ERR526003 Env_4 Source 96 +ERR526050 Env_1 Sink 97 +ERR526049 Env_2 Source 97 +ERR526048 Env_3 Source 97 +ERR526051 Env_4 Source 97 +ERR526062 Env_1 Sink 98 +ERR526061 Env_2 Source 98 +ERR526060 Env_3 Source 98 +ERR526063 Env_4 Source 98 diff --git a/q2_feast/tutorials/data/backhed/mixing-proportions.qza b/q2_feast/tutorials/data/backhed/mixing-proportions.qza new file mode 100644 index 0000000..8a07f19 Binary files /dev/null and b/q2_feast/tutorials/data/backhed/mixing-proportions.qza differ diff --git a/q2_feast/tutorials/data/backhed/table-multi.qza b/q2_feast/tutorials/data/backhed/table-multi.qza new file mode 100644 index 0000000..1eab94b Binary files /dev/null and b/q2_feast/tutorials/data/backhed/table-multi.qza differ diff --git a/q2_feast/tutorials/etc/backhed-barplot.png b/q2_feast/tutorials/etc/backhed-barplot.png new file mode 100644 index 0000000..0d15eec Binary files /dev/null and b/q2_feast/tutorials/etc/backhed-barplot.png differ diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..cb01822 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,8 @@ +[versioneer] +VCS=git +style=pep440 +versionfile_source = q2_feast/_version.py +versionfile_build = q2_feast/_version.py +tag_prefix = 0.1.0 +parentdir_prefix = q2_feast- + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..9f2fde4 --- /dev/null +++ b/setup.py @@ -0,0 +1,49 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2019, FEAST development team. +# +# Distributed under the terms of the Modified cc-by-sa-4.0 License. +# +# The full license is in the file LICENSE, distributed with this software. +# ---------------------------------------------------------------------------- +# Note that this file doesn't declare any install_requires packages -- this is +# because q2-FEAST assumes that it's being installed into a "normal" QIIME 2 +# conda environment, and thus that all of the following +# (not-in-the-standard-python-library) packages will be available: +# - pandas +# - numpy +# - biom +# - qiime2 +# - q2_types +# - q2_taxa +# ... However, this file does declare some packages under extra_requires, which +# should only be needed when running tests. + +import versioneer +from setuptools import setup, find_packages + +setup( + name="feast", + version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), + packages=find_packages(), + author="Liat Shenhav", + author_email="liashenhav@gmail.com", + description="Fast Expectation-mAximization microbial Source Tracking (FEAST)", + license='cc-by-sa-4.0', + url="https://github.com/cozygene/FEAST", + # idiom based on https://github.com/altair-viz/altair/blob/master/setup.py + extras_require={ + "dev": [ + "nose", + "coverage" + ] + }, + entry_points={ + 'qiime2.plugins': ['feast=q2_feast.plugin_setup:plugin'] + }, + scripts=['q2_feast/assets/source_tracking.R'], + package_data={ + "q2_feast": ['citations.bib'], + }, + zip_safe=False, +) diff --git a/src/FEAST.so b/src/FEAST.so deleted file mode 100644 index b4e1e54..0000000 Binary files a/src/FEAST.so and /dev/null differ diff --git a/src/RcppExports.o b/src/RcppExports.o deleted file mode 100644 index fed5819..0000000 Binary files a/src/RcppExports.o and /dev/null differ diff --git a/src/init.o b/src/init.o deleted file mode 100644 index be06bf7..0000000 Binary files a/src/init.o and /dev/null differ diff --git a/src/rcppSchur.o b/src/rcppSchur.o deleted file mode 100644 index 618bd3d..0000000 Binary files a/src/rcppSchur.o and /dev/null differ diff --git a/versioneer.py b/versioneer.py new file mode 100644 index 0000000..45d9386 --- /dev/null +++ b/versioneer.py @@ -0,0 +1,1825 @@ +# Version: 0.18 +# flake8: noqa + +"""The Versioneer - like a rocketeer, but for versions. + +The Versioneer +============== + +* like a rocketeer, but for versions! +* https://github.com/warner/python-versioneer +* Brian Warner +* License: Public Domain +* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy +* [![Latest Version] +(https://pypip.in/version/versioneer/badge.svg?style=flat) +](https://pypi.python.org/pypi/versioneer/) +* [![Build Status] +(https://travis-ci.org/warner/python-versioneer.png?branch=master) +](https://travis-ci.org/warner/python-versioneer) + +This is a tool for managing a recorded version number in distutils-based +python projects. The goal is to remove the tedious and error-prone "update +the embedded version string" step from your release process. Making a new +release should be as easy as recording a new tag in your version-control +system, and maybe making new tarballs. + + +## Quick Install + +* `pip install versioneer` to somewhere to your $PATH +* add a `[versioneer]` section to your setup.cfg (see below) +* run `versioneer install` in your source tree, commit the results + +## Version Identifiers + +Source trees come from a variety of places: + +* a version-control system checkout (mostly used by developers) +* a nightly tarball, produced by build automation +* a snapshot tarball, produced by a web-based VCS browser, like github's + "tarball from tag" feature +* a release tarball, produced by "setup.py sdist", distributed through PyPI + +Within each source tree, the version identifier (either a string or a number, +this tool is format-agnostic) can come from a variety of places: + +* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows + about recent "tags" and an absolute revision-id +* the name of the directory into which the tarball was unpacked +* an expanded VCS keyword ($Id$, etc) +* a `_version.py` created by some earlier build step + +For released software, the version identifier is closely related to a VCS +tag. Some projects use tag names that include more than just the version +string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool +needs to strip the tag prefix to extract the version identifier. For +unreleased software (between tags), the version identifier should provide +enough information to help developers recreate the same tree, while also +giving them an idea of roughly how old the tree is (after version 1.2, before +version 1.3). Many VCS systems can report a description that captures this, +for example `git describe --tags --dirty --always` reports things like +"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the +0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has +uncommitted changes. + +The version identifier is used for multiple purposes: + +* to allow the module to self-identify its version: `myproject.__version__` +* to choose a name and prefix for a 'setup.py sdist' tarball + +## Theory of Operation + +Versioneer works by adding a special `_version.py` file into your source +tree, where your `__init__.py` can import it. This `_version.py` knows how to +dynamically ask the VCS tool for version information at import time. + +`_version.py` also contains `$Revision$` markers, and the installation +process marks `_version.py` to have this marker rewritten with a tag name +during the `git archive` command. As a result, generated tarballs will +contain enough information to get the proper version. + +To allow `setup.py` to compute a version too, a `versioneer.py` is added to +the top level of your source tree, next to `setup.py` and the `setup.cfg` +that configures it. This overrides several distutils/setuptools commands to +compute the version when invoked, and changes `setup.py build` and `setup.py +sdist` to replace `_version.py` with a small static file that contains just +the generated version data. + +## Installation + +See [INSTALL.md](./INSTALL.md) for detailed installation instructions. + +## Version-String Flavors + +Code which uses Versioneer can learn about its version string at runtime by +importing `_version` from your main `__init__.py` file and running the +`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can +import the top-level `versioneer.py` and run `get_versions()`. + +Both functions return a dictionary with different flavors of version +information: + +* `['version']`: A condensed version string, rendered using the selected + style. This is the most commonly used value for the project's version + string. The default "pep440" style yields strings like `0.11`, + `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section + below for alternative styles. + +* `['full-revisionid']`: detailed revision identifier. For Git, this is the + full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". + +* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the + commit date in ISO 8601 format. This will be None if the date is not + available. + +* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that + this is only accurate if run in a VCS checkout, otherwise it is likely to + be False or None + +* `['error']`: if the version string could not be computed, this will be set + to a string describing the problem, otherwise it will be None. It may be + useful to throw an exception in setup.py if this is set, to avoid e.g. + creating tarballs with a version string of "unknown". + +Some variants are more useful than others. Including `full-revisionid` in a +bug report should allow developers to reconstruct the exact code being tested +(or indicate the presence of local changes that should be shared with the +developers). `version` is suitable for display in an "about" box or a CLI +`--version` output: it can be easily compared against release notes and lists +of bugs fixed in various releases. + +The installer adds the following text to your `__init__.py` to place a basic +version in `YOURPROJECT.__version__`: + + from ._version import get_versions + __version__ = get_versions()['version'] + del get_versions + +## Styles + +The setup.cfg `style=` configuration controls how the VCS information is +rendered into a version string. + +The default style, "pep440", produces a PEP440-compliant string, equal to the +un-prefixed tag name for actual releases, and containing an additional "local +version" section with more detail for in-between builds. For Git, this is +TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags +--dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the +tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and +that this commit is two revisions ("+2") beyond the "0.11" tag. For released +software (exactly equal to a known tag), the identifier will only contain the +stripped tag, e.g. "0.11". + +Other styles are available. See [details.md](details.md) in the Versioneer +source tree for descriptions. + +## Debugging + +Versioneer tries to avoid fatal errors: if something goes wrong, it will tend +to return a version of "0+unknown". To investigate the problem, run `setup.py +version`, which will run the version-lookup code in a verbose mode, and will +display the full contents of `get_versions()` (including the `error` string, +which may help identify what went wrong). + +## Known Limitations + +Some situations are known to cause problems for Versioneer. This details the +most significant ones. More can be found on Github +[issues page](https://github.com/warner/python-versioneer/issues). + +### Subprojects + +Versioneer has limited support for source trees in which `setup.py` is not in +the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are +two common reasons why `setup.py` might not be in the root: + +* Source trees which contain multiple subprojects, such as + [Buildbot](https://github.com/buildbot/buildbot), which contains both + "master" and "slave" subprojects, each with their own `setup.py`, + `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI + distributions (and upload multiple independently-installable tarballs). +* Source trees whose main purpose is to contain a C library, but which also + provide bindings to Python (and perhaps other langauges) in subdirectories. + +Versioneer will look for `.git` in parent directories, and most operations +should get the right version string. However `pip` and `setuptools` have bugs +and implementation details which frequently cause `pip install .` from a +subproject directory to fail to find a correct version string (so it usually +defaults to `0+unknown`). + +`pip install --editable .` should work correctly. `setup.py install` might +work too. + +Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in +some later version. + +[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking +this issue. The discussion in +[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the +issue from the Versioneer side in more detail. +[pip PR#3176](https://github.com/pypa/pip/pull/3176) and +[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve +pip to let Versioneer work correctly. + +Versioneer-0.16 and earlier only looked for a `.git` directory next to the +`setup.cfg`, so subprojects were completely unsupported with those releases. + +### Editable installs with setuptools <= 18.5 + +`setup.py develop` and `pip install --editable .` allow you to install a +project into a virtualenv once, then continue editing the source code (and +test) without re-installing after every change. + +"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a +convenient way to specify executable scripts that should be installed along +with the python package. + +These both work as expected when using modern setuptools. When using +setuptools-18.5 or earlier, however, certain operations will cause +`pkg_resources.DistributionNotFound` errors when running the entrypoint +script, which must be resolved by re-installing the package. This happens +when the install happens with one version, then the egg_info data is +regenerated while a different version is checked out. Many setup.py commands +cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into +a different virtualenv), so this can be surprising. + +[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes +this one, but upgrading to a newer version of setuptools should probably +resolve it. + +### Unicode version strings + +While Versioneer works (and is continually tested) with both Python 2 and +Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. +Newer releases probably generate unicode version strings on py2. It's not +clear that this is wrong, but it may be surprising for applications when then +write these strings to a network connection or include them in bytes-oriented +APIs like cryptographic checksums. + +[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates +this question. + + +## Updating Versioneer + +To upgrade your project to a new release of Versioneer, do the following: + +* install the new Versioneer (`pip install -U versioneer` or equivalent) +* edit `setup.cfg`, if necessary, to include any new configuration settings + indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install` in your source tree, to replace + `SRC/_version.py` +* commit any changed files + +## Future Directions + +This tool is designed to make it easily extended to other version-control +systems: all VCS-specific components are in separate directories like +src/git/ . The top-level `versioneer.py` script is assembled from these +components by running make-versioneer.py . In the future, make-versioneer.py +will take a VCS name as an argument, and will construct a version of +`versioneer.py` that is specific to the given VCS. It might also take the +configuration arguments that are currently provided manually during +installation by editing setup.py . Alternatively, it might go the other +direction and include code from all supported VCS systems, reducing the +number of intermediate scripts. + + +## License + +To make Versioneer easier to embed, all its code is dedicated to the public +domain. The `_version.py` that it creates is also in the public domain. +Specifically, both are released under the Creative Commons "Public Domain +Dedication" license (CC0-1.0), as described in +https://creativecommons.org/publicdomain/zero/1.0/ . + +""" + +from __future__ import print_function +try: + import configparser +except ImportError: + import ConfigParser as configparser +import errno +import json +import os +import re +import subprocess +import sys + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_root(): + """Get the project root directory. + + We require that all commands are run from the project root, i.e. the + directory that contains setup.py, setup.cfg, and versioneer.py . + """ + root = os.path.realpath(os.path.abspath(os.getcwd())) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + # allow 'python path/to/setup.py COMMAND' + root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + err = ("Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND').") + raise VersioneerBadRootError(err) + try: + # Certain runtime workflows (setup.py install/develop in a setuptools + # tree) execute all dependencies in a single python process, so + # "versioneer" may be imported multiple times, and python's shared + # module-import table will cache the first one. So we can't use + # os.path.dirname(__file__), as that will find whichever + # versioneer.py was first imported, even in later projects. + me = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(me)[0]) + vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) + if me_dir != vsr_dir: + print("Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(me), versioneer_py)) + except NameError: + pass + return root + + +def get_config_from_root(root): + """Read the project setup.cfg file to determine Versioneer config.""" + # This might raise EnvironmentError (if setup.cfg is missing), or + # configparser.NoSectionError (if it lacks a [versioneer] section), or + # configparser.NoOptionError (if it lacks "VCS="). See the docstring at + # the top of versioneer.py for instructions on writing your setup.cfg . + setup_cfg = os.path.join(root, "setup.cfg") + parser = configparser.SafeConfigParser() + with open(setup_cfg, "r") as f: + parser.readfp(f) + VCS = parser.get("versioneer", "VCS") # mandatory + + def get(parser, name): + if parser.has_option("versioneer", name): + return parser.get("versioneer", name) + return None + cfg = VersioneerConfig() + cfg.VCS = VCS + cfg.style = get(parser, "style") or "" + cfg.versionfile_source = get(parser, "versionfile_source") + cfg.versionfile_build = get(parser, "versionfile_build") + cfg.tag_prefix = get(parser, "tag_prefix") + if cfg.tag_prefix in ("''", '""'): + cfg.tag_prefix = "" + cfg.parentdir_prefix = get(parser, "parentdir_prefix") + cfg.verbose = get(parser, "verbose") + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +# these dictionaries contain VCS-specific tools +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + + +LONG_VERSION_PY['git'] = ''' +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.18 (https://github.com/warner/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" + git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" + git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "%(STYLE)s" + cfg.tag_prefix = "%(TAG_PREFIX)s" + cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" + cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %%s" %% dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %%s" %% (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %%s (error)" %% dispcmd) + print("stdout was %%s" %% stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %%s but none started with prefix %%s" %% + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %%d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%%s', no digits" %% ",".join(refs - tags)) + if verbose: + print("likely tags: %%s" %% ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %%s" %% r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %%s not under git control" %% root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%%s*" %% tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%%s'" + %% describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%%s' doesn't start with prefix '%%s'" + print(fmt %% (full_tag, tag_prefix)) + pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" + %% (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%%d" %% pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%%d" %% pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%%s'" %% style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} +''' + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs - tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def do_vcs_install(manifest_in, versionfile_source, ipy): + """Git-specific installation logic for Versioneer. + + For Git, this means creating/changing .gitattributes to mark _version.py + for export-subst keyword substitution. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + files = [manifest_in, versionfile_source] + if ipy: + files.append(ipy) + try: + me = __file__ + if me.endswith(".pyc") or me.endswith(".pyo"): + me = os.path.splitext(me)[0] + ".py" + versioneer_file = os.path.relpath(me) + except NameError: + versioneer_file = "versioneer.py" + files.append(versioneer_file) + present = False + try: + f = open(".gitattributes", "r") + for line in f.readlines(): + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + f.close() + except EnvironmentError: + pass + if not present: + f = open(".gitattributes", "a+") + f.write("%s export-subst\n" % versionfile_source) + f.close() + files.append(".gitattributes") + run_command(GITS, ["add", "--"] + files) + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +SHORT_VERSION_PY = """ +# This file was generated by 'versioneer.py' (0.18) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +import json + +version_json = ''' +%s +''' # END VERSION_JSON + + +def get_versions(): + return json.loads(version_json) +""" + + +def versions_from_file(filename): + """Try to determine the version from _version.py if present.""" + try: + with open(filename) as f: + contents = f.read() + except EnvironmentError: + raise NotThisMethod("unable to read _version.py") + mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + raise NotThisMethod("no version_json in _version.py") + return json.loads(mo.group(1)) + + +def write_to_version_file(filename, versions): + """Write the given version number to the given _version.py file.""" + os.unlink(filename) + contents = json.dumps(versions, sort_keys=True, + indent=1, separators=(",", ": ")) + with open(filename, "w") as f: + f.write(SHORT_VERSION_PY % contents) + + print("set %s to '%s'" % (filename, versions["version"])) + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +class VersioneerBadRootError(Exception): + """The project root directory is unknown or missing key files.""" + + +def get_versions(verbose=False): + """Get the project version from whatever source is available. + + Returns dict with two keys: 'version' and 'full'. + """ + if "versioneer" in sys.modules: + # see the discussion in cmdclass.py:get_cmdclass() + del sys.modules["versioneer"] + + root = get_root() + cfg = get_config_from_root(root) + + assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" + handlers = HANDLERS.get(cfg.VCS) + assert handlers, "unrecognized VCS '%s'" % cfg.VCS + verbose = verbose or cfg.verbose + assert cfg.versionfile_source is not None, \ + "please set versioneer.versionfile_source" + assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" + + versionfile_abs = os.path.join(root, cfg.versionfile_source) + + # extract version from first of: _version.py, VCS command (e.g. 'git + # describe'), parentdir. This is meant to work for developers using a + # source checkout, for users of a tarball created by 'setup.py sdist', + # and for users of a tarball/zipball created by 'git archive' or github's + # download-from-tag feature or the equivalent in other VCSes. + + get_keywords_f = handlers.get("get_keywords") + from_keywords_f = handlers.get("keywords") + if get_keywords_f and from_keywords_f: + try: + keywords = get_keywords_f(versionfile_abs) + ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) + if verbose: + print("got version from expanded keyword %s" % ver) + return ver + except NotThisMethod: + pass + + try: + ver = versions_from_file(versionfile_abs) + if verbose: + print("got version from file %s %s" % (versionfile_abs, ver)) + return ver + except NotThisMethod: + pass + + from_vcs_f = handlers.get("pieces_from_vcs") + if from_vcs_f: + try: + pieces = from_vcs_f(cfg.tag_prefix, root, verbose) + ver = render(pieces, cfg.style) + if verbose: + print("got version from VCS %s" % ver) + return ver + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + if verbose: + print("got version from parentdir %s" % ver) + return ver + except NotThisMethod: + pass + + if verbose: + print("unable to compute version") + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, "error": "unable to compute version", + "date": None} + + +def get_version(): + """Get the short version string for this project.""" + return get_versions()["version"] + + +def get_cmdclass(): + """Get the custom setuptools/distutils subclasses used by Versioneer.""" + if "versioneer" in sys.modules: + del sys.modules["versioneer"] + # this fixes the "python setup.py develop" case (also 'install' and + # 'easy_install .'), in which subdependencies of the main project are + # built (using setup.py bdist_egg) in the same python process. Assume + # a main project A and a dependency B, which use different versions + # of Versioneer. A's setup.py imports A's Versioneer, leaving it in + # sys.modules by the time B's setup.py is executed, causing B to run + # with the wrong versioneer. Setuptools wraps the sub-dep builds in a + # sandbox that restores sys.modules to it's pre-build state, so the + # parent is protected against the child's "import versioneer". By + # removing ourselves from sys.modules here, before the child build + # happens, we protect the child from the parent's versioneer too. + # Also see https://github.com/warner/python-versioneer/issues/52 + + cmds = {} + + # we add "version" to both distutils and setuptools + from distutils.core import Command + + class cmd_version(Command): + description = "report generated version string" + user_options = [] + boolean_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + vers = get_versions(verbose=True) + print("Version: %s" % vers["version"]) + print(" full-revisionid: %s" % vers.get("full-revisionid")) + print(" dirty: %s" % vers.get("dirty")) + print(" date: %s" % vers.get("date")) + if vers["error"]: + print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version + + # we override "build_py" in both distutils and setuptools + # + # most invocation pathways end up running build_py: + # distutils/build -> build_py + # distutils/install -> distutils/build ->.. + # setuptools/bdist_wheel -> distutils/install ->.. + # setuptools/bdist_egg -> distutils/install_lib -> build_py + # setuptools/install -> bdist_egg ->.. + # setuptools/develop -> ? + # pip install: + # copies source tree to a tempdir before running egg_info/etc + # if .git isn't copied too, 'git describe' will fail + # then does setup.py bdist_wheel, or sometimes setup.py install + # setup.py egg_info -> ? + + # we override different "build_py" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.build_py import build_py as _build_py + else: + from distutils.command.build_py import build_py as _build_py + + class cmd_build_py(_build_py): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_py.run(self) + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if cfg.versionfile_build: + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py + + if "cx_Freeze" in sys.modules: # cx_freeze enabled? + from cx_Freeze.dist import build_exe as _build_exe + # nczeczulin reports that py2exe won't like the pep440-style string + # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. + # setup(console=[{ + # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION + # "product_version": versioneer.get_version(), + # ... + + class cmd_build_exe(_build_exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _build_exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["build_exe"] = cmd_build_exe + del cmds["build_py"] + + if 'py2exe' in sys.modules: # py2exe enabled? + try: + from py2exe.distutils_buildexe import py2exe as _py2exe # py3 + except ImportError: + from py2exe.build_exe import py2exe as _py2exe # py2 + + class cmd_py2exe(_py2exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _py2exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["py2exe"] = cmd_py2exe + + # we override different "sdist" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.sdist import sdist as _sdist + else: + from distutils.command.sdist import sdist as _sdist + + class cmd_sdist(_sdist): + def run(self): + versions = get_versions() + self._versioneer_generated_versions = versions + # unless we update this, the command will keep using the old + # version + self.distribution.metadata.version = versions["version"] + return _sdist.run(self) + + def make_release_tree(self, base_dir, files): + root = get_root() + cfg = get_config_from_root(root) + _sdist.make_release_tree(self, base_dir, files) + # now locate _version.py in the new base_dir directory + # (remembering that it may be a hardlink) and replace it with an + # updated value + target_versionfile = os.path.join(base_dir, cfg.versionfile_source) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, + self._versioneer_generated_versions) + cmds["sdist"] = cmd_sdist + + return cmds + + +CONFIG_ERROR = """ +setup.cfg is missing the necessary Versioneer configuration. You need +a section like: + + [versioneer] + VCS = git + style = pep440 + versionfile_source = src/myproject/_version.py + versionfile_build = myproject/_version.py + tag_prefix = + parentdir_prefix = myproject- + +You will also need to edit your setup.py to use the results: + + import versioneer + setup(version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), ...) + +Please read the docstring in ./versioneer.py for configuration instructions, +edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. +""" + +SAMPLE_CONFIG = """ +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +#VCS = git +#style = pep440 +#versionfile_source = +#versionfile_build = +#tag_prefix = +#parentdir_prefix = + +""" + +INIT_PY_SNIPPET = """ +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions +""" + + +def do_setup(): + """Main VCS-independent setup function for installing Versioneer.""" + root = get_root() + try: + cfg = get_config_from_root(root) + except (EnvironmentError, configparser.NoSectionError, + configparser.NoOptionError) as e: + if isinstance(e, (EnvironmentError, configparser.NoSectionError)): + print("Adding sample versioneer config to setup.cfg", + file=sys.stderr) + with open(os.path.join(root, "setup.cfg"), "a") as f: + f.write(SAMPLE_CONFIG) + print(CONFIG_ERROR, file=sys.stderr) + return 1 + + print(" creating %s" % cfg.versionfile_source) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), + "__init__.py") + if os.path.exists(ipy): + try: + with open(ipy, "r") as f: + old = f.read() + except EnvironmentError: + old = "" + if INIT_PY_SNIPPET not in old: + print(" appending to %s" % ipy) + with open(ipy, "a") as f: + f.write(INIT_PY_SNIPPET) + else: + print(" %s unmodified" % ipy) + else: + print(" %s doesn't exist, ok" % ipy) + ipy = None + + # Make sure both the top-level "versioneer.py" and versionfile_source + # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so + # they'll be copied into source distributions. Pip won't be able to + # install the package without this. + manifest_in = os.path.join(root, "MANIFEST.in") + simple_includes = set() + try: + with open(manifest_in, "r") as f: + for line in f: + if line.startswith("include "): + for include in line.split()[1:]: + simple_includes.add(include) + except EnvironmentError: + pass + # That doesn't cover everything MANIFEST.in can do + # (http://docs.python.org/2/distutils/sourcedist.html#commands), so + # it might give some false negatives. Appending redundant 'include' + # lines is safe, though. + if "versioneer.py" not in simple_includes: + print(" appending 'versioneer.py' to MANIFEST.in") + with open(manifest_in, "a") as f: + f.write("include versioneer.py\n") + else: + print(" 'versioneer.py' already in MANIFEST.in") + if cfg.versionfile_source not in simple_includes: + print(" appending versionfile_source ('%s') to MANIFEST.in" % + cfg.versionfile_source) + with open(manifest_in, "a") as f: + f.write("include %s\n" % cfg.versionfile_source) + else: + print(" versionfile_source already in MANIFEST.in") + + # Make VCS-specific changes. For git, this means creating/changing + # .gitattributes to mark _version.py for export-subst keyword + # substitution. + do_vcs_install(manifest_in, cfg.versionfile_source, ipy) + return 0 + + +def scan_setup_py(): + """Validate the contents of setup.py against Versioneer's expectations.""" + found = set() + setters = False + errors = 0 + with open("setup.py", "r") as f: + for line in f.readlines(): + if "import versioneer" in line: + found.add("import") + if "versioneer.get_cmdclass()" in line: + found.add("cmdclass") + if "versioneer.get_version()" in line: + found.add("get_version") + if "versioneer.VCS" in line: + setters = True + if "versioneer.versionfile_source" in line: + setters = True + if len(found) != 3: + print("") + print("Your setup.py appears to be missing some important items") + print("(but I might be wrong). Please make sure it has something") + print("roughly like the following:") + print("") + print(" import versioneer") + print(" setup( version=versioneer.get_version(),") + print(" cmdclass=versioneer.get_cmdclass(), ...)") + print("") + errors += 1 + if setters: + print("You should remove lines like 'versioneer.VCS = ' and") + print("'versioneer.versionfile_source = ' . This configuration") + print("now lives in setup.cfg, and should be removed from setup.py") + print("") + errors += 1 + return errors + + +if __name__ == "__main__": + cmd = sys.argv[1] + if cmd == "setup": + errors = do_setup() + errors += scan_setup_py() + if errors: + sys.exit(1) + + +