index
int64
0
0
repo_id
stringlengths
16
145
file_path
stringlengths
27
196
content
stringlengths
1
16.7M
0
capitalone_repos
capitalone_repos/rubicon-ml/.pre-commit-config.yaml
repos: - repo: https://github.com/psf/black rev: 23.7.0 hooks: - id: black exclude: (versioneer.py|_version.py) - repo: https://github.com/timothycrosley/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/pycqa/flake8 rev: 6.1.0 hooks: - id: flake8
0
capitalone_repos
capitalone_repos/rubicon-ml/setup.cfg
[metadata] name = rubicon-ml description = "an ML library for model development and governance" long_description = file: README.md long_description_content_type = text/markdown author = "Joe Wolfe, Ryan Soley, Diane Lee, Mike McCarty, CapitalOne" license = "Apache License, Version 2.0" url = https://github.com/capitalone/rubicon-ml python_requires = >=3.8.0 project_urls = Documentation = https://capitalone.github.io/rubicon-ml/ Bug Tracker = https://github.com/capitalone/rubicon-ml/issues Source Code = https://github.com/capitalone/rubicon-ml classifiers = Development Status :: 4 - Beta Intended Audience :: Developers Intended Audience :: Science/Research Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Information Analysis Topic :: Software Development :: Build Tools Topic :: Software Development :: Documentation License :: OSI Approved :: Apache Software License Programming Language :: Python :: 3 [options] zip_safe = False include_package_data = True packages = find: install_requires = click<=8.1.7,>=7.1 fsspec<=2023.9.2,>=2021.4.0 intake[dataframe]<=0.7.0,>=0.5.2 jsonpath-ng<=1.6.0,>=1.5.3 numpy<=1.26.0,>=1.22.0 pandas<=2.1.1,>=1.0.0 pyarrow<=13.0.0,>=0.18.0 PyYAML<=6.0.1,>=5.4.0 scikit-learn<=1.3.1,>=0.22.0 [options.extras_require] prefect = prefect<=1.2.4,>=0.12.0 s3 = s3fs<=2023.9.2,>=0.4 ui = dash<=2.14.0,>=2.0.0 dash-bootstrap-components<=1.5.0,>=1.0.0 viz = dash<=2.14.0,>=2.0.0 dash-bootstrap-components<=1.5.0,>=1.0.0 all = dash<=2.14.0,>=2.0.0 dash-bootstrap-components<=1.5.0,>=1.0.0 prefect<=1.2.4,>=0.12.0 s3fs<=2023.9.2,>=0.4 [options.entry_points] console_scripts = rubicon_ml = rubicon_ml.cli:cli intake.drivers = rubicon_ml_experiment = rubicon_ml.intake_rubicon.experiment:ExperimentSource [versioneer] vcs = git style = pep440 versionfile_source = rubicon_ml/_version.py versionfile_build = rubicon_ml/_version.py tag_prefix = "" parentdir_prefix = rubicon-ml- [flake8] exclude = versioneer.py, rubicon_ml/_version.py, docs, .ipynb_checkpoints max-line-length = 88 ignore = E731 E741 W503 E203 E501 [isort] line_length = 88 skip = versioneer.py, rubicon_ml/_version.py, rubicon_ml/client/__init__.py filter_files = True multi_line_output = 3 include_trailing_comma = True force_grid_wrap = 0 combine_as_imports = True [tool:pytest] markers = run_notebooks: tests that run Jupyter notebooks write_files: tests that physically write files to local and S3 filesystems addopts = --cov=./rubicon_ml --cov-report=term-missing --cov-fail-under=90 -m="not write_files" minversion = 3.2 xfail_strict = True [edgetest.envs.core] python_version = 3.9 deps = dask jupyterlab kaleido nodejs nbconvert nbformat palmerpenguins Pillow pytest pytest-cov prefect xgboost extras = all upgrade = click dash dash-bootstrap-components fsspec intake[dataframe] jsonpath-ng numpy pandas pyarrow PyYAML s3fs scikit-learn command = pytest -m 'not run_notebooks and not write_files'
0
capitalone_repos
capitalone_repos/rubicon-ml/.coveragerc
[report] exclude_lines = pragma: no cover raise AssertionError raise NotImplementedError if __name__ == .__main__.: omit = versioneer.py rubicon_ml/_version.py
0
capitalone_repos
capitalone_repos/rubicon-ml/versioneer.py
# Version: 0.19 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/python-versioneer/python-versioneer * Brian Warner * License: Public Domain * Compatible with: Python 3.6, 3.7, 3.8, 3.9 and pypy3 * [![Latest Version][pypi-image]][pypi-url] * [![Build Status][travis-image]][travis-url] This is a tool for managing a recorded version number in 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 in your $PATH * add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) * run `versioneer install` in your source tree, commit the results * Verify version information with `python setup.py version` ## 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/python-versioneer/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 languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs 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/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve 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/python-versioneer/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ## 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. ## Similar projects * [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time dependency * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of versioneer ## 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/ . [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg [pypi-url]: https://pypi.python.org/pypi/versioneer/ [travis-image]: https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer """ import 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.ConfigParser() with open(setup_cfg, "r") as f: parser.read_file(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 """Create decorator to mark a method as the handler of a 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().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'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.19 (https://github.com/python-versioneer/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 """Create decorator to mark a method as the handler of a 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().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: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # 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() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """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[.post0.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post0.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post0.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. 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" 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: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # 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() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """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.19) 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[.post0.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post0.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post0.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. 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" 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(cmdclass=None): """Get the custom setuptools/distutils subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument. """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # '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/python-versioneer/python-versioneer/issues/52 cmds = {} if cmdclass is None else cmdclass.copy() # 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 'build_py' in cmds: _build_py = cmds['build_py'] elif "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 "setuptools" in sys.modules: from setuptools.command.build_ext import build_ext as _build_ext else: from distutils.command.build_ext import build_ext as _build_ext class cmd_build_ext(_build_ext): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_ext.run(self) if self.inplace: # build_ext --inplace will only build extensions in # build/lib<..> dir with no _version.py to write to. # As in place builds will already have a _version.py # in the module dir, we do not need to write one. return # now locate _version.py in the new build/ directory and replace # it with an updated value target_versionfile = os.path.join(self.build_lib, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_ext"] = cmd_build_ext if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # 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? from py2exe.distutils_buildexe import py2exe as _py2exe 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 'sdist' in cmds: _sdist = cmds['sdist'] elif "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(): """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): 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)
0
capitalone_repos
capitalone_repos/rubicon-ml/conftest.py
pytest_plugins = [ "tests.fixtures", ] def pytest_addoption(parser): parser.addoption("--s3-path", dest="s3-path")
0
capitalone_repos
capitalone_repos/rubicon-ml/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
capitalone_repos
capitalone_repos/rubicon-ml/pyproject.toml
[tool.black] line-length = 100 exclude = "(versioneer.py|_version.py)"
0
capitalone_repos
capitalone_repos/rubicon-ml/CODEOWNERS
* @capitalone/rubicon-admin-team
0
capitalone_repos
capitalone_repos/rubicon-ml/MANIFEST.in
graft rubicon_ml/viz/assets graft rubicon_ml/viz/assets/css include versioneer.py include rubicon_ml/_version.py recursive-include rubicon_ml/schema *.yaml
0
capitalone_repos
capitalone_repos/rubicon-ml/README.md
# rubicon-ml [![Test Package](https://github.com/capitalone/rubicon-ml/actions/workflows/test-package.yml/badge.svg)](https://github.com/capitalone/rubicon-ml/actions/workflows/test-package.yml) [![Publish Package](https://github.com/capitalone/rubicon-ml/actions/workflows/publish-package.yml/badge.svg)](https://github.com/capitalone/rubicon-ml/actions/workflows/publish-package.yml) [![Publish Docs](https://github.com/capitalone/rubicon-ml/actions/workflows/publish-docs.yml/badge.svg)](https://github.com/capitalone/rubicon-ml/actions/workflows/publish-docs.yml) [![edgetest](https://github.com/capitalone/rubicon-ml/actions/workflows/edgetest.yml/badge.svg)](https://github.com/capitalone/rubicon-ml/actions/workflows/edgetest.yml) [![Conda Version](https://img.shields.io/conda/vn/conda-forge/rubicon-ml.svg)](https://anaconda.org/conda-forge/rubicon-ml) [![PyPi Version](https://img.shields.io/pypi/v/rubicon_ml.svg)](https://pypi.org/project/rubicon-ml/) [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/capitalone/rubicon-ml/main?labpath=binder%2Fwelcome.ipynb) ## Purpose rubicon-ml is a data science tool that captures and stores model training and execution information, like parameters and outcomes, in a repeatable and searchable way. Its `git` integration associates these inputs and outputs directly with the model code that produced them to ensure full auditability and reproducibility for both developers and stakeholders alike. While experimenting, the dashboard makes it easy to explore, filter, visualize, and share recorded work. p.s. If you're looking for Rubicon, the Java/ObjC Python bridge, visit [this](https://pypi.org/project/rubicon/) instead. --- ## Components rubicon-ml is composed of three parts: * A Python library for storing and retrieving model inputs, outputs, and analyses to filesystems that’s powered by [`fsspec`](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest) * A dashboard for exploring, comparing, and visualizing logged data built with [`dash`](https://dash.plotly.com/) * And a process for sharing a selected subset of logged data with collaborators or reviewers that leverages [`intake`](https://intake.readthedocs.io/en/latest/) ## Workflow Use `rubicon_ml` to capture model inputs and outputs over time. It can be easily integrated into existing Python models or pipelines and supports both concurrent logging (so multiple experiments can be logged in parallel) and asynchronous communication with S3 (so network reads and writes won’t block). Meanwhile, periodically review the logged data within the Rubicon dashboard to steer the model tweaking process in the right direction. The dashboard lets you quickly spot trends by exploring and filtering your logged results and visualizes how the model inputs impacted the model outputs. When the model is ready for review, Rubicon makes it easy to share specific subsets of the data with model reviewers and stakeholders, giving them the context necessary for a complete model review and approval. ## Use Check out the [interactive notebooks in this Binder](https://mybinder.org/v2/gh/capitalone/rubicon-ml/main?labpath=binder%2Fwelcome.ipynb) to try `rubicon_ml` for yourself. Here's a simple example: ```python from rubicon_ml import Rubicon rubicon = Rubicon( persistence="filesystem", root_dir="/rubicon-root", auto_git_enabled=True ) project = rubicon.create_project( "Hello World", description="Using rubicon to track model results over time." ) experiment = project.log_experiment( training_metadata=[SklearnTrainingMetadata("sklearn.datasets", "my-data-set")], model_name="My Model Name", tags=["my_model_name"], ) experiment.log_parameter("n_estimators", n_estimators) experiment.log_parameter("n_features", n_features) experiment.log_parameter("random_state", random_state) accuracy = rfc.score(X_test, y_test) experiment.log_metric("accuracy", accuracy) ``` Then explore the project by running the dashboard: ``` rubicon_ml ui --root-dir /rubicon-root ``` ## Documentation For a full overview, visit the [docs](https://capitalone.github.io/rubicon-ml/). If you have suggestions or find a bug, [please open an issue](https://github.com/capitalone/rubicon-ml/issues/new/choose). ## Install The Python library is available on Conda Forge via `conda` and PyPi via `pip`. ``` conda config --add channels conda-forge conda install rubicon-ml ``` or ``` pip install rubicon-ml ``` ## Develop The project uses conda to manage environments. First, install [conda](https://conda.io/projects/conda/en/latest/user-guide/install/index.html). Then use conda to setup a development environment: ```bash conda env create -f environment.yml conda activate rubicon-ml-dev ``` Finally, install `rubicon_ml` locally into the newly created environment. ```bash pip install -e ".[all]" ``` ## Testing The tests are separated into unit and integration tests. They can be run directly in the activated dev environment via `pytest tests/unit` or `pytest tests/integration`. Or by simply running `pytest` to execute all of them. **Note**: some integration tests are intentionally `marked` to control when they are run (i.e. not during CICD). These tests include: * Integration tests that write to physical filesystems - local and S3. Local files will be written to `./test-rubicon` relative to where the tests are run. An S3 path must also be provided to run these tests. By default, these tests are disabled. To enable them, run: ``` pytest -m "write_files" --s3-path "s3://my-bucket/my-key" ``` * Integration tests that run Jupyter notebooks. These tests are a bit slower than the rest of the tests in the suite as they need to launch Jupyter servers. By default, they are enabled. To disable them, run: ``` pytest -m "not run_notebooks and not write_files" ``` **Note**: When simply running `pytest`, `-m "not write_files"` is the default. So, we need to also apply it when disabling notebook tests. ## Code Formatting Install and configure pre-commit to automatically run `black`, `flake8`, and `isort` during commits: * [install pre-commit](https://pre-commit.com/#installation) * run `pre-commit install` to set up the git hook scripts Now `pre-commit` will run automatically on git commit and will ensure consistent code format throughout the project. You can format without committing via `pre-commit run` or skip these checks with `git commit --no-verify`.
0
capitalone_repos
capitalone_repos/rubicon-ml/environment.yml
name: rubicon-ml-dev channels: - conda-forge dependencies: - python>=3.8 - pip - click<=8.1.7,>=7.1 - fsspec<=2023.9.2,>=2021.4.0 - intake[dataframe]<=0.7.0,>=0.5.2 - jsonpath-ng<=1.6.0,>=1.5.3 - numpy<=1.26.0,>=1.22.0 - pandas<=2.1.1,>=1.0.0 - pyarrow<=13.0.0,>=0.18.0 - PyYAML<=6.0.1,>=5.4.0 - scikit-learn<=1.3.1,>=0.22.0 # for prefect extras - prefect<=1.2.4,>=0.12.0 # for s3fs extras - s3fs<=2023.9.2,>=0.4 # for viz extras - dash<=2.14.0,>=2.0.0 - dash-bootstrap-components<=1.5.0,>=1.0.0 # for testing - black - dask - flake8 - ipykernel - isort - jupyterlab - lightgbm - nbconvert - pytest - pytest-cov - xgboost # for versioning - versioneer # for packaging - setuptools - wheel # for edgetest - edgetest - edgetest-conda
0
capitalone_repos
capitalone_repos/rubicon-ml/setup.py
"""Setup file for the package. For configuration information, see the ``setup.cfg``.""" from setuptools import setup import versioneer setup( version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), )
0
capitalone_repos/rubicon-ml
capitalone_repos/rubicon-ml/notebooks/user-environment.yml
name: rubicon-ml channels: - conda-forge dependencies: - python>=3.8 - pip - jupyterlab - rubicon-ml
0
capitalone_repos/rubicon-ml
capitalone_repos/rubicon-ml/notebooks/README.md
# rubicon-ml notebooks These notebooks are interactive versions of the examples found in our documentation. You can clone the repo and run the examples on your own, or just take a look at their outputs here! If you're a rubicon-ml user that wants to run the examples, check out the first section, **Users** to get set up. If you're a developer looking to create new examples, take a look at the second section, **Developers**. ## Users To ensure these examples work with your version of rubicon-ml, clone this repository at the tag corresponding to the verison of rubicon-ml you'll be using by replacing `X.X.X` in the command below with that version. ``` git clone https://github.com/capitalone/rubicon-ml.git --branch X.X.X --single-branch ``` Then, create and activate the "rubicon-ml" `conda` environment in the `notebooks` directory. ``` cd rubicon_ml conda env create -f notebooks/user-environment.yml conda activate rubicon-ml ``` The example notebooks can be viewed with either the `jupyter notebook` or `lab` command. ``` jupyter notebook notebooks/ ``` ``` jupyter lab notebooks/ ``` ## Developers When adding examples, make sure to commit any notebooks with their cells executed in order. These example notebooks are rendered as-is within the [documentation](https://capitalone.github.io/rubicon-ml/examples.html). To develop examples off the latest on the `main` branch, use the "rubicon-ml-dev" environment in `environment.yml` at the root of the rubicon-ml repository. ``` conda env create -f environment.yml conda activate rubicon-ml-dev ``` You'll need to install Jupyterlab and a local copy of the library as well. ``` conda install jupyterlab pip install -e .[all] ```
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/tagging.ipynb
from rubicon_ml import Rubicon import pandas as pd rubicon = Rubicon(persistence="memory") project = rubicon.get_or_create_project("Tagging") #logging experiments with tags experiment1 = project.log_experiment(name="experiment1", tags=["odd_num_exp"]) experiment2 = project.log_experiment(name="experiment2", tags=["even_num_exp"]) #logging artifacts, dataframes, features, metrics and parameters with tags first_artifact = experiment1.log_artifact(data_bytes=b"bytes", name="data_path", tags=["data"]) confusion_matrix = pd.DataFrame([[5, 0, 0], [0, 5, 1], [0, 0, 4]], columns=["x", "y", "z"]) first_dataframe = experiment1.log_dataframe(confusion_matrix, tags=["three_column"]) first_feature = experiment1.log_feature("year", tags=["time"]) first_metric = experiment1.log_metric("accuracy", .8, tags=["scalar"]) #can add multiple tags at logging (works for all objects) first_parameter = experiment1.log_parameter("n_estimators", tags=["tag1", "tag2"])print(experiment1.tags) print(experiment2.tags) print(first_artifact.tags) print(first_dataframe.tags) print(first_feature.tags) print(first_metric.tags) print(first_parameter.tags)experiment1.add_tags(["linear regression"]) experiment2.add_tags(["random forrest"]) first_artifact.add_tags(["added_tag"]) first_dataframe.add_tags(["added_tag"]) first_feature.add_tags(["added_tag"]) first_metric.add_tags(["added_tag"]) #can add multiple tags (works for all objects) first_parameter.add_tags(["added_tag1", "added_tag2"]) print(experiment1.tags) print(experiment2.tags) print(first_artifact.tags) print(first_dataframe.tags) print(first_feature.tags) print(first_metric.tags) print(first_parameter.tags)experiment1.remove_tags(["linear regression"]) experiment2.remove_tags(["random forrest"]) first_artifact.remove_tags(["added_tag"]) first_dataframe.remove_tags(["added_tag"]) first_feature.remove_tags(["added_tag"]) first_metric.remove_tags(["added_tag"]) #can remove multiple tags (works for all objects) first_parameter.remove_tags(["added_tag2", "added_tag1"]) print(experiment1.tags) print(experiment2.tags) print(first_artifact.tags) print(first_dataframe.tags) print(first_feature.tags) print(first_metric.tags) print(first_parameter.tags)experiment1.add_tags(["old_exp"]) experiment2.add_tags(["old_exp"]) experiment3 = project.log_experiment(name="experiment3", tags=["odd_num_exp","new_exp"]) #want just old experiments old_experiments = project.experiments(tags=["old_exp"]) #want just new experiments new_experiments = project.experiments(tags=["new_exp"]) #want just the odd number experiments odd_experiments = project.experiments(tags=["odd_num_exp"]) #this will return the same result as above since qtype="or" by default same_experiments = project.experiments(tags=["odd_num_exp", "new_exp"]) #this will return just experiment3 expected_experiment = project.experiments(tags=["odd_num_exp", "new_exp"], qtype="and") #getting both the old experiments 1 and 2 print("old experiments: " + str(old_experiments[0].name) + ", " + str(old_experiments[1].name) + "\n") #getting just the new experiment 3 print("new experiments: " + str(new_experiments[0].name) + "\n") #getting both odd experiments 1 and 3 print("odd experiments: " + str(odd_experiments[0].name) + ", " + str(odd_experiments[1].name) + "\n") #again getting both experiments 1 and 3 print("same experiments: " + str(same_experiments[0].name) + ", " + str(same_experiments[1].name) + "\n") #getting just experiment 3 print("expected experiment: " + str(expected_experiment[0].name) + "\n")
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/logging-plots.ipynb
import os from rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory") project = rubicon.get_or_create_project("Artifact Plots")import plotly.express as px from plotly import data df = data.wind() df.head()scatter_plot = px.scatter(df, x="direction", y="frequency", color="strength") scatter_plot.write_image("saved-scatter-plot-for-logging.png")bar_plot = px.bar(df, x="direction", y="frequency", color="strength") bar_plot_bytes = bar_plot.to_image(format="png")project.log_artifact( name="scatter plot", data_path="saved-scatter-plot-for-logging.png", description="saved scatter plot with path", ) artifact_plot_from_file = project.artifact(name="scatter plot")project.log_artifact(name="bar plot", data_bytes=bar_plot_bytes) artifact_plot_bytes = project.artifact(name="bar plot")import io from PIL import Image imageScatterPlotStream = io.BytesIO(artifact_plot_from_file.data) scatter_plot_image = Image.open(imageScatterPlotStream) imageBarPlotStream = io.BytesIO(artifact_plot_bytes.data) bar_plot_image = Image.open(imageBarPlotStream)display(scatter_plot_image)display(bar_plot_image)
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/set-schema.ipynb
from rubicon_ml.schema import registry available_schema = registry.available_schema() available_schemaimport pprint rfc_schema = registry.get_schema("sklearn__RandomForestClassifier") pprint.pprint(rfc_schema)from rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory") project = rubicon.create_project(name="apply schema") projectproject.set_schema(rfc_schema)
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/multiple-backend.ipynb
from rubicon_ml import Rubicon#rb = Rubicon(persistence="memory") #or #rb = Rubicon(persistence="filesystem")#example multiple backend instantiaiton rb = Rubicon(composite_config=[ {"persistence": "filesystem", "root_dir": "./rubicon-root/rootA"}, {"persistence": "filesystem", "root_dir": "./rubicon-root/rootB"}, ])project = rb.create_project("example_project") experiment = project.log_experiment("example_experiment") artifact = experiment.log_artifact(data_bytes=b"bytes", name="example_artifact") import pandas as pd dataframe = experiment.log_dataframe(pd.DataFrame([[5, 0, 0], [0, 5, 1], [0, 0, 4]], columns=["x", "y", "z"])) feature = experiment.log_feature("year") metric = experiment.log_metric("accuracy", .8) parameter = experiment.log_parameter("n_estimators")projects = rb.projects() print("projects: " + str(projects)) print("\n") experiments = project.experiments() print("experiments: " + str(experiments)) print("\n") artifacts = experiment.artifacts() print("artifacts: " + str(artifacts)) print("\n") dataframes = experiment.dataframes() print("dataframes: " + str(dataframes)) print("\n") features = experiment.features() print("features: " + str(features)) print("\n") metrics = experiment.metrics() print("metrics: " + str(metrics)) print("\n") parameters = experiment.parameters() print("parameters: " + str(parameters)) print("\n")rm -rf rubicon-root/rootArm -rf rubicon-root/rootB
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/logging_concurrently.py
from collections import namedtuple SklearnTrainingMetadata = namedtuple("SklearnTrainingMetadata", "module_name method") def run_experiment(project, classifier_cls, wine_datasets, feature_names, **kwargs): X_train, X_test, y_train, y_test = wine_datasets experiment = project.log_experiment( training_metadata=[ SklearnTrainingMetadata("sklearn.datasets", "load_wine"), ], model_name=classifier_cls.__name__, tags=[classifier_cls.__name__], ) for key, value in kwargs.items(): experiment.log_parameter(key, value) for name in feature_names: experiment.log_feature(name) classifier = classifier_cls(**kwargs) classifier.fit(X_train, y_train) classifier.predict(X_test) accuracy = classifier.score(X_test, y_test) experiment.log_metric("accuracy", accuracy) if accuracy >= 0.95: experiment.add_tags(["success"]) else: experiment.add_tags(["failure"])
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/visualizing-logged-dataframes.ipynb
import os from rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory") project = rubicon.get_or_create_project("Plotting Example") projectimport pandas as pd df = pd.DataFrame.from_records( [ ["Walmart", 514405], ["Exxon Mobil", 290212], ["Apple", 265595], ["Berkshire Hathaway", 247837], ["Amazon.com", 232887] ], columns=["Company", "Revenue (in millions)"] ) experiment = project.log_experiment() dataframe = experiment.log_dataframe(df, name="sample revenue df") dataframerevenue_line = dataframe.plot(x="Company", y="Revenue (in millions)") revenue_lineimport plotly.express as px revenue_scatter = dataframe.plot( plotting_func=px.scatter, x="Company", y="Revenue (in millions)", ) revenue_scatterfrom rubicon_ml.viz import DataframePlot DataframePlot( experiments=[experiment], dataframe_name="sample revenue df", ).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/logging-concurrently.ipynb
import os from rubicon_ml import Rubicon root_dir = os.environ.get("RUBICON_ROOT", "rubicon-root") root_path = f"{os.path.dirname(os.getcwd())}/{root_dir}" rubicon = Rubicon(persistence="filesystem", root_dir=root_path) project = rubicon.get_or_create_project( "Concurrent Experiments", description="training multiple models in parallel", ) projectfrom sklearn.datasets import load_wine from sklearn.model_selection import train_test_split wine = load_wine() wine_feature_names = wine.feature_names wine_datasets = train_test_split( wine["data"], wine["target"], test_size=0.25, )from collections import namedtuple SklearnTrainingMetadata = namedtuple("SklearnTrainingMetadata", "module_name method") def run_experiment(project, classifier_cls, wine_datasets, feature_names, **kwargs): X_train, X_test, y_train, y_test = wine_datasets experiment = project.log_experiment( training_metadata=[ SklearnTrainingMetadata("sklearn.datasets", "load_wine"), ], model_name=classifier_cls.__name__, tags=[classifier_cls.__name__], ) for key, value in kwargs.items(): experiment.log_parameter(key, value) for name in feature_names: experiment.log_feature(name) classifier = classifier_cls(**kwargs) classifier.fit(X_train, y_train) classifier.predict(X_test) accuracy = classifier.score(X_test, y_test) experiment.log_metric("accuracy", accuracy) if accuracy >= .95: experiment.add_tags(["success"]) else: experiment.add_tags(["failure"])from logging_concurrently import run_experimentimport multiprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier processes = [] for n_estimators in [10, 20, 30, 40]: processes.append(multiprocessing.Process( target=run_experiment, args=[project, RandomForestClassifier, wine_datasets, wine_feature_names], kwargs={"n_estimators": n_estimators}, )) for n_neighbors in [5, 10, 15, 20]: processes.append(multiprocessing.Process( target=run_experiment, args=[project, KNeighborsClassifier, wine_datasets, wine_feature_names], kwargs={"n_neighbors": n_neighbors}, )) for criterion in ["gini", "entropy"]: for splitter in ["best", "random"]: processes.append(multiprocessing.Process( target=run_experiment, args=[project, DecisionTreeClassifier, wine_datasets, wine_feature_names], kwargs={ "criterion": criterion, "splitter": splitter, }, ))for process in processes: process.start() for process in processes: process.join()len(project.experiments())for e in project.experiments(tags=["success"]): print(f"experiment {e.id[:8]} was successful using a {e.model_name}")first_experiment = project.experiments()[0] training_metadata = SklearnTrainingMetadata(*first_experiment.training_metadata) tags = first_experiment.tags parameters = [(p.name, p.value) for p in first_experiment.parameters()] metrics = [(m.name, m.value) for m in first_experiment.metrics()] print( f"experiment {first_experiment.id}\n" f"training metadata: {training_metadata}\ntags: {tags}\n" f"parameters: {parameters}\nmetrics: {metrics}" )ddf = rubicon.get_project_as_df("Concurrent Experiments", df_type="dask") ddf.compute()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/logging-training-metadata.ipynb
s3_config = { "region_name": "us-west-2", "signature_version": "v4", "retries": { "max_attempts": 10, "mode": "standard", } } bucket_name = "my-bucket" key = "path/to/my/data.parquet"def read_from_s3(config, bucket, key, local_output_path): import boto3 from botocore.config import Config config = Config(**config) # assuming credentials are correct in `~/.aws` or set in environment variables client = boto3.client("s3", config=config) with open(local_output_path, "wb") as f: s3.download_fileobj(bucket, key, f)def read_from_s3(config, bucket, key, local_output_path): return Nonefrom rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory") project = rubicon.get_or_create_project("Storing Training Metadata") projecttraining_metadata = (s3_config, bucket_name, key) experiment = project.log_experiment( training_metadata=training_metadata, tags=["S3", "training metadata"] ) # then run the experiment and log everything to rubicon! experiment.training_metadataexperiment = project.experiments(tags=["S3", "training metadata"], qtype="and")[0] training_metadata = experiment.training_metadata read_from_s3( training_metadata[0], training_metadata[1], training_metadata[2], "./local_output.parquet", )training_metadata = [ (s3_config, bucket_name, "path/to/my/data_0.parquet"), (s3_config, bucket_name, "path/to/my/data_1.parquet"), (s3_config, bucket_name, "path/to/my/data_2.parquet"), ] experiment = project.log_experiment(training_metadata=training_metadata) experiment.training_metadatatraining_metadata = ( s3_config, bucket_name, [ "path/to/my/data_0.parquet", "path/to/my/data_1.parquet", "path/to/my/data_2.parquet", ], ) experiment = project.log_experiment(training_metadata=training_metadata) experiment.training_metadatafrom collections import namedtuple S3TrainingMetadata = namedtuple("S3TrainingMetadata", "config bucket keys") training_metadata = S3TrainingMetadata( s3_config, bucket_name, [ "path/to/my/data_0.parquet", "path/to/my/data_1.parquet", "path/to/my/data_2.parquet", ], ) experiment = project.log_experiment(training_metadata=training_metadata) experiment.training_metadataS3Config = namedtuple("S3Config", "region_name signature_version retries") S3DatasetMetadata = namedtuple("S3DatasetMetadata", "bucket key") project = rubicon.get_or_create_project( "S3 Training Metadata", training_metadata=S3Config(**s3_config), ) for key in [ "path/to/my/data_0.parquet", "path/to/my/data_1.parquet", "path/to/my/data_2.parquet", ]: experiment = project.log_experiment( training_metadata=S3DatasetMetadata(bucket=bucket_name, key=key) ) # then run the experiment and log everything to rubicon!project = rubicon.get_project("S3 Training Metadata") s3_config = S3Config(*project.training_metadata) print(s3_config) for experiment in project.experiments(): s3_dataset_metadata = S3DatasetMetadata(*experiment.training_metadata) print(s3_dataset_metadata) training_data = read_from_s3( s3_config._asdict(), s3_dataset_metadata.bucket, s3_dataset_metadata.key, "./local_output.parquet" )
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/rubiconJSON-querying.ipynb
from rubicon_ml import Rubicon from sklearn.datasets import load_wine from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, make_scorer, precision_score, recall_score from sklearn.model_selection import ParameterGrid, train_test_splitX, y = load_wine(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0)rubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.get_or_create_project(name="jsonpath querying")for parameters in ParameterGrid({ "n_estimators": [5, 50, 500], "min_samples_leaf": [1, 10, 100], }): rfc = RandomForestClassifier(random_state=0, **parameters) tags = ["large"] if parameters["n_estimators"] > 10 else [] experiment = project.log_experiment(model_name=rfc.__class__.__name__, tags=tags) for name, value in parameters.items(): experiment.log_parameter(name=name, value=value) for name in X_train.columns: experiment.log_feature(name=name) rfc.fit(X_train, y_train) precision_scorer = make_scorer(precision_score, average="weighted", zero_division=0.0) precision = precision_scorer(rfc, X_test, y_test) recall_scorer = make_scorer(recall_score, average="weighted") recall = recall_scorer(rfc, X_test, y_test) experiment.log_metric(name="precision", value=precision) experiment.log_metric(name="recall", value=recall) experiment.log_artifact(data_object=rfc, name=rfc.__class__.__name__, tags=["trained"])from rubicon_ml import RubiconJSON rubicon_json = RubiconJSON(experiments=project.experiments()) rubicon_json.json["experiment"][0]experiment_query = "$..experiment[?(@.tags[*]=='large')]" for match in rubicon_json.search(experiment_query): print(match.value)experiment_query += ".id" for match in rubicon_json.search(experiment_query): print(match.value)metric_query = "$..experiment[*].metric" for match in rubicon_json.search(metric_query): print(match.value)best_metric_query = "$..experiment[*].metric[?(@.name=='precision' & @.value>=0.96)]" for match in rubicon_json.search(best_metric_query): print(match.value)best_experiment_query = "$..experiment[?(@.metric[?(@.name=='precision' & @.value>=0.96)])].id" for match in rubicon_json.search(best_experiment_query): print(match.value)for match in rubicon_json.search(best_experiment_query): experiment = project.experiment(id=match.value) print(experiment.artifact(name="RandomForestClassifier").get_data(unpickle=True))
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/logging-feature-plots.ipynb
import shap import sklearn from sklearn.datasets import load_wine from sklearn.ensemble import GradientBoostingRegressor from sklearn.preprocessing import StandardScaler from rubicon_ml import Rubicon from rubicon_ml.sklearn import make_pipeline rubicon = Rubicon(persistence="memory") project = rubicon.get_or_create_project("Logging Feature Plots") X, y = load_wine(return_X_y=True) reg = GradientBoostingRegressor(random_state=1) pipeline = make_pipeline(project, reg) pipeline.fit(X, y)explainer = shap.Explainer(pipeline[0]) shap_values = explainer.shap_values(X)import io import matplotlib.pyplot as pl experiment = pipeline.experiment for i in range(reg.n_features_in_): feature_name = f"feature {i}" experiment.log_feature(name=feature_name, tags=[feature_name]) shap.dependence_plot(i, shap_values, X, interaction_index=None, show=False) fig = pl.gcf() buf = io.BytesIO() fig.savefig(buf, format="png") buf.seek(0) experiment.log_artifact( data_bytes=buf.read(), name=feature_name, tags=[feature_name], ) buf.close()import io from PIL import Image experiment = pipeline.experiment for feature in experiment.features(): artifact = experiment.artifact(name=feature.name) buf = io.BytesIO(artifact.data) scatter_plot_image = Image.open(buf) print(feature.name) display(scatter_plot_image)
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/register-custom-schema.ipynb
import os os.environ["RUNTIME_ENV"] = "AWS" ! echo $RUNTIME_ENVimport pprint extended_schema = { "name": "sklearn__RandomForestClassifier__ext", "extends": "sklearn__RandomForestClassifier", "parameters": [ {"name": "runtime_environment", "value_env": "RUNTIME_ENV"}, ], } pprint.pprint(extended_schema)from rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.create_project(name="apply schema") projectproject.set_schema(extended_schema)from sklearn.datasets import load_wine X, y = load_wine(return_X_y=True, as_frame=True)from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier( ccp_alpha=5e-3, criterion="log_loss", max_features="log2", n_estimators=24, oob_score=True, random_state=121, ) rfc.fit(X, y) print(rfc)experiment = project.log_with_schema( rfc, experiment_kwargs={ "name": "log with extended schema", "model_name": "RandomForestClassifier", "description": "logged with an extended `rubicon_schema`", }, ) experimentfor parameter in experiment.parameters(): print(f"{parameter.name}: {parameter.value}")del os.environ["RUNTIME_ENV"]
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/log-with-schema.ipynb
from rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.create_project(name="apply schema") projectfrom sklearn.datasets import load_wine X, y = load_wine(return_X_y=True, as_frame=True)from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier( ccp_alpha=5e-3, criterion="log_loss", max_features="log2", n_estimators=24, oob_score=True, random_state=121, ) rfc.fit(X, y) print(rfc)experiment = project.log_with_schema( rfc, experiment_kwargs={ # additional kwargs to be passed to `project.log_experiment` "name": "log with schema", "model_name": "RandomForestClassifier", "description": "logged with the `RandomForestClassifier` `rubicon_schema`", }, ) print(f"inferred schema name: {project.schema_['name']}") experimentvars(experiment._domain)project.schema_["features"]for feature in experiment.features(): print(f"{feature.name} ({feature.importance})")project.schema_["parameters"]for parameter in experiment.parameters(): print(f"{parameter.name}: {parameter.value}")project.schema_["metrics"]import numpy as np for metric in experiment.metrics(): if np.isscalar(metric.value): print(f"{metric.name}: {metric.value}") else: # don't print long metrics print(f"{metric.name}: ...")project.schema_["artifacts"]for artifact in experiment.artifacts(): print(f"{artifact.name}:\n{artifact.get_data(unpickle=True)}")
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/logging-examples/logging-experiment-failures.ipynb
from sklearn.base import BaseEstimator import random class BadEstimator(BaseEstimator): def __init__(self): super().__init__() self.knn = KNeighborsClassifier(n_neighbors=2) def fit(self, X, y): self.knn.fit(X, y) output=random.random() if output>.3: self.state_=output def score(self, X): knn_score = self.knn.score(X) return knn_scorefrom rubicon_ml.sklearn import make_pipeline from sklearn.neighbors import KNeighborsClassifier from sklearn.impute import SimpleImputer from rubicon_ml import Rubicon random.seed(17) rubicon = Rubicon( persistence="memory", ) project = rubicon.get_or_create_project(name="Failed Experiments")X = [[1], [1], [1], [1]] y = [1, 1, 1, 1] for _ in range(20): pipe=make_pipeline(project, SimpleImputer(strategy="mean"),BadEstimator()) pipe.fit(X,y) if not hasattr(pipe["badestimator"],"state_"): pipe.experiment.add_tags(["failed"]) else: pipe.experiment.add_tags(["passed"])for exp in project.experiments(tags=["failed"]): print(exp)len(project.experiments(tags=["failed"]))len(project.experiments(tags=["passed"]))
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/quick-look/visualizing-experiments.ipynb
import intake import rubicon_ml catalog = intake.open_catalog("./penguin_catalog.yml") for source in catalog: catalog[source].discover() experiments = [catalog[source].read() for source in catalog]from rubicon_ml.viz import ExperimentsTable ExperimentsTable(experiments=experiments).show()from rubicon_ml.viz import Dashboard Dashboard(experiments=experiments).serve(run_server_kwargs={"port": 8051})
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/quick-look/logging-experiments.ipynb
from palmerpenguins import load_penguins penguins_df = load_penguins() target_values = penguins_df['species'].unique() print(f"target classes (species): {target_values}") penguins_df.head()from sklearn.preprocessing import LabelEncoder for column in ["species", "island", "sex"]: penguins_df[column] = LabelEncoder().fit_transform(penguins_df[column]) print(f"target classes (species): {penguins_df['species'].unique()}") penguins_df.head()from sklearn.model_selection import train_test_split train_penguins_df, test_penguins_df = train_test_split(penguins_df, test_size=.30) target_name = "species" feature_names = [c for c in train_penguins_df.columns if c != target_name] X_train, y_train = train_penguins_df[feature_names], train_penguins_df[target_name] X_test, y_test = test_penguins_df[feature_names], test_penguins_df[target_name] X_train.shape, y_train.shape, X_test.shape, y_test.shapefrom sklearn.impute import SimpleImputer from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline imputer_strategy = "mean" classifier_n_neighbors = 5 steps = [ ("si", SimpleImputer(strategy=imputer_strategy)), ("kn", KNeighborsClassifier(n_neighbors=classifier_n_neighbors)), ] penguin_pipeline = Pipeline(steps=steps) penguin_pipeline.fit(X_train, y_train) score = penguin_pipeline.score(X_test, y_test) scorefrom rubicon_ml import Rubicon rubicon = Rubicon( persistence="filesystem", root_dir="./rubicon-root", auto_git_enabled=True, ) project = rubicon.get_or_create_project(name="classifying penguins") experiment = project.log_experiment() for feature_name in feature_names: experiment.log_feature(name=feature_name) _ = experiment.log_parameter(name="strategy", value=imputer_strategy) _ = experiment.log_parameter(name="n_neighbors", value=classifier_n_neighbors) _ = experiment.log_metric(name="accuracy", value=score)print(experiment) print() print(f"git info:") print(f"\tbranch name: {experiment.branch_name}\n\tcommit hash: {experiment.commit_hash}") print(f"features: {[f.name for f in experiment.features()]}") print(f"parameters: {[(p.name, p.value) for p in experiment.parameters()]}") print(f"metrics: {[(m.name, m.value) for m in experiment.metrics()]}")from sklearn.base import clone for imputer_strategy in ["mean", "median", "most_frequent"]: for classifier_n_neighbors in [5, 10, 15, 20]: pipeline = clone(penguin_pipeline) pipeline.set_params( si__strategy=imputer_strategy, kn__n_neighbors=classifier_n_neighbors, ) pipeline.fit(X_train, y_train) score = pipeline.score(X_test, y_test) experiment = project.log_experiment(tags=["parameter search"]) for feature_name in feature_names: experiment.log_feature(name=feature_name) experiment.log_parameter(name="strategy", value=imputer_strategy) experiment.log_parameter(name="n_neighbors", value=classifier_n_neighbors) experiment.log_metric(name="accuracy", value=score)print("experiments:") for experiment in project.experiments(tags=["parameter search"]): print( f"\tid: {experiment.id}, " f"parameters: {[(p.name, p.value) for p in experiment.parameters()]}, " f"metrics: {[(m.name, m.value) for m in experiment.metrics()]}" )import pandas as pd from sklearn.metrics import confusion_matrix experiment = project.experiments(tags=["parameter search"])[-1] trained_model = pipeline._final_estimator experiment.log_artifact(data_object=trained_model, name="trained model") y_pred = pipeline.predict(X_test) confusion_matrix_df = pd.DataFrame( confusion_matrix(y_test, y_pred), columns=target_values, index=target_values, ) experiment.log_dataframe(confusion_matrix_df, name="confusion matrix") print(experiment.artifact(name="trained model").get_data(unpickle=True)) experiment.dataframe(name="confusion matrix").get_data()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/quick-look/sharing-experiments.ipynb
from rubicon_ml import Rubicon rubicon = Rubicon(persistence="filesystem", root_dir="./rubicon-root") project = rubicon.get_project(name="classifying penguins") projectfrom rubicon_ml import publish catalog = publish( project.experiments(tags=["parameter search"]), output_filepath="./penguin_catalog.yml", ) !head -7 penguin_catalog.ymlimport intake catalog = intake.open_catalog("./penguin_catalog.yml") for source in catalog: catalog[source].discover() shared_experiments = [catalog[source].read() for source in catalog] print("shared experiments:") for experiment in shared_experiments: print( f"\tid: {experiment.id}, " f"parameters: {[(p.name, p.value) for p in experiment.parameters()]}, " f"metrics: {[(m.name, m.value) for m in experiment.metrics()]}" )new_project = rubicon.get_or_create_project(name="update catalog example") new_experiments = [new_project.log_experiment() for _ in range(2)] updated_catalog = publish( base_catalog_filepath="./penguin_catalog.yml", experiments = new_experiments, ) !head -7 penguin_catalog.yml
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/demos/classification.ipynb
from palmerpenguins import load_penguins penguins_df = load_penguins() penguins_df.head()import plotly.express as px px.scatter(penguins_df, x="flipper_length_mm", y="bill_length_mm", color="species")from sklearn.preprocessing import LabelEncoder penguin_encoder = LabelEncoder() for column in ["species", "island", "sex"]: penguins_df[column] = penguin_encoder.fit_transform(penguins_df[column]) penguins_df.head()from sklearn.model_selection import train_test_split train_penguins_df, test_penguins_df = train_test_split(penguins_df, test_size=.30) target_column = "species" feature_columns = [c for c in train_penguins_df.columns if c != target_column] X_train, y_train = train_penguins_df[feature_columns], train_penguins_df[target_column] X_test, y_test = test_penguins_df[feature_columns], test_penguins_df[target_column] X_train.shape, y_train.shape, X_test.shape, y_test.shapefrom sklearn.impute import SimpleImputer from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline steps = [ ("si", SimpleImputer(strategy="mean")), ("kn", KNeighborsClassifier(n_neighbors=5)), ] penguin_pipeline = Pipeline(steps=steps) penguin_pipeline.fit(X_train, y_train) score = penguin_pipeline.score(X_test, y_test) scorefrom rubicon_ml import Rubicon rubicon = Rubicon( persistence="filesystem", root_dir="./rubicon-root", auto_git_enabled=True, ) project = rubicon.get_or_create_project(name="demo") experiment = project.log_experiment(name="classifying penguins") parameter_strategy = experiment.log_parameter(name="strategy", value="mean") parameter_n_neighbors = experiment.log_parameter(name="n_neighbors", value=5) metric_accuracy = experiment.log_metric(name="accuracy", value=score)print(experiment) print(experiment.branch_name, experiment.commit_hash) print() print([(p.name, p.value) for p in experiment.parameters()]) print([(m.name, m.value) for m in experiment.metrics()])from rubicon_ml.sklearn import RubiconPipeline rubicon_penguin_pipeline = RubiconPipeline( project=project, experiment_kwargs={"name": "KNeighborsClassifier", "tags": ["knn"]}, steps=steps, ) rubicon_penguin_pipeline.fit(X_train, y_train) pipeline_experiment = rubicon_penguin_pipeline.experiment rubicon_penguin_pipeline.score(X_test, y_test)print(pipeline_experiment) print() print([(p.name, p.value) for p in pipeline_experiment.parameters()]) print([(m.name, m.value) for m in pipeline_experiment.metrics()])from sklearn.model_selection import GridSearchCV parameters = { "si__strategy": ["mean", "median", "most_frequent"], "kn__n_neighbors": [2, 4, 8, 16, 32, 64], } grid_search_project = rubicon.get_or_create_project(name="grid search demo") rubicon_penguin_pipeline.project = grid_search_project grid_search = GridSearchCV( rubicon_penguin_pipeline, cv=2, param_grid=parameters, refit=False, verbose=True, ) grid_search.fit(X_train, y_train) grid_search_project.experiments()from rubicon_ml.viz import ExperimentsTable ExperimentsTable(experiments=grid_search_project.experiments()).show()import intake catalog = intake.open_catalog("./rubicon-ml-catalog.yml") for source in catalog: catalog[source].discover() shared_experiments = [catalog[source].read() for source in catalog] [(e.id, e.metric(name="score").value) for e in shared_experiments]from sklearn.ensemble import RandomForestClassifier new_steps = [ ("si", SimpleImputer(strategy="mean")), ("rf", RandomForestClassifier(n_estimators=100)), ] new_rubicon = Rubicon( persistence="filesystem", root_dir="./new-rubicon-root", auto_git_enabled=True, ) new_project = new_rubicon.get_or_create_project(name="demo") new_pipeline = RubiconPipeline( project=new_project, experiment_kwargs={"name": "RandomForestClassifier", "tags": ["rf"]}, steps=new_steps, ) new_parameters = { "si__strategy": ["mean", "median", "most_frequent"], "rf__n_estimators": [25, 50, 100, 200, 400], } new_grid_search = GridSearchCV( new_pipeline, cv=2, param_grid=new_parameters, refit=False, verbose=True, ) new_grid_search.fit(X_train, y_train)from rubicon_ml.viz import Dashboard, MetricCorrelationPlot Dashboard( experiments=new_project.experiments(), widgets=[ [ExperimentsTable()], [MetricCorrelationPlot(parameter_names=["si__strategy", "rf__n_estimators"])], ], ).serve()from rubicon_ml import publish combined_catalog = publish( shared_experiments + new_project.experiments(), "./combined-catalog.yml", )from sklearn.base import BaseEstimator class ComboEstimator(BaseEstimator): def __init__(self, n_neighbors=2, n_estimators=25): super().__init__() self.n_neighbors = n_neighbors self.n_estimators = n_estimators self.knn = KNeighborsClassifier(n_neighbors=n_neighbors) self.rf = RandomForestClassifier(n_estimators=n_estimators) def fit(self, X, y): self.knn.fit(X, y) self.rf.fit(X, y) def score(self, X): knn_score = self.knn.score(X) rf_score = self.rf.score(X) return (knn_score + (rf_score * 2)) / 3import pickle from rubicon_ml.sklearn.estimator_logger import EstimatorLogger class ModelLogger(EstimatorLogger): def log_parameters(self): super().log_parameters() self.experiment.log_artifact(data_bytes=pickle.dumps(self.estimator.knn), name="knn") self.experiment.log_artifact(data_bytes=pickle.dumps(self.estimator.rf), name="rf")from rubicon_ml.sklearn import make_pipeline another_pipeline = make_pipeline( new_project, SimpleImputer(strategy="mean"), (ComboEstimator(n_neighbors=16, n_estimators=100), ModelLogger()), ) another_pipeline.fit(X_train, y_train) [(a.name, a) for a in another_pipeline.experiment.artifacts()]for artifact in another_pipeline.experiment.artifacts(): print(pickle.loads(artifact.data))
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/integrations/integration-prefect-workflows.ipynb
from rubicon_ml.workflow.prefect import ( get_or_create_project_task, create_experiment_task, log_artifact_task, log_dataframe_task, log_feature_task, log_metric_task, log_parameter_task, )from prefect import task @task def load_data(): from sklearn.datasets import load_wine return load_wine()@task def split_data(dataset): from sklearn.model_selection import train_test_split return train_test_split( dataset.data, dataset.target, test_size=0.25, )@task def get_feature_names(dataset): return dataset.feature_names@task def fit_pred_model( train_test_split_result, n_components, n_neighbors, is_standardized ): from sklearn import metrics from sklearn.decomposition import PCA from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler X_train, X_test, y_train, y_test = train_test_split_result if is_standardized: classifier = make_pipeline( StandardScaler(), PCA(n_components=n_components), KNeighborsClassifier(n_neighbors=n_neighbors), ) else: classifier = make_pipeline( PCA(n_components=n_components), KNeighborsClassifier(n_neighbors=n_neighbors), ) classifier.fit(X_train, y_train) pred_test = classifier.predict(X_test) accuracy = metrics.accuracy_score(y_test, pred_test) return accuracyfrom prefect import Flow n_components = 2 n_neighbors = 5 is_standardized = True with Flow("Wine Classification") as flow: wine_dataset = load_data() feature_names = get_feature_names(wine_dataset) train_test_split = split_data(wine_dataset) accuracy = fit_pred_model( train_test_split, n_components, n_neighbors, is_standardized, )flow_id = flow.register(project_name="Wine Classification")import time from prefect import Client prefect_client = Client() def run_flow(client, flow_id): flow_run_id = client.create_flow_run(flow_id=flow_id) is_finished = False while not is_finished: state = client.get_flow_run_info(flow_run_id).state print(f"{state.message.strip('.')}. Waiting...") time.sleep(3) is_finished = state.is_finished() assert state.is_successful() print(f"Flow run {flow_run_id} was successful!") return flow_run_id flow_run_id = run_flow(prefect_client, flow_id)info = prefect_client.get_flow_run_info(flow_run_id) slugs = [t.task_slug for t in info.task_runs] index = slugs.index(accuracy.slug) result = info.task_runs[index].state._result.read( info.task_runs[index].state._result.location, ) result.valueimport os from prefect import unmapped root_dir = os.environ.get("RUBICON_ROOT", "rubicon-root") root_path = f"{os.path.dirname(os.getcwd())}/{root_dir}" n_components = 2 n_neighbors = 5 is_standardized = True with Flow("Wine Classification with Rubicon") as flow: project = get_or_create_project_task( "filesystem", root_path, "Wine Classification with Prefect", ) experiment = create_experiment_task( project, name="logged from a Prefect task", ) wine_dataset = load_data() feature_names = get_feature_names(wine_dataset) train_test_split = split_data(wine_dataset) log_feature_task.map(unmapped(experiment), feature_names) log_parameter_task(experiment, "n_components", n_components) log_parameter_task(experiment, "n_neighbors", n_neighbors) log_parameter_task(experiment, "is_standardized", is_standardized) accuracy = fit_pred_model( train_test_split, n_components, n_neighbors, is_standardized, ) log_metric_task(experiment, "accuracy", accuracy)flow_with_rubicon_id = flow.register(project_name="Wine Classification") flow_run_with_rubicon_id = run_flow(prefect_client, flow_with_rubicon_id)from rubicon_ml import Rubicon rubicon = Rubicon(persistence="filesystem", root_dir=root_path) project = rubicon.get_project("Wine Classification with Prefect") experiment = project.experiments()[0] features = [f.name for f in experiment.features()] parameters = [(p.name, p.value) for p in experiment.parameters()] metrics = [(m.name, m.value) for m in experiment.metrics()] print( f"experiment {experiment.id}\n" f"features: {features}\nparameters: {parameters}\n" f"metrics: {metrics}" )import dask.distributed from prefect.executors import DaskExecutor dask_client = dask.distributed.Client() dask_executor = DaskExecutor(address=dask_client.cluster.scheduler.address)@task def log_feature_set(experiment, feature_names): """log a set of features to a rubicon experiment Parameters ---------- experiment : rubicon.Experiment the experiment to log the feature set to feature_names : list of str the names of the features to log to `experiment` """ features = [] for name in feature_names: features.append(experiment.log_feature(name=name)) return featuresn_components = [2, 2, 2, 2, 4, 4, 4, 4 ] n_neighbors = [5, 5, 10, 10, 5, 5, 10, 10 ] is_standardized = [True, False, True, False, True, False, True, False] experiment_names = [f"mapped run {i}" for i in range(len(n_components))] with Flow( "Wine Classification with Rubicon - Mapped", executor=dask_executor, ) as mapped_flow: project = get_or_create_project_task( "filesystem", root_path, "Wine Classification with Prefect - Mapped", ) experiments = create_experiment_task.map( unmapped(project), name=experiment_names, description=unmapped("concurrent example with Prefect"), ) wine_dataset = load_data() feature_names = get_feature_names(wine_dataset) train_test_split = split_data(wine_dataset) log_feature_set.map(experiments, unmapped(feature_names)) log_parameter_task.map(experiments, unmapped("n_components"), n_components) log_parameter_task.map(experiments, unmapped("n_neighbors"), n_neighbors) log_parameter_task.map(experiments, unmapped("is_standardized"), is_standardized) accuracies = fit_pred_model.map( unmapped(train_test_split), n_components, n_neighbors, is_standardized, ) log_metric_task.map(experiments, unmapped("accuracy"), accuracies)flow_with_concurrent_rubicon_id = mapped_flow.register( project_name="Wine Classification", ) flow_run_with_concurrent_rubicon_id = run_flow( prefect_client, flow_with_concurrent_rubicon_id, )from rubicon_ml.viz import Dashboard project = get_project( "filesystem", root_path, "Wine Classification with Prefect - Mapped", ) Dashboard(project.experiments()).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/integrations/integration-git.ipynb
from rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory", auto_git_enabled=True)project = rubicon.create_project("Automatic Git Integration") project.github_urlexperiment = project.log_experiment(model_name="GitHub Model") experiment.branch_name, experiment.commit_hashfrom rubicon_ml.viz import Dashboard experiment.log_parameter(name="input", value=True) experiment.log_metric(name="output", value=1.0) Dashboard([experiment]).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/integrations/integration-sklearn.ipynb
from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from rubicon_ml import Rubicon from rubicon_ml.sklearn import RubiconPipeline rubicon = Rubicon(persistence="memory") project = rubicon.get_or_create_project("Rubicon Pipeline Example") X, y = make_classification(random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) pipe = RubiconPipeline( project, [('scaler', StandardScaler()), ('svc', SVC())], ) print(pipe)pipe.fit(X_train, y_train) pipe.score(X_test, y_test)for experiment in project.experiments(): parameters = [(p.name, p.value) for p in experiment.parameters()] metrics = [(m.name, m.value) for m in experiment.metrics()] print( f"experiment {experiment.id}\n" f"parameters: {parameters}\nmetrics: {metrics}" )from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import GridSearchCV categories = ["alt.atheism", "talk.religion.misc"] data = fetch_20newsgroups(subset='train', categories=categories)import os from rubicon_ml import Rubicon from rubicon_ml.sklearn import FilterEstimatorLogger, RubiconPipeline root_dir = os.environ.get("RUBICON_ROOT", "rubicon-root") root_path = f"{os.path.dirname(os.getcwd())}/{root_dir}" rubicon = Rubicon(persistence="filesystem", root_dir=root_path) project = rubicon.get_or_create_project("Grid Search") pipeline = RubiconPipeline( project, [ ("vect", CountVectorizer()), ("tfidf", TfidfTransformer()), ("clf", SGDClassifier()), ], user_defined_loggers = { "vect": FilterEstimatorLogger(select=["max_df"]), "tfidf": FilterEstimatorLogger(ignore_all=True), "clf": FilterEstimatorLogger(select=["max_iter", "alpha", "penalty"]), }, experiment_kwargs={ "name": "logged from a RubiconPipeline", "model_name": SGDClassifier.__name__, }, )parameters = { "vect__max_df": (0.5, 0.75, 1.0), "vect__ngram_range": ((1, 1), (1, 2)), "clf__max_iter": (10, 20), "clf__alpha": (0.00001, 0.000001), "clf__penalty": ("l2", "elasticnet"), } grid_search = GridSearchCV(pipeline, parameters, cv=2, n_jobs=-1, refit=False) grid_search.fit(data.data, data.target) print(grid_search)print(f"Best score: {grid_search.best_score_}") full_results = grid_search.cv_results_from rubicon_ml.viz import Dashboard Dashboard(project.experiments()).serve(in_background=True)pipe_toggle_warnings = RubiconPipeline( project, [('scaler', StandardScaler()), ('svc', SVC())], ignore_warnings=True )pipe_toggle_warnings.ignore_warnings = False
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/viz/dataframe-plot.ipynb
import random import numpy as np import pandas as pd import plotly.express as px from rubicon_ml import Rubicon from rubicon_ml.viz import DataframePlotDISPLAY_DFS = False rubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.get_or_create_project("plot comparison") num_experiments_to_log = 6 data_ranges = [ (random.randint(0, 15000), random.randint(0, 15000)) for _ in range(num_experiments_to_log) ] dates = pd.date_range(start="1/1/2010", end="12/1/2020", freq="MS") for start, stop in data_ranges: data = np.array([list(dates), np.linspace(start, stop, len(dates))]) data_df = pd.DataFrame.from_records( data.T, columns=["calendar month", "open accounts"], ) dataframe = project.log_experiment().log_dataframe(data_df, name="open accounts") if DISPLAY_DFS: print(f"dataframe {dataframe.id}") display(data_df.head())DataframePlot( experiments=project.experiments(), dataframe_name="open accounts", x="calendar month", y="open accounts", plotting_func=px.line, ).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/viz/metric-correlation-plot.ipynb
import random from rubicon_ml import Rubicon from rubicon_ml.viz import MetricCorrelationPlotrubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.get_or_create_project("metric correlation plot") for i in range(0, 100): experiment = project.log_experiment() experiment.log_parameter( name="is_standardized", value=random.choice([True, False]), ) experiment.log_parameter(name="n_estimators", value=random.randrange(2, 10, 2)) experiment.log_parameter( name="sample", value=random.choice(["A", "B", "C", "D", "E"]), ) experiment.log_metric(name="accuracy", value=random.random()) experiment.log_metric(name="confidence", value=random.random())MetricCorrelationPlot( experiments=project.experiments(), selected_metric="accuracy", ).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/viz/experiments-table.ipynb
import random from rubicon_ml import Rubicon from rubicon_ml.viz import ExperimentsTablerubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.get_or_create_project("experiment table") for i in range(0, 24): experiment = project.log_experiment() experiment.log_parameter(name="max_depth", value=random.randrange(5, 25, 5)) experiment.log_parameter(name="n_estimators", value=random.randrange(2, 12, 2)) experiment.log_metric(name="accuracy", value=random.random())ExperimentsTable( experiments=project.experiments(), ).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/viz/dashboard.ipynb
import random import numpy as np import pandas as pd from rubicon_ml import Rubicon from rubicon_ml.viz import ( DataframePlot, ExperimentsTable, MetricCorrelationPlot, MetricListsComparison, ) from rubicon_ml.viz.dashboard import Dashboarddates = pd.date_range(start="1/1/2010", end="12/1/2020", freq="MS") rubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.get_or_create_project("dashboard composition") for i in range(0, 10): experiment = project.log_experiment() experiment.log_parameter( name="is_standardized", value=random.choice([True, False]), ) experiment.log_parameter(name="n_estimators", value=random.randrange(2, 10, 2)) experiment.log_parameter( name="sample", value=random.choice(["A", "B", "C", "D", "E"]), ) experiment.log_metric(name="accuracy", value=random.random()) experiment.log_metric(name="confidence", value=random.random()) experiment.log_metric( name="coefficients", value=[random.random() for _ in range(0, 5)], ) experiment.log_metric( name="stderr", value=[random.random() for _ in range(0, 5)], ) data = np.array( [ list(dates), np.linspace(random.randint(0, 15000), random.randint(0, 15000), len(dates)) ] ) data_df = pd.DataFrame.from_records( data.T, columns=["calendar month", "open accounts"], ) experiment.log_dataframe(data_df, name="open accounts")default_dashbaord = Dashboard(experiments=project.experiments()) default_dashbaord.show()Dashboard( experiments=project.experiments(), widgets=[ [ ExperimentsTable(is_selectable=True), MetricCorrelationPlot(selected_metric="accuracy"), ], [ MetricListsComparison(column_names=[f"var_00{i}" for i in range(0, 5)]), DataframePlot(dataframe_name="open accounts"), ], ], ).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/viz/metric-lists-comparisons.ipynb
import random from rubicon_ml import Rubicon from rubicon_ml.viz import MetricListsComparisonrubicon = Rubicon(persistence="memory", auto_git_enabled=True) project = rubicon.get_or_create_project("list metric comparison") for i in range(0, 10): experiment = project.log_experiment() experiment.log_metric( name="coefficients", value=[random.random() for _ in range(0, 25)], ) experiment.log_metric( name="p-values", value=[random.random() for _ in range(0, 25)], ) experiment.log_metric( name="stderr", value=[random.random() for _ in range(0, 25)], )MetricListsComparison( experiments=project.experiments(), column_names=["intercept"] + [f"var_{i:03}" for i in range(1, 25)], ).show()
0
capitalone_repos/rubicon-ml/notebooks
capitalone_repos/rubicon-ml/notebooks/tutorials/failure-modes.ipynb
from rubicon_ml import Rubicon rb = Rubicon(persistence="memory") rb.get_project(name="failure modes")from rubicon_ml import set_failure_mode set_failure_mode("warn") rb.get_project(name="failure modes")set_failure_mode("log") rb.get_project(name="failure modes")set_failure_mode("log", traceback_limit=0) rb.get_project(name="failure modes")set_failure_mode("log", traceback_chain=True) rb.get_project(name="failure modes")rb.create_project(name="failure modes") project = rb.get_project(name="failure modes") print(project)print(project.id)set_failure_mode("log") project = rb.get_project(name="failure modes v2") print(project)if project is not None: print(project.id)project = rb.create_project(name="failure modes v3") experiment = project.log_experiment() experimentclass BrokenFilesystem: pass rb.config.repository.filesystem = BrokenFilesystem() set_failure_mode("raise")from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=1) X_train, y_train, X_test, y_test = [[0, 1, 2, 3]], [0], [[0, 1, 2, 3]], [0] knn.fit(X_train, y_train) experiment.log_parameter(name="n_neighbors", value=1) score = knn.score(X_test, y_test) experiment.log_metric(name="score", value=score) scoreset_failure_mode("log") knn = KNeighborsClassifier(n_neighbors=1) X_train, y_train, X_test, y_test = [[0, 1, 2, 3]], [0], [[0, 1, 2, 3]], [0] knn.fit(X_train, y_train) experiment.log_parameter(name="n_neighbors", value=1) score = knn.score(X_test, y_test) experiment.log_metric(name="score", value=score) score
0
capitalone_repos/rubicon-ml
capitalone_repos/rubicon-ml/tests/fixtures.py
import os import random import uuid import dask.array as da import dask.dataframe as dd import numpy as np import pandas as pd import pytest from dask.distributed import Client from sklearn.datasets import make_classification from rubicon_ml import Rubicon from rubicon_ml.repository import MemoryRepository class _AnotherObject: """Another object to log for schema testing.""" def __init__(self): self.another_parameter = 100 self.another_metric = 100 class _ObjectToLog: """An object to log for schema testing.""" def __init__(self): """Initialize an object to log.""" self.object_ = _AnotherObject() self.feature_names_ = ["var_001", "var_002"] self.other_feature_names_ = ["var_003", "var_004"] self.feature_importances_ = [0.75, 0.25] self.feature_name_ = "var_005" self.other_feature_name_ = "var_006" self.feature_importance_ = 1.0 self.dataframe = pd.DataFrame([[100, 0], [0, 100]], columns=["x", "y"]) self.parameter = 100 self.metric = 100 def metric_function(self): return self.metric def artifact_function(self): return self def dataframe_function(self): return pd.DataFrame([[100, 0], [0, 100]], columns=["x", "y"]) def erroring_function(self): raise RuntimeError("raised from `_ObjectToLog.erroring_function`") class _MockCompletedProcess: """Use to mock a CompletedProcess result from `subprocess.run()`.""" def __init__(self, stdout="", returncode=0): self.stdout = stdout self.returncode = returncode @pytest.fixture def mock_completed_process_empty(): return _MockCompletedProcess(stdout=b"\n") @pytest.fixture def mock_completed_process_git(): return _MockCompletedProcess(stdout=b"origin github.com (fetch)\n") @pytest.fixture def rubicon_client(): """Setup an instance of rubicon configured to log to memory and clean it up afterwards. """ from rubicon_ml import Rubicon rubicon = Rubicon(persistence="memory", root_dir="./") # teardown after yield yield rubicon rubicon.repository.filesystem.rm(rubicon.config.root_dir, recursive=True) @pytest.fixture def rubicon_composite_client(): """Setup an instance of rubicon configured to log to two memory backends and clean it up afterwards. """ from rubicon_ml import Rubicon rubicon = Rubicon( composite_config=[ {"persistence": "memory", "root_dir": "a"}, {"persistence": "memory", "root_dir": "b"}, ], ) # teardown after yield yield rubicon for i, repository in enumerate(rubicon.repositories): repository.filesystem.rm( rubicon.config.storage_options["composite_config"][i]["root_dir"], recursive=True, ) @pytest.fixture def rubicon_local_filesystem_client(): """Setup an instance of rubicon configured to log to the filesystem and clean it up afterwards. """ from rubicon_ml import Rubicon rubicon = Rubicon( persistence="filesystem", root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubicon"), ) # teardown after yield yield rubicon rubicon.repository.filesystem.rm(rubicon.config.root_dir, recursive=True) @pytest.fixture def rubicon_local_filesystem_client_with_project(rubicon_local_filesystem_client): rubicon = rubicon_local_filesystem_client project_name = "Test Project" project = rubicon.get_or_create_project(project_name, description="testing") return rubicon, project @pytest.fixture def project_client(rubicon_client): """Setup an instance of rubicon configured to log to memory with a default project and clean it up afterwards. """ rubicon = rubicon_client project_name = "Test Project" project = rubicon.get_or_create_project( project_name, description="In memory project for testing." ) return project @pytest.fixture def project_composite_client(rubicon_composite_client): """Setup an instance of rubicon configured to log to two memory backends with a default project and clean it up afterwards. """ rubicon = rubicon_composite_client project_name = "Test Project" project = rubicon.get_or_create_project( project_name, description="In memory project for testing." ) return project @pytest.fixture def rubicon_and_project_client(rubicon_client): """Setup an instance of rubicon configured to log to memory with a default project and clean it up afterwards. Expose both the rubicon instance and the project. """ rubicon = rubicon_client project_name = "Test Project" project = rubicon.get_or_create_project( project_name, description="In memory project for testing.", github_url="test.github.url.git", ) return (rubicon, project) @pytest.fixture def rubicon_and_project_client_with_experiments(rubicon_and_project_client): """Setup an instance of rubicon configured to log to memory with a default project with experiments and clean it up afterwards. Expose both the rubicon instance and the project. """ rubicon, project = rubicon_and_project_client for e in range(0, 10): experiment = project.log_experiment( tags=["testing"], commit_hash=str(int(e / 3)), training_metadata=("training", "metadata"), ) experiment.log_parameter("n_estimators", e + 1) experiment.log_feature("year") experiment.log_metric("accuracy", (80 + e)) return (rubicon, project) @pytest.fixture def test_dataframe(): """Create a test dataframe which can be logged to a project or experiment.""" import pandas as pd from dask import dataframe as dd return dd.from_pandas( pd.DataFrame.from_records([[0, 1]], columns=["a", "b"]), npartitions=1, ) @pytest.fixture def memory_repository(): """Setup an in-memory repository and clean it up afterwards.""" root_dir = "/in-memory-root" repository = MemoryRepository(root_dir) yield repository repository.filesystem.rm(root_dir, recursive=True) @pytest.fixture def fake_estimator_cls(): """A fake estimator that exposes the same API as a sklearn estimator so we can test without relying on sklearn. """ class FakeEstimator: def __init__(self, params=None): if params is None: params = {"max_df": 0.75, "lowercase": True, "ngram_range": (1, 2)} self.params = params def get_params(self): return self.params def fit(self): pass def transform(self): pass return FakeEstimator @pytest.fixture def viz_experiments(rubicon_and_project_client): """Returns a list of experiments with the parameters, metrics, and dataframes required to test the `viz` module. """ rubicon, project = rubicon_and_project_client dates = pd.date_range(start="1/1/2010", end="12/1/2020", freq="MS") for i in range(0, 10): experiment = project.log_experiment( commit_hash="1234567", model_name="test model name", name="test name", tags=["test tag"], ) experiment.log_parameter(name="test param 0", value=random.choice([True, False])) experiment.log_parameter(name="test param 1", value=random.randrange(2, 10, 2)) experiment.log_parameter( name="test param 2", value=random.choice(["A", "B", "C", "D", "E"]) ) experiment.log_metric(name="test metric 0", value=random.random()) experiment.log_metric(name="test metric 1", value=random.random()) experiment.log_metric(name="test metric 2", value=[random.random() for _ in range(0, 5)]) experiment.log_metric(name="test metric 3", value=[random.random() for _ in range(0, 5)]) data = np.array( [ list(dates), np.linspace(random.randint(0, 15000), random.randint(0, 15000), len(dates)), ] ) data_df = pd.DataFrame.from_records(data.T, columns=["test x", "test y"]) experiment.log_dataframe(data_df, name="test dataframe") return project.experiments() @pytest.fixture def objects_to_log(): """Returns objects for testing.""" return _ObjectToLog(), _AnotherObject() @pytest.fixture def another_object_schema(): """Returns a schema representing ``_AnotherObject``.""" return { "parameters": [{"name": "another_parameter", "value_attr": "another_parameter"}], "metrics": [{"name": "another_metric", "value_attr": "another_metric"}], } @pytest.fixture def artifact_schema(): """Returns a schema for testing artifacts.""" return { "artifacts": [ "self", {"name": "object_", "data_object_attr": "object_"}, {"name": "object_b", "data_object_func": "artifact_function"}, ] } @pytest.fixture def dataframe_schema(): """Returns a schema for testing dataframes.""" return { "dataframes": [ {"name": "dataframe", "df_attr": "dataframe"}, {"name": "dataframe_b", "df_func": "dataframe_function"}, ] } @pytest.fixture def feature_schema(): """Returns a schema for testing features.""" return { "features": [ { "names_attr": "feature_names_", "importances_attr": "feature_importances_", }, {"names_attr": "other_feature_names_"}, {"name_attr": "feature_name_", "importance_attr": "feature_importance_"}, {"name_attr": "other_feature_name_"}, ] } @pytest.fixture def metric_schema(): """Returns a schema for testing metrics.""" return { "metrics": [ {"name": "metric_a", "value_attr": "metric"}, {"name": "metric_b", "value_env": "METRIC"}, {"name": "metric_c", "value_func": "metric_function"}, ], } @pytest.fixture def parameter_schema(): """Returns a schema for testing parameters.""" return { "parameters": [ {"name": "parameter_a", "value_attr": "parameter"}, {"name": "parameter_b", "value_env": "PARAMETER"}, ], } @pytest.fixture def nested_schema(): """Returns a schema for testing nested schema.""" return {"schema": [{"name": "AnotherObject", "attr": "object_"}]} @pytest.fixture def optional_schema(): """Returns a schema for testing optional attributes.""" return { "artifacts": [ { "name": "object", "data_object_attr": "missing_object", "optional": "true", }, { "name": "object_b", "data_object_func": "missing_object_func", "optional": "true", }, ], "dataframes": [ {"name": "dataframe", "df_attr": "missing_dataframe", "optional": "true"}, { "name": "dataframe_b", "df_func": "missing_dataframe_func", "optional": "true", }, ], "features": [ {"names_attr": "missing_feature_names", "optional": "true"}, {"name_attr": "missing_feature_name", "optional": "true"}, ], "metrics": [ {"name": "metric_a", "value_attr": "missing_metric", "optional": "true"}, {"name": "metric_b", "value_env": "MISSING_METRIC", "optional": "true"}, { "name": "metric_c", "value_func": "missing_metric_func", "optional": "true", }, ], "parameters": [ { "name": "parameter_a", "value_attr": "missing_parameter", "optional": "true", }, { "name": "parameter_b", "value_env": "MISSING_PARAMETER", "optional": "true", }, ], "schema": [ { "name": "MissingObject", "attr": "another_missing_object", "optional": "true", } ], } @pytest.fixture def hierarchical_schema(): """Returns a schema for testing hierarchical schema.""" return {"children": [{"name": "AnotherObject", "attr": "children"}]} @pytest.fixture def rubicon_project(): """Returns an in-memory rubicon project for testing.""" rubicon = Rubicon(persistence="memory", root_dir="/tmp") random_name = str(uuid.uuid4()) return rubicon.create_project(name=random_name) @pytest.fixture def make_classification_array(): """Returns classification data generated by scikit-learn as an array.""" X, y = make_classification( n_samples=1000, n_features=10, n_informative=5, n_redundant=5, n_classes=2, class_sep=1, random_state=3211, ) return X, y @pytest.fixture def make_classification_df(make_classification_array): """Returns classification data generated by scikit-learn as dataframes.""" X, y = make_classification_array X_df = pd.DataFrame(X, columns=[f"var_{i}" for i in range(10)]) return X_df, y @pytest.fixture def dask_client(): """Returns a dask client and shuts it down upon test completion.""" client = Client() yield client client.shutdown() @pytest.fixture def make_classification_dask_array(make_classification_array): """Returns classification data generated by scikit-learn as a dask array.""" X, y = make_classification_array X_da, y_da = da.from_array(X), da.from_array(y) return X_da, y_da @pytest.fixture def make_classification_dask_df(make_classification_df): """Returns classification data generated by scikit-learn as dataframes.""" X, y = make_classification_df X_df, y_da = dd.from_pandas(X, npartitions=1), da.from_array(y) return X_df, y_da
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/notebooks/test_notebooks.py
import os from unittest import mock import fsspec import pytest from nbconvert.preprocessors import ExecutePreprocessor from tests.notebooks.utils import get_notebook_filenames, read_notebook_file NOTEBOOK_FILENAMES = get_notebook_filenames( os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "notebooks") ) BAD_NOTEBOOK_FILENAMES = get_notebook_filenames( os.path.join(os.path.dirname(__file__), "bad-notebooks") ) BAD_NOTEBOOK_XFAIL_MARKS = [ pytest.param( n, marks=pytest.mark.xfail( reason=f"`test_notebook_is_executed_in_order` for notebook {n} is expected to fail" ), ) for n in BAD_NOTEBOOK_FILENAMES ] @pytest.mark.run_notebooks @pytest.mark.parametrize("notebook_filename", NOTEBOOK_FILENAMES + BAD_NOTEBOOK_XFAIL_MARKS) def test_notebook_is_executed_in_order(notebook_filename): notebook = read_notebook_file(notebook_filename) execution_counts = [ cell.get("execution_count") for cell in notebook.cells if cell.get("cell_type") == "code" ] is_all_cells_executed = all([ec is not None for ec in execution_counts]) if not is_all_cells_executed: failure_message = "all code cells are not executed" is_last_cell_executed = execution_counts[-1] is not None if not is_last_cell_executed: failure_message += " - there might be an empty cell at the end" pytest.fail(failure_message) is_cell_execution_ordered = all( execution_counts[i] < execution_counts[i + 1] for i in range(len(execution_counts) - 1) ) if not is_cell_execution_ordered: pytest.fail("code cells are executed out of order") IGNORE_EXECUTE_NOTEBOOK_FILENAMES = [ "classification.ipynb", "failure-modes.ipynb", "integration-prefect-workflows.ipynb", "logging-feature-plots.ipynb", "visualizing-experiments.ipynb", ] EXECUTE_NOTEBOOK_FILENAMES = [ n for n in NOTEBOOK_FILENAMES if os.path.split(n)[-1] not in IGNORE_EXECUTE_NOTEBOOK_FILENAMES ] @mock.patch.dict(os.environ, {"RUBICON_ROOT": "test-rubicon-root"}) @pytest.mark.run_notebooks @pytest.mark.parametrize("notebook_filename", EXECUTE_NOTEBOOK_FILENAMES) def test_notebooks_execute_without_error(notebook_filename): notebook = read_notebook_file(notebook_filename) resources = {"metadata": {"path": os.path.dirname(notebook_filename)}} preprocessor = ExecutePreprocessor(kernel_name="python3", timeout=60) preprocessor.preprocess(notebook, resources=resources) repo_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) notebook_output_dir = os.path.join(repo_root, "notebooks", "test-rubicon-root") if "logging-experiments.ipynb" not in notebook_filename: fs = fsspec.filesystem("file") try: fs.rm(notebook_output_dir, recursive=True) except FileNotFoundError: pass # some notebooks don't write output
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/notebooks/utils.py
import json import os import fsspec import nbformat DEFAULT_NBFORMAT_VERSION = 4 def get_notebook_filenames(root_path): fs = fsspec.filesystem("file") notebook_glob = os.path.join(root_path, "*.ipynb") nested_notebook_glob = os.path.join(root_path, "**", "*.ipynb") notebook_filenames = fs.glob(notebook_glob) + fs.glob(nested_notebook_glob) return [n for n in notebook_filenames if ".ipynb_checkpoints" not in n] def read_notebook_file(notebook_filename): fs = fsspec.filesystem("file") with fs.open(notebook_filename, "r") as notebook_file: notebook = notebook_file.read() notebook_json = json.loads(notebook) notebook_version = notebook_json.get("nbformat", DEFAULT_NBFORMAT_VERSION) notebook = nbformat.reads(notebook, as_version=notebook_version) return notebook
0
capitalone_repos/rubicon-ml/tests/notebooks
capitalone_repos/rubicon-ml/tests/notebooks/bad-notebooks/not-executed.ipynb
x = 1y = 2z = 3
0
capitalone_repos/rubicon-ml/tests/notebooks
capitalone_repos/rubicon-ml/tests/notebooks/bad-notebooks/empty-last-cell.ipynb
x = 1y = 2z = 3
0
capitalone_repos/rubicon-ml/tests/notebooks
capitalone_repos/rubicon-ml/tests/notebooks/bad-notebooks/not-executed-in-order.ipynb
x = 1y = 2z = 3
0
capitalone_repos/rubicon-ml/tests/notebooks
capitalone_repos/rubicon-ml/tests/notebooks/bad-notebooks/not-all-executed.ipynb
x = 1y = 2z = 3
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/integration/test_misc_dotfiles.py
import os import warnings def test_rubicon_with_misc_folders_at_project_level(rubicon_local_filesystem_client_with_project): rubicon, project = rubicon_local_filesystem_client_with_project os.makedirs(os.path.join(rubicon.config.root_dir, ".ipynb_checkpoints")) with warnings.catch_warnings(record=True) as w: projects = rubicon.projects() assert len(projects) == 1 assert "not found" in str(w[-1].message) def test_rubicon_with_misc_folders_at_sublevel_level(rubicon_local_filesystem_client_with_project): rubicon, project = rubicon_local_filesystem_client_with_project project.log_experiment("exp1") project.log_experiment("exp2") os.makedirs( os.path.join(rubicon.config.root_dir, "test-project", "experiments", ".ipynb_checkpoints") ) with warnings.catch_warnings(record=True) as w: experiments = project.experiments() assert len(experiments) == 2 assert "not found" in str(w[-1].message) def test_rubicon_with_misc_folders_at_deeper_sublevel_level( rubicon_local_filesystem_client_with_project, ): rubicon, project = rubicon_local_filesystem_client_with_project exp = project.log_experiment("exp1") exp.log_parameter("a", 1) os.makedirs( os.path.join( rubicon.config.root_dir, "test-project", "experiments", exp.id, "parameters", ".ipynb_checkpoints", ) ) with warnings.catch_warnings(record=True) as w: parameters = exp.parameters() assert len(parameters) == 1 assert "not found" in str(w[-1].message)
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/integration/test_dataframe_logging.py
import pandas as pd import pytest from dask import dataframe as dd from rubicon_ml.exceptions import RubiconException def test_pandas_df(rubicon_local_filesystem_client): rubicon = rubicon_local_filesystem_client project = rubicon.create_project("Dataframe Test Project") multi_index_df = pd.DataFrame( [[0, 1, "a"], [1, 1, "b"], [2, 2, "c"], [3, 2, "d"]], columns=["a", "b", "c"] ) multi_index_df = multi_index_df.set_index(["b", "a"]) written_dataframe = project.log_dataframe(multi_index_df) read_dataframes = project.dataframes() read_dataframe = read_dataframes[0] assert len(read_dataframes) == 1 assert read_dataframe.id == written_dataframe.id assert read_dataframe.get_data().equals(multi_index_df) def test_dask_df(rubicon_local_filesystem_client): rubicon = rubicon_local_filesystem_client project = rubicon.create_project("Dataframe Test Project") ddf = dd.from_pandas(pd.DataFrame([0, 1], columns=["a"]), npartitions=1) written_dataframe = project.log_dataframe(ddf) read_dataframes = project.dataframes() read_dataframe = read_dataframes[0] assert len(read_dataframes) == 1 assert read_dataframe.id == written_dataframe.id assert read_dataframe.get_data(df_type="dask").compute().equals(ddf.compute()) def test_df_read_error(rubicon_local_filesystem_client): rubicon = rubicon_local_filesystem_client project = rubicon.create_project("Dataframe Test Project") ddf = dd.from_pandas(pd.DataFrame([0, 1], columns=["a"]), npartitions=1) written_dataframe = project.log_dataframe(ddf) read_dataframes = project.dataframes() read_dataframe = read_dataframes[0] assert len(read_dataframes) == 1 assert read_dataframe.id == written_dataframe.id # simulate user forgetting to set `df_type` to `dask` when reading a logged dask df with pytest.raises(RubiconException) as e: read_dataframe.get_data() assert ( "This might have happened if you forgot to set `df_type='dask'` when trying to read a `dask` dataframe." in str(e) )
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/integration/test_prefect_flow.py
import numpy as np import pandas as pd from prefect import Flow from rubicon_ml import Rubicon from rubicon_ml.client import ( Artifact, Dataframe, Experiment, Feature, Metric, Parameter, Project, ) from rubicon_ml.workflow.prefect import ( create_experiment_task, get_or_create_project_task, log_artifact_task, log_dataframe_task, log_feature_task, log_metric_task, log_parameter_task, ) def test_flow(): persistence = "memory" root_dir = "./" project_name = "Prefect Integration Test" df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=["a", "b", "c"]) artifact = b"byte artifact" with Flow("testing-rubicon-tasks") as flow: project_t = get_or_create_project_task(persistence, root_dir, project_name) experiment_t = create_experiment_task(project_t) feature_t = log_feature_task(experiment_t, "test feature") parameter_t = log_parameter_task(experiment_t, "test parameter", 0) metric_t = log_metric_task(experiment_t, "test metric", 0) dataframe_t = log_dataframe_task(experiment_t, df, description="a test df") artifact_t = log_artifact_task(experiment_t, data_bytes=artifact, name="my artifact") assert len(flow.tasks) == 7 state = flow.run() assert state.is_successful() # outside of the flow, the objects are Task references assert state.result[project_t].is_successful() assert state.result[experiment_t].is_successful() assert state.result[feature_t].is_successful() assert state.result[parameter_t].is_successful() assert state.result[metric_t].is_successful() assert state.result[dataframe_t].is_successful() assert state.result[artifact_t].is_successful() assert isinstance(state.result[project_t].result, Project) assert isinstance(state.result[experiment_t].result, Experiment) assert isinstance(state.result[feature_t].result, Feature) assert isinstance(state.result[parameter_t].result, Parameter) assert isinstance(state.result[metric_t].result, Metric) assert isinstance(state.result[dataframe_t].result, Dataframe) assert isinstance(state.result[artifact_t].result, Artifact) # use Rubicon to grab the logged data rubicon = Rubicon(persistence, root_dir) project = rubicon.get_project(project_name) assert project.name == project_name experiments = project.experiments() assert len(experiments) == 1 experiment = experiments[0] # features features = experiment.features() assert len(features) == 1 assert features[0].name == "test feature" # metrics metrics = experiment.metrics() assert len(metrics) == 1 assert metrics[0].name == "test metric" assert metrics[0].value == 0 # parameters parameters = experiment.parameters() assert len(parameters) == 1 assert parameters[0].name == "test parameter" assert parameters[0].value == 0 # dataframes dataframes = experiment.dataframes() assert len(dataframes) == 1 assert dataframes[0].description == "a test df" assert df.equals(dataframes[0].get_data()) # artifacts artifacts = experiment.artifacts() assert len(artifacts) == 1 assert artifacts[0].name == "my artifact" assert artifacts[0].data == artifact
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/integration/test_schema.py
import pytest from lightgbm import LGBMClassifier, LGBMRegressor from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier, XGBRegressor from xgboost.dask import DaskXGBClassifier, DaskXGBRegressor PANDAS_SCHEMA_CLS = [ LGBMClassifier, LGBMRegressor, RandomForestClassifier, XGBClassifier, XGBRegressor, ] DASK_SCHEMA_CLS = [DaskXGBClassifier, DaskXGBRegressor] def _fit_and_log(X, y, schema_cls, rubicon_project): model = schema_cls() model.fit(X, y) rubicon_project.log_with_schema(model) @pytest.mark.integration @pytest.mark.parametrize("schema_cls", PANDAS_SCHEMA_CLS) def test_estimator_schema_fit_array(schema_cls, make_classification_array, rubicon_project): X, y = make_classification_array _fit_and_log(X, y, schema_cls, rubicon_project) @pytest.mark.integration @pytest.mark.parametrize("schema_cls", PANDAS_SCHEMA_CLS) def test_estimator_schema_fit_df(schema_cls, make_classification_df, rubicon_project): X, y = make_classification_df _fit_and_log(X, y, schema_cls, rubicon_project) @pytest.mark.integration @pytest.mark.parametrize("schema_cls", DASK_SCHEMA_CLS) def test_estimator_schema_fit_dask_array( schema_cls, make_classification_dask_array, rubicon_project, dask_client, ): X_da, y_da = make_classification_dask_array _fit_and_log(X_da, y_da, schema_cls, rubicon_project) @pytest.mark.integration @pytest.mark.parametrize("schema_cls", DASK_SCHEMA_CLS) def test_estimator_schema_fit_dask_df( schema_cls, make_classification_dask_df, rubicon_project, dask_client ): X_df, y_da = make_classification_dask_df _fit_and_log(X_df, y_da, schema_cls, rubicon_project)
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/integration/test_concurrency.py
import multiprocessing import pandas as pd from dask import dataframe as dd from rubicon_ml.domain.utils import uuid def _log_all_to_experiment(experiment): ddf = dd.from_pandas(pd.DataFrame([0, 1], columns=["a"]), npartitions=1) for _ in range(0, 4): experiment.log_metric(uuid.uuid4(), 0) experiment.log_feature(uuid.uuid4()) experiment.log_parameter(uuid.uuid4(), 1) experiment.log_artifact(data_bytes=b"artifact bytes", name=uuid.uuid4()) experiment.log_dataframe(ddf) experiment.add_tags([uuid.uuid4()]) def _read_all_from_experiment(experiment): for _ in range(0, 4): experiment.metrics() experiment.features() experiment.parameters() experiment.artifacts() experiment.dataframes() experiment.tags def test_filesystem_concurrency(rubicon_local_filesystem_client): rubicon = rubicon_local_filesystem_client project = rubicon.create_project("Test Concurrency") experiment = project.log_experiment() processes = [] for i in range(0, 4): process = multiprocessing.Process(target=_read_all_from_experiment, args=[experiment]) process.start() processes.append(process) for i in range(0, 4): process = multiprocessing.Process(target=_log_all_to_experiment, args=[experiment]) process.start() processes.append(process) for process in processes: process.join() assert len(experiment.metrics()) == 16 assert len(experiment.features()) == 16 assert len(experiment.parameters()) == 16 assert len(experiment.artifacts()) == 16 assert len(experiment.dataframes()) == 16 assert len(experiment.tags) == 16
0
capitalone_repos/rubicon-ml/tests
capitalone_repos/rubicon-ml/tests/integration/test_rubicon.py
import uuid import pandas as pd import pytest from rubicon_ml import Rubicon filesystems = [ pytest.param(Rubicon(persistence="memory")), pytest.param( Rubicon(persistence="filesystem", root_dir="./test-rubicon"), marks=pytest.mark.write_files, ), pytest.param( Rubicon(persistence="filesystem", root_dir="s3://change-me"), marks=pytest.mark.write_files, ), pytest.param( Rubicon( composite_config=[ {"persistence": "memory", "root_dir": "./memory/root"}, {"persistence": "filesystem", "root_dir": "./test-rubicon"}, ] ), marks=pytest.mark.write_files, ), ] @pytest.mark.parametrize("rubicon", filesystems) def test_rubicon(rubicon, request): for repository in rubicon.repositories: if "change-me" in repository.root_dir: root_dir = request.config.getoption("s3-path") if root_dir is None: pytest.fail("`root_dir` cannot be None. Run `pytest` with `--s3-path`.") repository.root_dir = root_dir written_project = rubicon.create_project(name=f"Test Project {uuid.uuid4()}") written_experiment = written_project.log_experiment(name=f"Test Experiment {uuid.uuid4()}") written_experiment.add_tags(["x", "y"]) written_experiment.remove_tags(["x"]) written_feature = written_experiment.log_feature(name=f"Test Feature {uuid.uuid4()}") written_parameter = written_experiment.log_parameter( name=f"Test Parameter {uuid.uuid4()}", value=8 ) written_metric = written_experiment.log_metric(name=f"Test Feature {uuid.uuid4()}", value=24) written_project_artifact = written_project.log_artifact( name=f"Test Artifact {uuid.uuid4()}", data_bytes=b"test artifact data" ) written_experiment_artifact = written_experiment.log_artifact( name=f"Test Artifact {uuid.uuid4()}", data_bytes=b"test artifact data" ) written_project_dataframe = written_project.log_dataframe( df=pd.DataFrame([[0, 1], [1, 0]], columns=["a", "b"]) ) json_dict = {"hello": "world", "numbers": [1, 2, 3]} written_project_json = written_project.log_json( name=f"Test JSON {uuid.uuid4()}.json", json_object=json_dict ) written_experiment_json = written_experiment.log_json( name=f"Test JSON {uuid.uuid4()}.json", json_object=json_dict ) written_project_dataframe.add_tags(["x", "y"]) written_project_dataframe.remove_tags(["x"]) read_project = rubicon.get_project(name=written_project.name) assert written_project.id == read_project.id read_experiments = read_project.experiments() assert len(read_experiments) == 1 assert written_experiment.id == read_experiments[0].id read_experiment = read_experiments[0] assert written_experiment.tags == read_experiment.tags read_features = read_experiment.features() assert len(read_features) == 1 assert written_feature.id == read_features[0].id read_parameters = read_experiment.parameters() assert len(read_parameters) == 1 assert written_parameter.id == read_parameters[0].id assert written_parameter.value == read_parameters[0].value read_metrics = read_experiment.metrics() assert len(read_metrics) == 1 assert written_metric.id == read_metrics[0].id assert written_metric.value == read_metrics[0].value read_project_artifacts = read_project.artifacts() assert len(read_project_artifacts) == 2 assert written_project_artifact.id == read_project_artifacts[0].id assert written_project_artifact.data == read_project_artifacts[0].data assert written_project_json.id == read_project_artifacts[1].id assert written_project_json.data == read_project_artifacts[1].data read_project.delete_artifacts([artifact.id for artifact in read_project_artifacts]) assert len(read_project.artifacts()) == 0 read_experiment_artifacts = read_experiment.artifacts() assert len(read_experiment_artifacts) == 2 assert written_experiment_artifact.id == read_experiment_artifacts[0].id assert written_experiment_artifact.data == read_experiment_artifacts[0].data assert written_experiment_json.id == read_experiment_artifacts[1].id assert written_experiment_json.data == read_experiment_artifacts[1].data assert json_dict == read_experiment_artifacts[1].get_json() read_project_dataframes = read_project.dataframes() assert len(read_project_dataframes) == 1 assert written_project_dataframe.id == read_project_dataframes[0].id assert written_project_dataframe.get_data().equals(read_project_dataframes[0].get_data()) assert written_project_dataframe.tags == read_project_dataframes[0].tags read_project.delete_dataframes([read_project_dataframes[0].id]) assert len(read_project.dataframes()) == 0 for repository in rubicon.repositories: repository.filesystem.rm(repository.root_dir, recursive=True)

No dataset card yet

Contribute a Dataset Card
Downloads last month
20