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)
|
0 | capitalone_repos/rubicon-ml/tests | capitalone_repos/rubicon-ml/tests/unit/test_cli.py | import warnings
from unittest.mock import patch
import click
from click.testing import CliRunner
from rubicon_ml.cli import cli
def mock_click_output(**server_args):
click.echo("Running the mock server")
@patch("rubicon_ml.viz.dashboard.Dashboard.serve")
@patch("rubicon_ml.client.rubicon.Rubicon.projects")
@patch("rubicon_ml.client.rubicon.Rubicon.get_project")
def test_cli(mock_get_project, mock_projects, mock_run_server, project_client):
mock_get_project.return_value = project_client
mock_projects.return_value = [project_client]
mock_run_server.side_effect = mock_click_output
with warnings.catch_warnings(record=True) as caught_warnings:
runner = CliRunner()
result = runner.invoke(
cli,
["ui", "--root-dir", "/path/to/root", "--page-size", 100],
)
assert result.exit_code == 0
assert "Running the mock server" in result.output
assert len(caught_warnings) == 2
assert "`--page-size` option will be deprecated" in str(caught_warnings[0])
assert "`--project-name` will be a required option" in str(caught_warnings[1])
def _set_up_rubicon_project(project):
NUM_EXPERIMENTS = 4
for _ in range(NUM_EXPERIMENTS):
tags = ["a", "b", "c"]
ex = project.log_experiment(tags=tags)
for feature in ["f", "g", "h", "i"]:
ex.log_feature(name=feature)
for parameter in [("d", 100), ("e", 1000), ("f", 1000)]:
name, value = parameter
ex.log_parameter(name=name, value=value)
for metric in ["j", "k"]:
value = 1
tags = ["l", "m", "n"]
ex.log_metric(name=metric, value=value, tags=tags)
ex.log_artifact(name="o", data_bytes=b"o")
project.log_artifact(name="p", data_bytes=b"p")
return project
def test_search_cli_base(rubicon_local_filesystem_client_with_project):
_, project = rubicon_local_filesystem_client_with_project
QUERY = "$..experiment[*].metric"
project = _set_up_rubicon_project(project=project)
runner = CliRunner()
result_a = runner.invoke(
cli,
[
"search",
"--root-dir",
project.repository.root_dir,
"--project-name",
project.name,
QUERY,
],
env={"RUBICON_PROJECT_NAME": None, "RUBICON_ROOT_DIR": None},
)
assert result_a.exit_code == 0
def test_search_cli_exp_fail(rubicon_local_filesystem_client_with_project):
_, project = rubicon_local_filesystem_client_with_project
QUERY = "$..experiment[*].metric"
project = _set_up_rubicon_project(project=project)
runner = CliRunner()
result_a = runner.invoke(
cli, ["search", QUERY], env={"RUBICON_PROJECT_NAME": None, "RUBICON_ROOT_DIR": None}
)
result_b = runner.invoke(
cli,
[
"search",
"--root-dir",
project.repository.root_dir,
"--project-name",
"NON-EXISTENT-PROJECT",
QUERY,
],
env={"RUBICON_PROJECT_NAME": None, "RUBICON_ROOT_DIR": None},
)
assert "No --root-dir or --project-name provided. Exiting..." in result_a.output
assert "No project with name 'NON-EXISTENT-PROJECT' found." in result_b.output
assert result_a.exit_code == 1
assert result_b.exit_code == 1
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/domain/test_mixin.py | from rubicon_ml.domain.mixin import TagMixin
class Taggable(TagMixin):
def __init__(self, tags=[]):
self.tags = tags
def test_add_tags():
taggable = Taggable()
taggable.add_tags(["x"])
assert taggable.tags == ["x"]
def test_add_duplicate_tags():
taggable = Taggable(tags=["x"])
taggable.add_tags(["x"])
assert taggable.tags == ["x"]
def test_remove_tags():
taggable = Taggable(tags=["x", "y"])
taggable.remove_tags(["x"])
assert taggable.tags == ["y"]
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/domain/test_metric.py | import pytest
from rubicon_ml.domain import Metric
def test_metric_throws_error_if_invalid_directionality():
with pytest.raises(ValueError) as e:
Metric("accuracy", 99, directionality="invalid")
assert str(["score", "loss"]) in str(e)
|
0 | capitalone_repos/rubicon-ml/tests/unit/domain | capitalone_repos/rubicon-ml/tests/unit/domain/utils/test_training_metadata.py | import pytest
from rubicon_ml.domain.utils import TrainingMetadata
from rubicon_ml.exceptions import RubiconException
def test_init_throws_validation_error():
with pytest.raises(RubiconException) as e:
training_metadata = ["not", "a", "list", "of", "tuples"]
TrainingMetadata(training_metadata)
assert "must be a list of tuples" in str(e)
def test_init_convert_to_list():
training_metadata = TrainingMetadata(("test/path", "SELECT * FROM test"))
assert isinstance(training_metadata.training_metadata, list)
def test_repr():
training_metadata = TrainingMetadata(("test/path", "SELECT * FROM test"))
assert str(training_metadata) == str(training_metadata.training_metadata)
|
0 | capitalone_repos/rubicon-ml/tests/unit/domain | capitalone_repos/rubicon-ml/tests/unit/domain/utils/test_uuid.py | from uuid import UUID
from rubicon_ml.domain.utils import uuid
def test_returns_valid_uuid():
uuid_str = uuid.uuid4()
try:
UUID(uuid_str)
except ValueError as e:
assert f"`{uuid_str}` is not a valid UUID" in e
|
0 | capitalone_repos/rubicon-ml/tests/unit/workflow | capitalone_repos/rubicon-ml/tests/unit/workflow/prefect/test_prefect.py | import sys
from unittest.mock import patch
import pytest
from rubicon_ml.workflow.prefect import _check_for_prefect_extras
def test_missing_prefect_extra_raises_error():
install_prefect_message = "Install `prefect` with `pip install rubicon[prefect]`."
with patch.dict(sys.modules, {"prefect": None}):
with pytest.raises(ImportError) as e:
_check_for_prefect_extras()
assert str(e.value) in install_prefect_message
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/generators.py | import os
import sys
import holoviews as hv
import pandas as pd
from rubicon_ml import Rubicon
from rubicon_ml.exceptions import RubiconException
def get_or_create_project(rubicon, name):
try:
project = rubicon.create_project(name)
except RubiconException:
project = rubicon.get_project(name)
return project
def log_rubicon(path):
project_name = "intake-rubicon unit testing"
if os.path.exists(os.path.join(path, "projects", project_name)):
return
rubicon = Rubicon(persistence="filesystem", root_dir=path)
project = get_or_create_project(rubicon, project_name)
experiment_a = project.log_experiment(name="experiment_a", tags=["model-a", "y"])
experiment_a.log_feature("year")
experiment_a.log_feature("credit score")
experiment_b = project.log_experiment(name="experiment_b", tags=["model-b", "y"])
experiment_b.log_feature("year")
experiment_b.log_feature("credit score")
experiment_a.log_parameter("random state", 13243546)
experiment_a.log_parameter("test size", "10 GB")
experiment_a.log_parameter("n_estimators", 20)
experiment_a.log_metric("Accuracy", "99")
experiment_a.log_metric("AUC", "0.825")
df = pd.DataFrame([[1, 2, 3], [2, 1, 2], [3, 2, 1]], columns=["x", "y", "z"])
dataframe = experiment_a.log_dataframe(df, tags=["x", "y"])
plot = dataframe.plot(kind="bar")
plot_path = f"{path}/plot.png"
hv.save(plot, plot_path, fmt="png")
project.log_artifact(data_path=plot_path, description="bar plot logged with path")
with open(plot_path, "rb") as f:
source_data = f.read()
project.log_artifact(
data_bytes=source_data,
name="plot.png",
description="bar plot logged with bytes",
)
with open(plot_path, "rb") as f:
project.log_artifact(data_file=f, name="plot.png", description="bar plot logged with file")
if __name__ == "__main__":
here = os.path.dirname(__file__)
path = os.path.join(here, "data")
sys.exit(log_rubicon(path))
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/test_publish.py | import fsspec
import yaml
from rubicon_ml import Rubicon, publish
def test_publish(project_client):
project = project_client
experiment = project.log_experiment()
catalog_yaml = publish(project.experiments())
catalog = yaml.safe_load(catalog_yaml)
assert f"experiment_{experiment.id.replace('-', '_')}" in catalog["sources"]
assert (
"rubicon_ml_experiment"
== catalog["sources"][f"experiment_{experiment.id.replace('-', '_')}"]["driver"]
)
assert (
experiment.repository.root_dir
== catalog["sources"][f"experiment_{experiment.id.replace('-', '_')}"]["args"]["urlpath"]
)
assert (
experiment.id
== catalog["sources"][f"experiment_{experiment.id.replace('-', '_')}"]["args"][
"experiment_id"
]
)
assert (
project.name
== catalog["sources"][f"experiment_{experiment.id.replace('-', '_')}"]["args"][
"project_name"
]
)
def test_publish_from_multiple_sources():
rubicon_a = Rubicon(persistence="memory", root_dir="path/a")
rubicon_b = Rubicon(persistence="memory", root_dir="path/b")
experiment_a = rubicon_a.create_project("test").log_experiment()
experiment_b = rubicon_b.create_project("test").log_experiment()
catalog_yaml = publish([experiment_a, experiment_b])
catalog = yaml.safe_load(catalog_yaml)
assert (
rubicon_a.repository.root_dir
== catalog["sources"][f"experiment_{experiment_a.id.replace('-', '_')}"]["args"]["urlpath"]
)
assert (
rubicon_b.repository.root_dir
== catalog["sources"][f"experiment_{experiment_b.id.replace('-', '_')}"]["args"]["urlpath"]
)
assert (
catalog["sources"][f"experiment_{experiment_a.id.replace('-', '_')}"]["args"]["urlpath"]
!= catalog["sources"][f"experiment_{experiment_b.id.replace('-', '_')}"]["args"]["urlpath"]
)
def test_publish_to_file(project_client):
project = project_client
project.log_experiment()
project.log_experiment()
catalog_yaml = publish(project.experiments(), output_filepath="memory://catalog.yml")
with fsspec.open("memory://catalog.yml", "r") as f:
written_catalog = f.read()
assert catalog_yaml == written_catalog
def test_update_catalog(project_client):
project = project_client
project.log_experiment()
project.log_experiment()
publish(project.experiments(), output_filepath="memory://catalog.yml")
# add new experiments to project
experiment_c = project.log_experiment()
experiment_d = project.log_experiment()
new_experiments = [experiment_c, experiment_d]
# publish new experiments into the exisiting catalog
updated_catalog = publish(
base_catalog_filepath="memory://catalog.yml", experiments=new_experiments
)
with fsspec.open("memory://catalog.yml", "r") as f:
written_catalog = f.read()
assert updated_catalog == written_catalog
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/catalog.yml | sources:
experiment_a:
driver: rubicon_ml_experiment
args:
urlpath: '{{ CATALOG_DIR }}/data'
project_name: 'intake-rubicon unit testing'
experiment_id: '5f6ca6a1-563f-4f34-a34b-b45997bc4a1f'
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/test_experiment.py | import os
import intake
from rubicon_ml.intake_rubicon.experiment import ExperimentSource
root = os.path.dirname(__file__)
project_name = "intake-rubicon unit testing"
experiment_id = "5f6ca6a1-563f-4f34-a34b-b45997bc4a1f"
def test_source():
source = ExperimentSource(os.path.join(root, "data"), project_name, experiment_id)
assert source is not None
source.discover()
experiment = source.read()
assert experiment is not None
assert experiment.id == experiment_id
metadata = source._schema.extra_metadata
assert metadata["experiment"]["name"] == experiment.name
source.close()
def test_catalog():
cat = intake.open_catalog(os.path.join(root, "catalog.yml"))
source = cat.experiment_a()
source.discover()
experiment = source.read()
assert experiment is not None
assert experiment.id == experiment_id
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/metadata.json | {"name": "intake-rubicon unit testing", "id": "84c3cab2-29e1-4b55-98a3-035516bbf01a", "description": null, "training_metadata": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.375744"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/5f6ca6a1-563f-4f34-a34b-b45997bc4a1f/metadata.json | {"project_name": "intake-rubicon unit testing", "id": "5f6ca6a1-563f-4f34-a34b-b45997bc4a1f", "name": "experiment_b", "description": null, "model_name": null, "commit_hash": null, "training_metadata": null, "tags": ["model-b", "y"], "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.386372"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/5f6ca6a1-563f-4f34-a34b-b45997bc4a1f/features | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/5f6ca6a1-563f-4f34-a34b-b45997bc4a1f/features/year/metadata.json | {"name": "year", "id": "a25d0c07-968e-41d2-8f48-86e4aeddba2a", "description": null, "importance": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.388006"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/5f6ca6a1-563f-4f34-a34b-b45997bc4a1f/features | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/5f6ca6a1-563f-4f34-a34b-b45997bc4a1f/features/credit-score/metadata.json | {"name": "credit score", "id": "00140fd9-e96a-40ca-bbf4-0cdb9c6ec5e3", "description": null, "importance": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.388985"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/metadata.json | {"project_name": "intake-rubicon unit testing", "id": "8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1", "name": "experiment_a", "description": null, "model_name": null, "commit_hash": null, "training_metadata": null, "tags": ["model-a", "y"], "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.377333"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/features | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/features/year/metadata.json | {"name": "year", "id": "cce8917c-1382-4720-8927-005ecd9d73cc", "description": null, "importance": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.383581"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/features | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/features/credit-score/metadata.json | {"name": "credit score", "id": "d9022b6d-928f-450f-ad39-e6d9340acc10", "description": null, "importance": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.385203"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/metrics | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/metrics/auc/metadata.json | {"name": "AUC", "value": "0.825", "id": "b41397b5-28f8-4e07-8ca2-a41342adafd5", "description": null, "directionality": "score", "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.394936"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/metrics | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/metrics/accuracy/metadata.json | {"name": "Accuracy", "value": "99", "id": "25ef306a-4798-4959-bdb6-3be80e779892", "description": null, "directionality": "score", "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.393400"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/parameters | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/parameters/nestimators/metadata.json | {"name": "n_estimators", "id": "64537e08-7a34-44d4-9906-e498acf3a434", "value": 20, "description": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.391705"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/parameters | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/parameters/random-state/metadata.json | {"name": "random state", "id": "7665c636-f5fe-4a4a-bcd8-a58f7324c7b5", "value": 13243546, "description": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.389866"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/parameters | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/parameters/test-size/metadata.json | {"name": "test size", "id": "5087c08c-abfc-40e7-bfff-9a64c8cefee9", "value": "10 GB", "description": null, "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.390857"}}
|
0 | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/dataframes | capitalone_repos/rubicon-ml/tests/unit/intake_rubicon/data/intakerubicon-unit-testing/experiments/8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1/dataframes/aa8d5354-3e39-48fc-ace7-6939c9c79590/metadata.json | {"id": "aa8d5354-3e39-48fc-ace7-6939c9c79590", "description": null, "tags": ["x", "y"], "created_at": {"_type": "datetime", "value": "2020-07-13 15:03:21.397566"}, "parent_id": "8e5b4ad9-6afc-43ce-9e19-aaa1d80831f1"}
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_project_client.py | import os
import time
import warnings
from unittest import mock
from unittest.mock import patch
import pytest
from rubicon_ml import domain
from rubicon_ml.client import Project, Rubicon
from rubicon_ml.exceptions import RubiconException
from rubicon_ml.repository.utils import slugify
def _raise_error():
raise RubiconException()
class MockCompletedProcess:
def __init__(self, stdout="", returncode=0):
self.stdout = stdout
self.returncode = returncode
def test_properties():
domain_project = domain.Project(
"Test Project",
description="a test project",
github_url="github.com",
training_metadata=domain.utils.TrainingMetadata([("test/path", "SELECT * FROM test")]),
)
project = Project(domain_project)
assert project.name == "Test Project"
assert project.description == "a test project"
assert project.github_url == "github.com"
assert project.training_metadata == domain_project.training_metadata.training_metadata[0]
assert project.created_at == domain_project.created_at
assert project.id == domain_project.id
def test_get_branch_name(project_client):
project = project_client
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = MockCompletedProcess(stdout=b"branch-name\n")
expected = [
mock.call(["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True),
]
assert project._get_branch_name() == "branch-name"
assert mock_run.mock_calls == expected
def test_get_commit_hash(project_client):
project = project_client
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = MockCompletedProcess(stdout=b"abcd0000\n")
expected = [
mock.call(["git", "rev-parse", "HEAD"], capture_output=True),
]
assert project._get_commit_hash() == "abcd0000"
assert mock_run.mock_calls == expected
def test_get_identifiers(project_client):
project = project_client
project_name, experiment_id = project._get_identifiers()
assert project_name == project.name
assert experiment_id is None
def test_create_experiment_with_auto_git():
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = MockCompletedProcess(stdout=b"test", returncode=0)
rubicon = Rubicon("memory", "test-root", auto_git_enabled=True)
project = rubicon.create_project("Test Project A")
project.log_experiment()
expected = [
mock.call(["git", "rev-parse", "--git-dir"], capture_output=True),
mock.call(["git", "remote", "-v"], capture_output=True),
mock.call(["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True),
mock.call(["git", "rev-parse", "HEAD"], capture_output=True),
]
assert mock_run.mock_calls == expected
rubicon.repository.filesystem.store = {}
def test_experiments_log_and_retrieval(project_client):
project = project_client
experiment1 = project.log_experiment(
name="exp1", training_metadata=[("test/path", "SELECT * FROM test")]
)
experiment2 = project.log_experiment(name="exp2")
assert experiment1._domain.project_name == project.name
assert len(project.experiments()) == 2
assert experiment1.id in [e.id for e in project.experiments()]
assert experiment2.id in [e.id for e in project.experiments()]
@mock.patch("rubicon_ml.repository.BaseRepository.get_experiments")
def test_get_experiments_multiple_backend_error(mock_get_experiments, project_composite_client):
project = project_composite_client
mock_get_experiments.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
project.experiments()
assert "all configured storage backends failed" in str(e)
def test_experiment_by_id(rubicon_and_project_client):
project = rubicon_and_project_client[1]
_experiment = project.log_experiment(tags=["x"])
project.log_experiment(tags=["y"])
experiment = project.experiment(id=_experiment.id)
assert experiment.id == _experiment.id
def test_experiment_by_name(project_client):
project = project_client
project.log_experiment(name="exp1")
experiment = project.experiment(name="exp1")
assert experiment.name == "exp1"
def test_get_experiment_fails_both_set(project_client):
project = project_client
project.log_experiment(name="exp1")
with pytest.raises(ValueError) as e:
project.experiment(name="foo", id=123)
assert "`name` OR `id` required." in str(e.value)
def test_get_experiment_fails_neither_set(project_client):
project = project_client
project.log_experiment(name="exp1")
with pytest.raises(ValueError) as e:
project.experiment(name=None, id=None)
assert "`name` OR `id` required." in str(e.value)
@mock.patch("rubicon_ml.repository.BaseRepository.get_experiment")
def test_get_experiment_multiple_backend_error(mock_get_experiment, project_composite_client):
project = project_composite_client
mock_get_experiment.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
project.experiment("exp1")
assert "all configured storage backends failed" in str(e)
def test_experiment_warning(project_client, test_dataframe):
project = project_client
experiment_a = project.log_experiment(name="exp1")
experiment_b = project.log_experiment(name="exp1")
with warnings.catch_warnings(record=True) as w:
experiment_c = project.experiment(name="exp1")
assert (
"Multiple experiments found with name 'exp1'. Returning most recently logged"
) in str(w[0].message)
assert experiment_c.id != experiment_a.id
assert experiment_c.id == experiment_b.id
def test_experiment_name_not_found_error(project_client):
project = project_client
with pytest.raises(RubiconException) as e:
project.experiment(name="exp1")
assert "No experiment found with name 'exp1'." in str(e)
def test_experiments_tagged_and(project_client):
project = project_client
experiment = project.log_experiment(tags=["x", "y"])
project.log_experiment(tags=["x"])
project.log_experiment(tags=["y"])
experiments = project.experiments(tags=["x", "y"], qtype="and")
assert len(experiments) == 1
assert experiment.id in [e.id for e in experiments]
def test_experiments_tagged_or(project_client):
project = project_client
experiment_a = project.log_experiment(tags=["x"])
experiment_b = project.log_experiment(tags=["y"])
project.log_experiment(tags=["z"])
experiments = project.experiments(tags=["x", "y"], qtype="or")
assert len(experiments) == 2
assert experiment_a.id in [e.id for e in experiments]
assert experiment_b.id in [e.id for e in experiments]
def test_dataframes_recursive(project_client, test_dataframe):
project = project_client
experiment = project.log_experiment()
df = test_dataframe
dataframe_a = project.log_dataframe(df)
dataframe_b = experiment.log_dataframe(df)
dataframes = project.dataframes(recursive=True)
assert len(dataframes) == 2
assert dataframe_a.id in [d.id for d in dataframes]
assert dataframe_b.id in [d.id for d in dataframes]
def test_to_dask_df(rubicon_and_project_client_with_experiments):
project = rubicon_and_project_client_with_experiments[1]
ddf = project.to_df(df_type="dask")
# compute to pandas df so we can use iloc for easier testing
df = ddf.compute()
# check that all experiments made it into df
assert len(df) == 10
# check the cols within the df
exp_details = ["id", "name", "description", "model_name", "commit_hash", "tags", "created_at"]
for detail in exp_details:
assert detail in df.columns
def test_to_pandas_df(rubicon_and_project_client_with_experiments):
project = rubicon_and_project_client_with_experiments[1]
df = project.to_df(df_type="pandas")
# check that all experiments made it into df
assert len(df) == 10
# check the cols within the df
exp_details = ["id", "name", "description", "model_name", "commit_hash", "tags", "created_at"]
for detail in exp_details:
assert detail in df.columns
def test_to_dask_df_grouped_by_commit_hash(rubicon_and_project_client_with_experiments):
project = rubicon_and_project_client_with_experiments[1]
ddfs = project.to_df(df_type="dask", group_by="commit_hash")
# compute to pandas df so we can use iloc for easier testing
dfs = [ddf.compute() for ddf in ddfs.values()]
# check df was broken into 4 groups
assert len(dfs) == 4
for df in dfs:
# check the cols within the df
exp_details = [
"id",
"name",
"description",
"model_name",
"commit_hash",
"tags",
"created_at",
]
for detail in exp_details:
assert detail in df.columns
def test_to_pandas_df_grouped_by_commit_hash(rubicon_and_project_client_with_experiments):
project = rubicon_and_project_client_with_experiments[1]
dfs = project.to_df(df_type="pandas", group_by="commit_hash")
# check df was broken into 4 groups
assert len(dfs) == 4
for df in dfs.values():
# check the cols within the df
exp_details = [
"id",
"name",
"description",
"model_name",
"commit_hash",
"tags",
"created_at",
]
for detail in exp_details:
assert detail in df.columns
def test_to_df_grouped_by_invalid_group(rubicon_and_project_client_with_experiments):
project = rubicon_and_project_client_with_experiments[1]
with pytest.raises(ValueError) as e:
project.to_df(group_by="INVALID")
assert "`group_by` must be one of" in str(e)
def test_archive_no_experiments(project_client):
project = project_client
with pytest.raises(ValueError):
project.archive()
def test_archive_bad_experiments_argument(project_client):
project = project_client
experiment1 = project.log_experiment(name="experiment1")
with pytest.raises(ValueError):
project.archive(experiment1)
project.log_experiment(name="experiment2")
with pytest.raises(ValueError):
project.archive(["experiment1", "experiment2"])
def test_archive_all_experiments(rubicon_local_filesystem_client_with_project):
project = rubicon_local_filesystem_client_with_project[1]
project.log_experiment(name="experiment1")
project.log_experiment(name="experiment2")
project.log_experiment(name="experiment3")
archive_path = project.archive()
assert project.repository._exists(archive_path)
def test_archive_select_experiments(rubicon_local_filesystem_client_with_project):
project = rubicon_local_filesystem_client_with_project[1]
experiment1 = project.log_experiment(name="experiment1")
experiment2 = project.log_experiment(name="experiment2")
project.log_experiment(name="experiment3")
zip_archive_filename = project.archive([experiment1, experiment2])
assert project.repository._exists(zip_archive_filename)
def test_archive_bad_remote_rubicon():
rubiconA = Rubicon(
persistence="filesystem",
root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconA"),
)
rubiconB = Rubicon(
persistence="filesystem",
root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconB"),
)
rubiconA.get_or_create_project("ArchiveTesting")
projectB = rubiconB.get_or_create_project("ArchiveTesting")
projectB.log_experiment(name="experiment1")
projectB.log_experiment(name="experiment2")
with pytest.raises(ValueError):
projectB.archive(remote_rubicon=os.path.dirname(os.path.realpath(__file__)))
rubiconA.repository.filesystem.rm(rubiconA.config.root_dir, recursive=True)
rubiconB.repository.filesystem.rm(rubiconB.config.root_dir, recursive=True)
def test_archive_remote_rubicon():
rubiconA = Rubicon(
persistence="filesystem",
root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconA"),
)
rubiconB = Rubicon(
persistence="filesystem",
root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconB"),
)
projectA = rubiconA.get_or_create_project("ArchiveTesting")
projectB = rubiconB.get_or_create_project("ArchiveTesting")
projectB.log_experiment(name="experiment1")
projectB.log_experiment(name="experiment2")
zip_archive_filename = projectB.archive(remote_rubicon=rubiconA)
assert projectA.repository._exists(zip_archive_filename)
rubiconA.repository.filesystem.rm(rubiconA.config.root_dir, recursive=True)
rubiconB.repository.filesystem.rm(rubiconB.config.root_dir, recursive=True)
def test_experiments_from_archive_bad_argument():
rubiconA = Rubicon(
persistence="filesystem",
root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconA"),
)
rubiconB = Rubicon(
persistence="filesystem",
root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconB"),
)
projectA = rubiconA.get_or_create_project("ArchiveTesting")
projectA.log_experiment(name="experiment1")
projectA.log_experiment(name="experiment2")
# no archive created
projectB = rubiconB.get_or_create_project("ArchiveTesting")
with pytest.raises(ValueError):
projectB.experiments_from_archive(
remote_rubicon=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconA")
)
rubiconA.repository.filesystem.rm(rubiconA.config.root_dir, recursive=True)
rubiconB.repository.filesystem.rm(rubiconB.config.root_dir, recursive=True)
def test_experiments_from_archive():
root_dirA = os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconA")
rubiconA = Rubicon(
persistence="filesystem",
root_dir=root_dirA,
)
root_dirB = os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconB")
rubiconB = Rubicon(
persistence="filesystem",
root_dir=root_dirB,
)
projectA = rubiconA.get_or_create_project("ArchiveTesting")
projectA.log_experiment(name="experiment1")
projectA.log_experiment(name="experiment2")
projectA.archive()
projectB = rubiconB.get_or_create_project("ArchiveTesting")
projectB.log_experiment(name="experiment3")
projectB.log_experiment(name="experiment4")
experiments_dirB = os.path.join(root_dirB, slugify(projectB.name), "experiments")
og_num_exps_B = len(projectB.repository._ls(experiments_dirB))
assert og_num_exps_B == 2
projectB.experiments_from_archive(remote_rubicon=rubiconA)
new_num_expsB = len(projectB.repository._ls(experiments_dirB))
assert new_num_expsB == 4
rubiconA.repository.filesystem.rm(rubiconA.config.root_dir, recursive=True)
rubiconB.repository.filesystem.rm(rubiconB.config.root_dir, recursive=True)
def test_experiments_from_archive_latest_only():
root_dirA = os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconA")
rubiconA = Rubicon(
persistence="filesystem",
root_dir=root_dirA,
)
root_dirB = os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconB")
rubiconB = Rubicon(
persistence="filesystem",
root_dir=root_dirB,
)
projectA = rubiconA.get_or_create_project("ArchiveTesting")
projectA.log_experiment(name="experiment1")
projectA.log_experiment(name="experiment2")
projectA.log_experiment(name="experiment3")
projectA.archive()
projectB = rubiconB.get_or_create_project("ArchiveTesting")
projectB.log_experiment(name="experiment4")
projectB.log_experiment(name="experiment5")
experiment6 = projectA.log_experiment(name="experiment6")
experiment7 = projectA.log_experiment(name="experiment7")
time.sleep(1)
projectA.archive([experiment6, experiment7])
experiments_dirB = os.path.join(root_dirB, slugify(projectB.name), "experiments")
og_num_exps_B = len(projectB.repository._ls(experiments_dirB))
assert og_num_exps_B == 2
projectB.experiments_from_archive(remote_rubicon=rubiconA, latest_only=True)
new_num_expsB = len(projectB.repository._ls(experiments_dirB))
assert new_num_expsB == 4
rubiconA.repository.filesystem.rm(rubiconA.config.root_dir, recursive=True)
rubiconB.repository.filesystem.rm(rubiconB.config.root_dir, recursive=True)
@patch("fsspec.open")
def test_archive_remote_rubicon_s3(mock_open):
print("buffer")
rubicon_a = Rubicon(
persistence="filesystem",
root_dir=os.path.join(os.path.dirname(os.path.realpath(__file__)), "rubiconA"),
)
s3_repo = "s3://bucket/root/path/to/data"
rubicon_b = Rubicon(persistence="filesystem", root_dir=s3_repo)
projectA = rubicon_a.get_or_create_project("ArchiveTesting")
projectA.log_experiment(name="experiment1")
projectA.log_experiment(name="experiment2")
zip_archive_filename = projectA.archive(remote_rubicon=rubicon_b)
mock_open.assert_called_once_with(zip_archive_filename, "wb")
rubicon_a.repository.filesystem.rm(rubicon_a.config.root_dir, recursive=True)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_metric_client.py | from unittest.mock import MagicMock
from rubicon_ml import domain
from rubicon_ml.client import Metric
def test_properties():
domain_metric = domain.Metric("Accuracy", 99, description="some description")
metric = Metric(domain_metric, MagicMock())
assert metric.name == "Accuracy"
assert metric.value == 99
assert metric.directionality == "score"
assert metric.description == "some description"
assert metric.id == domain_metric.id
assert metric.created_at == domain_metric.created_at
assert hasattr(metric, "parent")
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_base_client.py | def test_str(project_client):
project = project_client
assert project.__str__() == project._domain.__str__()
def test_get_repository(rubicon_client):
rubicon = rubicon_client
assert rubicon.repository == rubicon.config.repository
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_experiment_client.py | from unittest import mock
import pytest
from rubicon_ml import domain
from rubicon_ml.client import Experiment
from rubicon_ml.exceptions import RubiconException
def _raise_error():
raise RubiconException()
def test_properties(project_client):
project = project_client
domain_experiment = domain.Experiment(
project_name=project.name,
description="some description",
name="exp-1",
model_name="ModelOne model",
branch_name="branch",
commit_hash="a-commit-hash",
training_metadata=domain.utils.TrainingMetadata([("test/path", "SELECT * FROM test")]),
tags=["x"],
)
experiment = Experiment(domain_experiment, project)
assert experiment.name == "exp-1"
assert experiment.description == "some description"
assert experiment.model_name == "ModelOne model"
assert experiment.branch_name == "branch"
assert experiment.commit_hash == "a-commit-hash"
assert experiment.name == domain_experiment.name
assert experiment.commit_hash == domain_experiment.commit_hash
assert experiment.training_metadata == domain_experiment.training_metadata.training_metadata[0]
assert experiment.tags == domain_experiment.tags
assert experiment.created_at == domain_experiment.created_at
assert experiment.id == domain_experiment.id
assert experiment.project == project
def test_get_identifiers(project_client):
project = project_client
experiment = project.log_experiment()
project_name, experiment_id = experiment._get_identifiers()
assert project_name == project.name
assert experiment_id == experiment.id
def test_log_metric(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_metric("Accuracy", 99)
experiment.log_metric("AUC", 0.825)
assert "Accuracy" in [m.name for m in experiment.metrics()]
assert "AUC" in [m.name for m in experiment.metrics()]
def test_get_metrics(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
metric = {"name": "Accuracy", "value": 99}
experiment.log_metric(metric["name"], metric["value"])
metrics = experiment.metrics()
assert len(metrics) == 1
assert metrics[0].name == metric["name"]
assert metrics[0].value == metric["value"]
@mock.patch("rubicon_ml.repository.BaseRepository.get_metrics")
def test_get_metrics_multiple_backend_error(mock_get_metrics, project_composite_client):
project = project_composite_client
experiment = project.log_experiment(name="exp1")
mock_get_metrics.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
experiment.metrics()
assert "all configured storage backends failed" in str(e)
def test_get_metric_by_name(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_metric("accuracy", 100)
metric = experiment.metric(name="accuracy").name
assert metric == "accuracy"
def test_get_metric_fails_neither_set(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_metric("accuracy", 100)
with pytest.raises(ValueError) as e:
experiment.metric(name=None, id=None)
assert "`name` OR `id` required." in str(e)
def test_get_metric_fails_both_set(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_metric("accuracy", 100)
with pytest.raises(ValueError) as e:
experiment.metric(name="foo", id=123)
assert "`name` OR `id` required." in str(e)
def test_metrics_tagged_and(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
metric = experiment.log_metric(name="name", value=0, tags=["x", "y"])
experiment.log_metric(name="name_a", value=0, tags=["x"])
experiment.log_metric(name="name_b", value=0, tags=["y"])
metrics = experiment.metrics(tags=["x", "y"], qtype="and")
assert len(metrics) == 1
assert metric.id in [d.id for d in metrics]
def test_metrics_tagged_or(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
metric_a = experiment.log_metric(name="name_a", value=0, tags=["x"])
metric_b = experiment.log_metric(name="name_b", value=0, tags=["y"])
experiment.log_metric(name="name_c", value=0, tags=["z"])
metrics = experiment.metrics(tags=["x", "y"], qtype="or")
assert len(metrics) == 2
assert metric_a.id in [d.id for d in metrics]
assert metric_b.id in [d.id for d in metrics]
def test_get_metric_by_id(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_metric("accuracy", 100)
metric_id = experiment.metric("accuracy").id
metric = experiment.metric(id=metric_id).name
assert metric == "accuracy"
@mock.patch("rubicon_ml.repository.BaseRepository.get_metric")
def test_get_metric_multiple_backend_error(mock_get_metric, project_composite_client):
project = project_composite_client
experiment = project.log_experiment(name="exp1")
mock_get_metric.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
experiment.metric("accuracy")
assert "all configured storage backends failed" in str(e)
def test_log_feature(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_feature("year")
assert "year" in [f.name for f in experiment.features()]
def test_get_features(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_feature("year")
experiment.log_feature("credit score")
features = experiment.features()
assert len(features) == 2
assert features[0].name == "year"
assert features[1].name == "credit score"
@mock.patch("rubicon_ml.repository.BaseRepository.get_features")
def test_get_features_multiple_backend_error(mock_get_features, project_composite_client):
project = project_composite_client
experiment = project.log_experiment(name="exp1")
mock_get_features.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
experiment.features()
assert "all configured storage backends failed" in str(e)
def test_get_feature_by_name(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_feature("year")
feature = experiment.feature(name="year").name
assert feature == "year"
def test_get_feature_by_id(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_feature("year")
feature_id = experiment.feature("year").id
feature = experiment.feature(id=feature_id).name
assert feature == "year"
def test_get_feature_fails_neither_set(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_feature("year")
with pytest.raises(ValueError) as e:
experiment.feature(name=None, id=None)
assert "`name` OR `id` required." in str(e)
def test_get_feature_fails_both_set(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_feature("year")
with pytest.raises(ValueError) as e:
experiment.feature(name="foo", id=123)
assert "`name` OR `id` required." in str(e)
@mock.patch("rubicon_ml.repository.BaseRepository.get_feature")
def test_get_feature_multiple_backend_error(mock_get_feature, project_composite_client):
project = project_composite_client
experiment = project.log_experiment(name="exp1")
mock_get_feature.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
experiment.feature("year")
assert "all configured storage backends failed" in str(e)
def test_features_tagged_and(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
feature = experiment.log_feature(name="name", tags=["x", "y"])
experiment.log_feature(name="name_a", tags=["x"])
experiment.log_feature(name="name_b", tags=["y"])
features = experiment.features(tags=["x", "y"], qtype="and")
assert len(features) == 1
assert feature.id in [d.id for d in features]
def test_features_tagged_or(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
feature_a = experiment.log_feature(name="name_a", tags=["x"])
feature_b = experiment.log_feature(name="name_b", tags=["y"])
experiment.log_feature(name="name_c", tags=["z"])
features = experiment.features(tags=["x", "y"], qtype="or")
assert len(features) == 2
assert feature_a.id in [d.id for d in features]
assert feature_b.id in [d.id for d in features]
def test_log_parameter(project_client):
project = project_client
experiment = project.log_experiment()
experiment.log_parameter("test", value="value")
assert "test" in [p.name for p in experiment.parameters()]
assert "value" in [p.value for p in experiment.parameters()]
def test_parameters(project_client):
project = project_client
experiment = project.log_experiment()
parameter_a = experiment.log_parameter("test_a", value="value_a")
parameter_b = experiment.log_parameter("test_b", value="value_b")
parameters = experiment.parameters()
assert len(parameters) == 2
assert parameter_a.id in [p.id for p in parameters]
assert parameter_b.id in [p.id for p in parameters]
@mock.patch("rubicon_ml.repository.BaseRepository.get_parameters")
def test_parameters_multiple_backend_error(mock_get_parameters, project_composite_client):
project = project_composite_client
experiment = project.log_experiment(name="exp1")
mock_get_parameters.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
experiment.parameters()
assert "all configured storage backends failed" in str(e)
def test_get_parameter_by_name(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_parameter("n_estimators", "estimator")
parameter = experiment.parameter(name="n_estimators").name
assert parameter == "n_estimators"
def test_get_parameter_by_id(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_parameter("n_estimators", "estimator")
parameter_id = experiment.parameter("n_estimators").id
parameter = experiment.parameter(id=parameter_id).name
assert parameter == "n_estimators"
def test_get_parameter_fails_neither_set(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_parameter("n_estimators", "estimator")
with pytest.raises(ValueError) as e:
experiment.parameter(name=None, id=None)
assert "`name` OR `id` required." in str(e)
def test_get_parameter_fails_both_set(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
experiment.log_parameter("n_estimators", "estimator")
with pytest.raises(ValueError) as e:
experiment.parameter(name="foo", id=123)
assert "`name` OR `id` required." in str(e)
@mock.patch("rubicon_ml.repository.BaseRepository.get_parameter")
def test_get_parameter_multiple_backend_error(mock_get_parameter, project_composite_client):
project = project_composite_client
experiment = project.log_experiment(name="exp1")
mock_get_parameter.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
experiment.parameter("n_estimators")
assert "all configured storage backends failed" in str(e)
def test_parameters_tagged_and(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
parameter = experiment.log_parameter(name="param_1", tags=["x", "y"])
experiment.log_parameter(name="param_2", tags=["x"])
experiment.log_parameter(name="param_3", tags=["y"])
parameters = experiment.parameters(tags=["x", "y"], qtype="and")
assert len(parameters) == 1
assert parameter.id in [d.id for d in parameters]
def test_parameters_tagged_or(project_client):
project = project_client
experiment = project.log_experiment(name="exp1")
param_a = experiment.log_parameter(name="param_a", tags=["x"])
param_b = experiment.log_parameter(name="param_b", tags=["y"])
experiment.log_parameter(name="param_c", tags=["z"])
parameters = experiment.parameters(tags=["x", "y"], qtype="or")
assert len(parameters) == 2
assert param_a.id in [d.id for d in parameters]
assert param_b.id in [d.id for d in parameters]
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_parameter_client.py | from unittest.mock import MagicMock
from rubicon_ml import domain
from rubicon_ml.client import Parameter
def test_properties():
domain_parameter = domain.Parameter("name", value="value", description="description")
parameter = Parameter(domain_parameter, MagicMock())
assert parameter.id == domain_parameter.id
assert parameter.name == domain_parameter.name
assert parameter.value == domain_parameter.value
assert parameter.description == domain_parameter.description
assert parameter.created_at == domain_parameter.created_at
assert hasattr(parameter, "parent")
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_feature_client.py | from unittest.mock import MagicMock
from rubicon_ml import domain
from rubicon_ml.client import Feature
def test_properties():
domain_feature = domain.Feature("year", description="year feature", importance=0.5)
feature = Feature(domain_feature, MagicMock())
assert feature.name == "year"
assert feature.description == "year feature"
assert feature.importance == 0.5
assert feature.id == domain_feature.id
assert feature.created_at == domain_feature.created_at
assert hasattr(feature, "parent")
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_mixin_client.py | import subprocess
import warnings
from unittest import mock
from unittest.mock import MagicMock, patch
import pytest
from rubicon_ml.client.mixin import ArtifactMixin, DataframeMixin, TagMixin
from rubicon_ml.exceptions import RubiconException
def _raise_error():
raise RubiconException()
# ArtifactMixin
def test_log_artifact_from_bytes(project_client):
project = project_client
artifact = ArtifactMixin.log_artifact(project, data_bytes=b"content", name="test.txt")
assert artifact.id in [a.id for a in project.artifacts()]
assert artifact.name == "test.txt"
assert artifact.data == b"content"
def test_log_artifact_from_file(project_client):
project = project_client
mock_file = MagicMock()
mock_file.__enter__().read.side_effect = [b"content"]
artifact = ArtifactMixin.log_artifact(project, data_file=mock_file, name="test.txt")
assert artifact.id in [a.id for a in project.artifacts()]
assert artifact.name == "test.txt"
assert artifact.data == b"content"
@patch("fsspec.implementations.local.LocalFileSystem.open")
def test_log_artifact_from_path(mock_open, project_client):
project = project_client
mock_file = MagicMock()
mock_file().read.side_effect = [b"content"]
mock_open.side_effect = mock_file
artifact = ArtifactMixin.log_artifact(project, data_path="/path/to/test.txt")
assert artifact.id in [a.id for a in project.artifacts()]
assert artifact.name == "test.txt"
assert artifact.data == b"content"
def test_log_artifact_throws_error_if_data_missing(project_client):
project = project_client
with pytest.raises(RubiconException) as e:
ArtifactMixin.log_artifact(project, name="test.txt")
assert (
"One of `data_bytes`, `data_file`, `data_object` or `data_path` must be provided." in str(e)
)
def test_log_artifact_throws_error_if_name_missing_data_bytes(project_client):
project = project_client
with pytest.raises(RubiconException) as e:
ArtifactMixin.log_artifact(project, data_bytes=b"content")
assert "`name` must be provided if not using `data_path`." in str(e)
def test_log_artifact_throws_error_if_name_missing_data_file(project_client):
project = project_client
mock_file = MagicMock()
mock_file.__enter__().read.side_effect = [b"content"]
with pytest.raises(RubiconException) as e:
ArtifactMixin.log_artifact(project, data_file=mock_file)
assert "`name` must be provided if not using `data_path`." in str(e)
def test_log_artifact_throws_error_if_name_missing_data_object(project_client):
project = project_client
class TestObject:
value = "test"
test_object = TestObject()
with pytest.raises(RubiconException) as e:
ArtifactMixin.log_artifact(project, data_object=test_object)
assert "`name` must be provided if not using `data_path`." in str(e)
def test_get_environment_bytes(project_client, mock_completed_process_empty):
project = project_client
with patch("subprocess.run") as mock_run:
mock_run.return_value = mock_completed_process_empty
env_bytes = project._get_environment_bytes(["conda", "env", "export"])
assert env_bytes == b"\n"
def test_get_environment_bytes_error(project_client):
project = project_client
with pytest.raises(RubiconException) as e:
with patch("subprocess.run") as mock_run:
mock_run.side_effect = subprocess.CalledProcessError(
returncode=-1, cmd=b"\n", stderr="yikes"
)
project._get_environment_bytes(["conda", "env", "export"])
assert "yikes" in str(e)
def test_log_conda_env(project_client, mock_completed_process_empty):
project = project_client
with patch("subprocess.run") as mock_run:
mock_run.return_value = mock_completed_process_empty
artifact = project.log_conda_environment()
assert artifact.id in [a.id for a in project.artifacts()]
assert ".yml" in artifact.name
assert artifact.data == b"\n"
def test_log_pip_requirements(project_client, mock_completed_process_empty):
project = project_client
with patch("subprocess.run") as mock_run:
mock_run.return_value = mock_completed_process_empty
artifact = project.log_pip_requirements()
assert artifact.id in [a.id for a in project.artifacts()]
assert ".txt" in artifact.name
assert artifact.data == b"\n"
def test_log_json(project_client):
project = project_client
data = {"hello": "world", "foo": [1, 2, 3]}
artifact_a = ArtifactMixin.log_json(project, data, name="test.json")
artifact_b = ArtifactMixin.log_json(project, data, name="test.txt")
artifacts = ArtifactMixin.artifacts(project)
assert len(artifacts) == 2
assert artifact_a.id in [a.id for a in artifacts]
assert artifact_b.id in [a.id for a in artifacts]
def test_artifacts(project_client):
project = project_client
data = b"content"
artifact_a = ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
artifact_b = ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
artifacts = ArtifactMixin.artifacts(project)
assert len(artifacts) == 2
assert artifact_a.id in [a.id for a in artifacts]
assert artifact_b.id in [a.id for a in artifacts]
@mock.patch("rubicon_ml.repository.BaseRepository.get_artifacts_metadata")
def test_artifacts_multiple_backend_error(mock_get_artifacts_metadata, project_composite_client):
project = project_composite_client
mock_get_artifacts_metadata.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
ArtifactMixin.artifacts(project)
assert "all configured storage backends failed" in str(e)
def test_artifacts_by_name(project_client):
project = project_client
data = b"content"
artifact_a = ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
artifact_b = ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
ArtifactMixin.log_artifact(project, data_bytes=data, name="test2.txt")
artifacts = ArtifactMixin.artifacts(project, name="test.txt")
assert len(artifacts) == 2
assert artifact_a.id in [a.id for a in artifacts]
assert artifact_b.id in [a.id for a in artifacts]
def test_artifacts_tagged_and(project_client):
project = project_client
artifact = ArtifactMixin.log_artifact(project, name="name", data_bytes=b"test", tags=["x", "y"])
ArtifactMixin.log_artifact(project, name="name", data_bytes=b"test", tags=["x"])
ArtifactMixin.log_artifact(project, name="name", data_bytes=b"test", tags=["y"])
artifacts = ArtifactMixin.artifacts(project, tags=["x", "y"], qtype="and")
assert len(artifacts) == 1
assert artifact.id in [d.id for d in artifacts]
def test_artifacts_tagged_or(project_client):
project = project_client
artifact_a = ArtifactMixin.log_artifact(project, name="name", data_bytes=b"test", tags=["x"])
artifact_b = ArtifactMixin.log_artifact(project, name="name", data_bytes=b"test", tags=["y"])
ArtifactMixin.log_artifact(project, name="name", data_bytes=b"test", tags=["z"])
artifacts = ArtifactMixin.artifacts(project, tags=["x", "y"], qtype="or")
assert len(artifacts) == 2
assert artifact_a.id in [d.id for d in artifacts]
assert artifact_b.id in [d.id for d in artifacts]
def test_artifact_warning(project_client):
project = project_client
data = b"content"
artifact_a = ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
artifact_b = ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
with warnings.catch_warnings(record=True) as w:
artifact_c = ArtifactMixin.artifact(project, name="test.txt")
assert (
"Multiple artifacts found with name 'test.txt'. Returning most recently logged"
) in str(w[0].message)
assert artifact_c.id != artifact_a.id
assert artifact_c.id == artifact_b.id
def test_artifact_name_not_found_error(project_client):
project = project_client
with pytest.raises(RubiconException) as e:
ArtifactMixin.artifact(project, name="test.txt")
assert "No artifact found with name 'test.txt'." in str(e)
def test_artifacts_name_not_found_error(project_client):
project = project_client
artifacts = ArtifactMixin.artifacts(project, name="test.txt")
assert artifacts == []
def test_artifact_by_name(project_client):
project = project_client
data = b"content"
ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
artifact = ArtifactMixin.artifact(project, name="test.txt")
assert artifact.name == "test.txt"
def test_artifact_by_id(project_client):
project = project_client
data = b"content"
ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
artifact = ArtifactMixin.artifact(project, name="test.txt")
artifact_name = ArtifactMixin.artifact(project, id=artifact.id).name
assert artifact_name == "test.txt"
@mock.patch("rubicon_ml.repository.BaseRepository.get_artifact_metadata")
def test_artifact_multiple_backend_error(mock_get_artifact_metadata, project_composite_client):
project = project_composite_client
data = b"content"
artifact = ArtifactMixin.log_artifact(project, data_bytes=data, name="test.txt")
mock_get_artifact_metadata.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
ArtifactMixin.artifact(project, id=artifact.id)
assert "all configured storage backends failed" in str(e)
def test_delete_artifacts(project_client):
project = project_client
artifact = ArtifactMixin.log_artifact(project, data_bytes=b"content", name="test.txt")
ArtifactMixin.delete_artifacts(project, [artifact.id])
assert artifact.id not in [a.id for a in project.artifacts()]
# DataframeMixin
def test_log_dataframe(project_client, test_dataframe):
project = project_client
df = test_dataframe
test_df_name = "test_df"
dataframe = DataframeMixin.log_dataframe(project, df, name=test_df_name, tags=["x"])
DataframeMixin.log_dataframe(project, df, name="secondary test df", tags=["x"])
assert dataframe.name == test_df_name
assert dataframe.id in [df.id for df in project.dataframes()]
def test_dataframes(project_client, test_dataframe):
project = project_client
df = test_dataframe
dataframe_a = DataframeMixin.log_dataframe(project, df)
dataframe_b = DataframeMixin.log_dataframe(project, df)
dataframes = DataframeMixin.dataframes(project)
assert len(dataframes) == 2
assert dataframe_a.id in [d.id for d in dataframes]
assert dataframe_b.id in [d.id for d in dataframes]
@mock.patch("rubicon_ml.repository.BaseRepository.get_dataframes_metadata")
def test_dataframes_multiple_backend_error(mock_get_dataframes_metadata, project_composite_client):
project = project_composite_client
mock_get_dataframes_metadata.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
DataframeMixin.dataframes(project)
assert "all configured storage backends failed" in str(e)
def test_dataframes_by_name(project_client, test_dataframe):
project = project_client
df = test_dataframe
test_df_name = "test_df"
dataframe_a = DataframeMixin.log_dataframe(project, df, name=test_df_name)
dataframe_b = DataframeMixin.log_dataframe(project, df, name=test_df_name)
dataframes = DataframeMixin.dataframes(project, name=test_df_name)
assert len(dataframes) == 2
assert dataframe_a.id in [d.id for d in dataframes]
assert dataframe_b.id in [d.id for d in dataframes]
def test_dataframe_by_name(project_client, test_dataframe):
project = project_client
df = test_dataframe
test_df_name = "test_df"
dataframe_a = DataframeMixin.log_dataframe(project, df, name=test_df_name)
dataframe_b = DataframeMixin.dataframe(project, name=test_df_name)
assert dataframe_a.id == dataframe_b.id
def test_dataframe_by_id(project_client, test_dataframe):
project = project_client
df = test_dataframe
dataframe_a = DataframeMixin.log_dataframe(project, df)
id = dataframe_a.id
dataframe_b = DataframeMixin.dataframe(project, id=id)
assert dataframe_a.id == dataframe_b.id
@mock.patch("rubicon_ml.repository.BaseRepository.get_dataframe_metadata")
def test_dataframe_multiple_backend_error(
mock_get_dataframe_metadata, project_composite_client, test_dataframe
):
project = project_composite_client
dataframe = DataframeMixin.log_dataframe(project, test_dataframe)
mock_get_dataframe_metadata.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
DataframeMixin.dataframe(project, id=dataframe.id)
assert "all configured storage backends failed" in str(e)
def test_dataframe_warning(project_client, test_dataframe):
project = project_client
df = test_dataframe
test_df_name = "test_df"
dataframe_a = DataframeMixin.log_dataframe(project, df, name=test_df_name)
dataframe_b = DataframeMixin.log_dataframe(project, df, name=test_df_name)
with warnings.catch_warnings(record=True) as w:
dataframe_c = DataframeMixin.dataframe(project, name=test_df_name)
assert (
"Multiple dataframes found with name 'test_df'. Returning most recently logged"
) in str(w[0].message)
assert dataframe_c.id != dataframe_a.id
assert dataframe_c.id == dataframe_b.id
def test_dataframe_by_name_not_found(project_client, test_dataframe):
project = project_client
test_df_name = "test_df"
with pytest.raises(RubiconException) as e:
DataframeMixin.dataframe(project, name=test_df_name)
assert "No dataframe found with name 'test_df'." in str(e.value)
def test_dataframes_by_name_not_found(project_client, test_dataframe):
project = project_client
test_df_name = "test_df"
dataframes = DataframeMixin.dataframes(project, name=test_df_name)
assert dataframes == []
def test_get_dataframe_fails_both_set(project_client, test_dataframe):
project = project_client
with pytest.raises(ValueError) as e:
DataframeMixin.dataframe(project, name="foo", id=123)
assert "`name` OR `id` required." in str(e.value)
def test_get_dataframe_fails_neither_set(project_client, test_dataframe):
project = project_client
with pytest.raises(ValueError) as e:
DataframeMixin.dataframe(project, name=None, id=None)
assert "`name` OR `id` required." in str(e.value)
def test_dataframes_tagged_and(project_client, test_dataframe):
project = project_client
df = test_dataframe
dataframe = DataframeMixin.log_dataframe(project, df, tags=["x", "y"])
DataframeMixin.log_dataframe(project, df, tags=["x"])
DataframeMixin.log_dataframe(project, df, tags=["y"])
dataframes = DataframeMixin.dataframes(project, tags=["x", "y"], qtype="and")
assert len(dataframes) == 1
assert dataframe.id in [d.id for d in dataframes]
def test_dataframes_tagged_or(project_client, test_dataframe):
project = project_client
df = test_dataframe
dataframe_a = DataframeMixin.log_dataframe(project, df, tags=["x"])
dataframe_b = DataframeMixin.log_dataframe(project, df, tags=["y"])
DataframeMixin.log_dataframe(project, df, tags=["z"])
dataframes = DataframeMixin.dataframes(project, tags=["x", "y"], qtype="or")
assert len(dataframes) == 2
assert dataframe_a.id in [d.id for d in dataframes]
assert dataframe_b.id in [d.id for d in dataframes]
def test_delete_dataframes(project_client, test_dataframe):
project = project_client
df = test_dataframe
dataframe = DataframeMixin.log_dataframe(project, df, tags=["x"])
DataframeMixin.delete_dataframes(project, [dataframe.id])
assert dataframe.id not in [df.id for df in project.dataframes()]
# TagMixin
def test_get_taggable_experiment_identifiers(project_client):
project = project_client
experiment = project.log_experiment()
project_name, experiment_id, dataframe_id = TagMixin._get_taggable_identifiers(experiment)
assert project_name == project.name
assert experiment_id == experiment.id
assert dataframe_id is None
def test_get_taggable_dataframe_identifiers(project_client, test_dataframe):
project = project_client
experiment = project.log_experiment()
df = test_dataframe
project_df = project.log_dataframe(df)
experiment_df = experiment.log_dataframe(df)
project_name, experiment_id, dataframe_id = TagMixin._get_taggable_identifiers(project_df)
assert project_name == project.name
assert experiment_id is None
assert dataframe_id == project_df.id
project_name, experiment_id, dataframe_id = TagMixin._get_taggable_identifiers(experiment_df)
assert project_name == project.name
assert experiment_id is experiment.id
assert dataframe_id == experiment_df.id
def test_get_taggable_artifact_identifiers(project_client):
project = project_client
experiment = project.log_experiment()
project_artifact = project.log_artifact(data_bytes=b"test", name="test")
experiment_artifact = experiment.log_artifact(data_bytes=b"test", name="test")
project_name, experiment_id, artifact_id = TagMixin._get_taggable_identifiers(project_artifact)
assert project_name == project.name
assert experiment_id is None
assert artifact_id == project_artifact.id
project_name, experiment_id, artifact_id = TagMixin._get_taggable_identifiers(
experiment_artifact
)
assert project_name == project.name
assert experiment_id is experiment.id
assert artifact_id == experiment_artifact.id
def test_add_tags(project_client):
project = project_client
experiment = project.log_experiment()
TagMixin.add_tags(experiment, ["x"])
assert experiment.tags == ["x"]
def test_remove_tags(project_client):
project = project_client
experiment = project.log_experiment(tags=["x", "y"])
TagMixin.remove_tags(experiment, ["x", "y"])
assert experiment.tags == []
@mock.patch("rubicon_ml.repository.BaseRepository.get_tags")
def test_tags_multiple_backend_error(mock_get_tags, project_composite_client):
project = project_composite_client
experiment = project.log_experiment(tags=["x", "y"])
def raise_error():
raise RubiconException()
mock_get_tags.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
experiment.tags()
assert "all configured storage backends failed" in str(e)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_rubicon_client.py | import subprocess
from unittest import mock
import dask.dataframe as dd
import pandas as pd
import pytest
from rubicon_ml import client, domain
from rubicon_ml.client import Rubicon
from rubicon_ml.exceptions import RubiconException
class TestRepository:
root_dir = ""
@property
def filesystem(self):
class TestFilesystem:
def rm(self, path, recursive):
pass
return TestFilesystem()
def _raise_error():
raise RubiconException()
def test_get_repository(rubicon_client):
rubicon = rubicon_client
assert rubicon.repository == rubicon.config.repository
def test_set_repository(rubicon_client):
rubicon = rubicon_client
test_repo = TestRepository()
rubicon.repository = test_repo
assert rubicon.config.repository == test_repo
def test_repository_storage_options():
storage_options = {"key": "secret"}
rubicon_memory = Rubicon(persistence="memory", root_dir="./", **storage_options)
rubicon_s3 = Rubicon(persistence="filesystem", root_dir="s3://nothing", **storage_options)
assert rubicon_memory.config.repository.filesystem.storage_options["key"] == "secret"
assert rubicon_s3.config.repository.filesystem.storage_options["key"] == "secret"
def test_get_github_url(rubicon_client, mock_completed_process_git):
rubicon = rubicon_client
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock_completed_process_git
expected = [
mock.call(["git", "remote", "-v"], capture_output=True),
]
assert rubicon._get_github_url() == "github.com"
assert mock_run.mock_calls == expected
def test_get_github_url_no_remotes(rubicon_client, mock_completed_process_empty):
rubicon = rubicon_client
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock_completed_process_empty
assert rubicon._get_github_url() is None
def test_create_project(rubicon_client):
rubicon = rubicon_client
project = rubicon.create_project(
"Test Project A", training_metadata=[("test/path", "SELECT * FROM test")]
)
assert project._domain.name == "Test Project A"
def test_create_project_with_auto_git(mock_completed_process_git):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock_completed_process_git
rubicon = Rubicon("memory", "test-root", auto_git_enabled=True)
rubicon.create_project("Test Project A")
expected = [
mock.call(["git", "rev-parse", "--git-dir"], capture_output=True),
mock.call(["git", "remote", "-v"], capture_output=True),
]
assert mock_run.mock_calls == expected
rubicon.repository.filesystem.store = {}
def test_get_project_by_name(rubicon_and_project_client):
rubicon, project = rubicon_and_project_client
assert "Test Project" == rubicon.get_project("Test Project").name
def test_get_project_by_id(rubicon_and_project_client):
rubicon, project = rubicon_and_project_client
project_id = project.id
assert project_id == rubicon.get_project(id=project_id).id
def test_get_project_fails_both_set(rubicon_and_project_client):
rubicon, project = rubicon_and_project_client
with pytest.raises(ValueError) as e:
rubicon.get_project(name="foo", id=123)
assert "`name` OR `id` required." in str(e.value)
def test_get_project_fails_neither_set(rubicon_and_project_client):
rubicon, project = rubicon_and_project_client
with pytest.raises(ValueError) as e:
rubicon.get_project(name=None, id=None)
assert "`name` OR `id` required." in str(e.value)
@mock.patch("rubicon_ml.repository.BaseRepository.get_project")
def test_get_project_multiple_backend_error(mock_get_project, rubicon_composite_client):
rubicon = rubicon_composite_client
mock_get_project.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
rubicon.get_project(name="Test Project")
assert "all configured storage backends failed" in str(e)
def test_get_projects(rubicon_client):
rubicon = rubicon_client
rubicon.create_project("Project A")
rubicon.create_project("Project B")
projects = rubicon.projects()
assert len(projects) == 2
assert projects[0].name == "Project A"
assert projects[1].name == "Project B"
@mock.patch("rubicon_ml.repository.BaseRepository.get_projects")
def test_get_projects_multiple_backend_error(mock_get_projects, rubicon_composite_client):
rubicon = rubicon_composite_client
mock_get_projects.side_effect = _raise_error
with pytest.raises(RubiconException) as e:
rubicon.projects()
assert "all configured storage backends failed" in str(e)
def test_get_or_create_project(rubicon_client):
rubicon = rubicon_client
created_project = rubicon.get_or_create_project("Test Project A")
assert created_project._domain.name == "Test Project A"
fetched_project = rubicon.get_or_create_project("Test Project A")
assert fetched_project._domain.name == "Test Project A"
assert created_project.id == fetched_project.id
def test_sync_from_memory(rubicon_and_project_client):
rubicon, project = rubicon_and_project_client
with pytest.raises(RubiconException) as e:
rubicon.sync("Test Project", "s3://test/path")
assert "can't sync projects written to memory" in str(e)
@mock.patch("subprocess.run")
@mock.patch("rubicon_ml.client.Rubicon.get_project")
def test_sync_from_local(mock_get_project, mock_run):
rubicon = Rubicon(persistence="filesystem", root_dir="./local/path")
project_name = "Sync Test Project"
mock_get_project.return_value = client.Project(domain.Project(project_name))
rubicon.sync(project_name, "s3://test/path")
assert "aws s3 sync ./local/path/sync-test-project s3://test/path" in str(
mock_run._mock_call_args_list
)
@mock.patch("subprocess.run")
@mock.patch("rubicon_ml.client.Rubicon.get_project")
def test_sync_from_local_error(mock_get_project, mock_run):
rubicon = Rubicon(persistence="filesystem", root_dir="./local/path")
project_name = "Sync Test Project"
mock_get_project.return_value = client.Project(domain.Project(project_name))
mock_run.side_effect = subprocess.CalledProcessError(
cmd="aws cli sync", stderr="Some error. I bet it was proxy tho.", returncode=1
)
with pytest.raises(RubiconException) as e:
rubicon.sync(project_name, "s3://test/path")
assert "Some error. I bet it was proxy tho." in str(e)
def test_get_project_as_dask_df(rubicon_and_project_client_with_experiments):
rubicon, project = rubicon_and_project_client_with_experiments
ddf = rubicon.get_project_as_df(name="Test Project", df_type="dask")
assert isinstance(ddf, dd.core.DataFrame)
def test_get_project_as_pandas_df(rubicon_and_project_client_with_experiments):
rubicon, project = rubicon_and_project_client_with_experiments
ddf = rubicon.get_project_as_df(name="Test Project", df_type="pandas")
assert isinstance(ddf, pd.DataFrame)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_rubicon_json_client.py | import pandas as pd
import pytest
from rubicon_ml.client import Rubicon, RubiconJSON
def test_experiment_to_json_single_experiment(rubicon_and_project_client):
_, project = rubicon_and_project_client
experiment = project.log_experiment("first experiment", tags=["a", "b"])
experiment.log_parameter("n estimators", 3)
experiment.log_feature("year")
experiment.log_metric("accuracy", 0.87)
experiment.log_metric("runtime(s)", 45)
experiment.log_metric("kernel", "linear")
experiment.log_artifact(name="example artifact", data_bytes=b"a")
experiment.log_dataframe(pd.DataFrame([[0, 1], [1, 0]]))
experiment_as_json = RubiconJSON(experiments=experiment)
json = experiment_as_json.json
assert isinstance(json, dict)
assert isinstance(json["experiment"], list)
assert len(json["experiment"]) == 1
assert isinstance(json["experiment"][0], dict)
assert json["experiment"][0]["project_name"] == "Test Project"
assert isinstance(json["experiment"][0]["tags"], list)
assert isinstance(json["experiment"][0]["feature"], list)
assert isinstance(json["experiment"][0]["parameter"], list)
assert isinstance(json["experiment"][0]["metric"], list)
assert isinstance(json["experiment"][0]["artifact"], list)
assert isinstance(json["experiment"][0]["dataframe"], list)
assert isinstance(json["experiment"][0]["metric"][0]["value"], float)
assert isinstance(json["experiment"][0]["metric"][1]["value"], int)
assert isinstance(json["experiment"][0]["metric"][2]["value"], str)
assert json["experiment"][0]["tags"] == ["a", "b"]
assert len(json["experiment"][0]["metric"]) == 3
json_numeric = experiment_as_json.json_numeric
assert isinstance(json_numeric["experiment"][0]["metric"][0]["value"], float)
assert isinstance(json_numeric["experiment"][0]["metric"][1]["value"], int)
assert len(json_numeric["experiment"][0]["metric"]) == 2
def test_experiment_to_json_multiple_experiments(rubicon_and_project_client_with_experiments):
_, project = rubicon_and_project_client_with_experiments
experiments_as_json = RubiconJSON(experiments=project.experiments())
json = experiments_as_json.json
assert isinstance(json, dict)
assert isinstance(json["experiment"], list)
assert len(json["experiment"]) == 10
assert [isinstance(experiment, dict) for experiment in json["experiment"]]
assert [isinstance(experiment["tags"], list) for experiment in json["experiment"]]
assert [isinstance(experiment["feature"], list) for experiment in json["experiment"]]
assert [isinstance(experiment["parameter"], list) for experiment in json["experiment"]]
assert [isinstance(experiment["metric"], list) for experiment in json["experiment"]]
def test_project_to_json_single_project(rubicon_and_project_client_with_experiments):
_, project = rubicon_and_project_client_with_experiments
project_as_json = RubiconJSON(projects=project)
json = project_as_json.json
assert isinstance(json, dict)
assert isinstance(json["project"], list)
assert len(json["project"]) == 1
assert json["project"][0]["name"] == "Test Project"
def test_project_to_json_multiple_projects(rubicon_and_project_client_with_experiments):
rubicon, _ = rubicon_and_project_client_with_experiments
project = rubicon.get_or_create_project(name="Second Test Project")
project.log_artifact(name="example artifact", data_bytes=b"a")
project.log_dataframe(pd.DataFrame([[0, 1], [1, 0]]))
projects_as_json = RubiconJSON(projects=rubicon.projects())
json = projects_as_json.json
assert isinstance(json, dict)
assert isinstance(json["project"], list)
assert len(json["project"]) == 2
assert json["project"][0]["name"] == "Test Project"
assert json["project"][1]["name"] == "Second Test Project"
def test_rubicon_to_json_single_rubicon(rubicon_and_project_client_with_experiments):
rubicon, _ = rubicon_and_project_client_with_experiments
rubicon_as_json = RubiconJSON(rubicon_objects=rubicon)
json = rubicon_as_json.json
assert isinstance(json, dict)
assert isinstance(json["project"], list)
assert len(json["project"]) == 1
assert json["project"][0]["name"] == "Test Project"
def test_rubicon_to_json_multiple_rubicons(rubicon_and_project_client_with_experiments):
rubicon, _ = rubicon_and_project_client_with_experiments
rubicon2 = Rubicon(persistence="memory")
rubicon2.get_or_create_project(name="Test Project for Second Rubicon")
rubicon_as_json = RubiconJSON(rubicon_objects=[rubicon, rubicon2])
json = rubicon_as_json.json
assert isinstance(json, dict)
assert isinstance(json["project"], list)
assert len(json["project"]) == 2
assert json["project"][0]["name"] == "Test Project"
assert json["project"][1]["name"] == "Test Project for Second Rubicon"
def test_convert_to_json_invalid_rubicon_objects_argument(rubicon_client):
with pytest.raises(ValueError):
RubiconJSON(rubicon_objects=5)
with pytest.raises(ValueError):
RubiconJSON(rubicon_objects=[rubicon_client, 5])
def test_convert_to_json_invalid_projects_argument(project_client):
with pytest.raises(ValueError):
RubiconJSON(projects=5)
with pytest.raises(ValueError):
RubiconJSON(rubicon_objects=[project_client, 5])
def test_convert_to_json_invalid_experiments_argument(project_client):
with pytest.raises(ValueError):
RubiconJSON(experiments=5)
experiment = project_client.log_experiment(name="Test Experiment")
with pytest.raises(ValueError):
RubiconJSON(experiments=[experiment, 5])
def test_convert_to_json_rubicon_and_projects_input(rubicon_and_project_client_with_experiments):
rubicon, _ = rubicon_and_project_client_with_experiments
rubicon2 = Rubicon(persistence="memory")
additional_project = rubicon2.get_or_create_project(name="Second Test Project")
conversion_to_json = RubiconJSON(rubicon_objects=rubicon, projects=additional_project)
json = conversion_to_json.json
assert isinstance(json, dict)
assert isinstance(json["project"], list)
assert len(json["project"]) == 2
assert json["project"][0]["name"] == "Test Project"
assert json["project"][1]["name"] == "Second Test Project"
def test_convert_to_json_projects_and_experiments_input(
rubicon_and_project_client_with_experiments,
):
_, project = rubicon_and_project_client_with_experiments
rubicon2 = Rubicon(persistence="memory")
additional_project = rubicon2.get_or_create_project(name="Second Test Project")
experiment1 = additional_project.log_experiment(name="additional experiment 1")
experiment2 = additional_project.log_experiment(name="additional experiment 2")
conversion_to_json = RubiconJSON(projects=project, experiments=[experiment1, experiment2])
json = conversion_to_json.json
assert isinstance(json, dict)
assert isinstance(json["project"], list)
assert len(json["experiment"]) == 2
@pytest.mark.parametrize(
["query", "expected_results"],
[
("$..experiment[*].metric[?(@.value>0.0)].name", ["accuracy", "runtime(s)"]),
("$..experiment[*].metric[?(@.name='kernel')].value", ["linear"]),
],
)
def test_search(query, expected_results, rubicon_and_project_client):
_, project = rubicon_and_project_client
experiment = project.log_experiment("search experiment", tags=["a", "b"])
experiment.log_metric("accuracy", 0.87)
experiment.log_metric("runtime(s)", 45)
experiment.log_metric("kernel", "linear")
experiment_as_json = RubiconJSON(experiments=experiment)
results = experiment_as_json.search(query)
for result, expected_result in zip(results, expected_results):
assert result.value == expected_result
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_dataframe_client.py | import pytest
from rubicon_ml import domain
from rubicon_ml.client import Dataframe, Rubicon
from rubicon_ml.exceptions import RubiconException
def test_properties(project_client):
parent = project_client
domain_dataframe = domain.Dataframe(
description="some description", tags=["x"], name="test title"
)
dataframe = Dataframe(domain_dataframe, parent)
assert dataframe.id == domain_dataframe.id
assert dataframe.name == domain_dataframe.name
assert dataframe.description == domain_dataframe.description
assert dataframe.tags == domain_dataframe.tags
assert dataframe.created_at == domain_dataframe.created_at
assert dataframe.parent == parent
def test_get_data(project_client, test_dataframe):
parent = project_client
df = test_dataframe
logged_df = parent.log_dataframe(df)
assert logged_df.get_data().compute().equals(df.compute())
def test_get_data_multiple_backend_error(test_dataframe):
rb = Rubicon(
composite_config=[
{"persistence": "memory", "root_dir": "./memory/rootA"},
{"persistence": "memory", "root_dir": "./memory/rootB"},
]
)
project = rb.create_project("test")
df = test_dataframe
logged_df = project.log_dataframe(df)
for repo in rb.repositories:
repo.delete_dataframe(project.name, logged_df.id)
with pytest.raises(RubiconException) as e:
logged_df.get_data()
assert f"No data for dataframe with id `{logged_df.id}`" in str(e)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_config.py | from unittest.mock import patch
import pytest
from rubicon_ml.client import Config
from rubicon_ml.exceptions import RubiconException
from rubicon_ml.repository import LocalRepository, MemoryRepository, S3Repository
def test_parameters():
config = Config("memory", "./rubicon-file-system")
assert config.persistence == "memory"
assert config.root_dir == "./rubicon-file-system"
def test_enviroment():
with patch.dict("os.environ", {"PERSISTENCE": "memory", "ROOT_DIR": "./rubicon-file-system"}):
config = Config()
assert config.persistence == "memory"
assert config.root_dir == "./rubicon-file-system"
def test_init_local_repository():
config = Config("filesystem", "/local/rubicon-file-system")
assert isinstance(config.repository, LocalRepository)
assert config.root_dir == config.repository.root_dir
def test_init_s3_repository():
config = Config("filesystem", "s3://rubicon-file-system")
assert isinstance(config.repository, S3Repository)
assert config.root_dir == config.repository.root_dir
def test_init_memory_repository():
config = Config("memory", "/memory/rubicon-file-system")
assert isinstance(config.repository, MemoryRepository)
assert config.root_dir == config.repository.root_dir
def test_init_multiple_backend():
config = Config(
composite_config=[
{"persistence": "filesystem", "root_dir": "./local/root", "is_auto_git_enabled": False},
{
"persistence": "filesystem",
"root_dir": "s3://remote/bucket/root",
"is_auto_git_enabled": False,
},
{"persistence": "memory", "root_dir": "./memory/root", "is_auto_git_enabled": False},
]
)
assert hasattr(config, "repositories")
assert isinstance(config.repositories[0], LocalRepository)
assert isinstance(config.repositories[1], S3Repository)
assert isinstance(config.repositories[2], MemoryRepository)
def test_invalid_persistence():
with pytest.raises(ValueError) as e:
Config("invalid")
assert str(Config.PERSISTENCE_TYPES) in str(e)
def test_invalid_root_dir():
with pytest.raises(ValueError) as e:
Config("filesystem")
assert "root_dir cannot be None" in str(e)
def test_not_in_git_repo():
with patch("subprocess.run") as mock_run:
class MockCompletedProcess:
returncode = 1
mock_run.return_value = MockCompletedProcess()
with pytest.raises(RubiconException) as e:
Config("memory", is_auto_git_enabled=True)
assert "Not a `git` repo" in str(e)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/client/test_artifact_client.py | import os
from unittest.mock import MagicMock, patch
import pytest
from rubicon_ml import domain
from rubicon_ml.client import Artifact, Rubicon
from rubicon_ml.exceptions import RubiconException
def test_properties(project_client):
parent = project_client
domain_artifact = domain.Artifact(name="test.txt")
artifact = Artifact(domain_artifact, parent)
assert artifact.id == domain_artifact.id
assert artifact.name == domain_artifact.name
assert artifact.description == domain_artifact.description
assert artifact.created_at == domain_artifact.created_at
assert artifact.parent == parent
def test_get_data(project_client):
project = project_client
data = b"content"
artifact = project.log_artifact(name="test.txt", data_bytes=data)
artifact._get_data()
assert artifact.data == data
def test_get_json(project_client):
project = project_client
data = {"hello": "world", "numbers": [1, 2, 3]}
artifact = project.log_json(json_object=data, name="test.json")
assert artifact.get_json() == data
def test_internal_get_data_multiple_backend_error():
rb = Rubicon(
composite_config=[
{"persistence": "memory", "root_dir": "./memory/rootA"},
{"persistence": "memory", "root_dir": "./memory/rootB"},
]
)
project = rb.create_project("test")
data = b"content"
artifact = project.log_artifact(name="test.txt", data_bytes=data)
for repo in rb.repositories:
repo.delete_artifact(project.name, artifact.id)
with pytest.raises(RubiconException) as e:
artifact._get_data()
assert "all configured storage backends failed" in str(e)
def test_get_data_unpickle_false(project_client):
project = project_client
data = b"content"
artifact = project.log_artifact(name="test.txt", data_bytes=data)
assert artifact.get_data(unpickle=False) == data
def test_get_data_unpickle_true(project_client):
"""Unpickle=True intended for retrieving python objects
that were logged as artifacts, hence dummy object is needed.
"""
project = project_client
global TestObject # cannot pickle local variable
class TestObject:
value = 1
test_object = TestObject()
artifact = project.log_artifact(name="test object", data_object=test_object)
assert artifact.get_data(unpickle=True).value == test_object.value
def test_get_data_multiple_backend_error():
rb = Rubicon(
composite_config=[
{"persistence": "memory", "root_dir": "./memory/rootA"},
{"persistence": "memory", "root_dir": "./memory/rootB"},
]
)
project = rb.create_project("test")
data = b"content"
artifact = project.log_artifact(name="test.txt", data_bytes=data)
for repo in rb.repositories:
repo.delete_artifact(project.name, artifact.id)
with pytest.raises(RubiconException) as e:
artifact.get_data()
assert "all configured storage backends failed" in str(e)
@patch("fsspec.implementations.local.LocalFileSystem.open")
def test_download_cwd(mock_open, project_client):
project = project_client
data = b"content"
artifact = project.log_artifact(name="test.txt", data_bytes=data)
artifact.data
mock_file = MagicMock()
mock_open.side_effect = mock_file
artifact.download()
mock_open.assert_called_once_with(os.path.join(os.getcwd(), artifact.name), mode="wb")
mock_file().write.assert_called_once_with(data)
@patch("fsspec.implementations.local.LocalFileSystem.open")
def test_download_location(mock_open, project_client):
project = project_client
data = b"content"
artifact = project.log_artifact(name="test.txt", data_bytes=data)
artifact.data
mock_file = MagicMock()
mock_open.side_effect = mock_file
artifact.download(location="/path/to/tests", name="new_name.txt")
mock_open.assert_called_once_with("/path/to/tests/new_name.txt", mode="wb")
mock_file().write.assert_called_once_with(data)
|
0 | capitalone_repos/rubicon-ml/tests/unit/client | capitalone_repos/rubicon-ml/tests/unit/client/utils/test_exception_handling.py | from unittest.mock import patch
import pytest
from rubicon_ml.client.utils.exception_handling import FAILURE_MODES, set_failure_mode
from rubicon_ml.exceptions import RubiconException
@pytest.mark.parametrize("failure_mode", FAILURE_MODES)
def test_set_failure_mode(failure_mode):
set_failure_mode(failure_mode=failure_mode)
from rubicon_ml.client.utils.exception_handling import FAILURE_MODE
assert FAILURE_MODE == failure_mode
# cleanup: reset to default
set_failure_mode("raise")
def test_set_failure_mode_traceback_options():
traceback_chain = True
traceback_limit = 1
set_failure_mode("raise", traceback_chain=traceback_chain, traceback_limit=traceback_limit)
from rubicon_ml.client.utils.exception_handling import (
TRACEBACK_CHAIN,
TRACEBACK_LIMIT,
)
assert TRACEBACK_CHAIN == traceback_chain
assert TRACEBACK_LIMIT == traceback_limit
def test_set_failure_mode_error():
with pytest.raises(ValueError) as e:
set_failure_mode("invalid mode")
assert f"`failure_mode` must be one of {FAILURE_MODES}" in repr(e)
def test_failure_mode_raise(rubicon_client):
set_failure_mode("raise")
with pytest.raises(RubiconException) as e:
rubicon_client.get_project(name="does not exist")
assert "No project with name 'does not exist' found." in repr(e)
@patch("warnings.warn")
def test_failure_mode_log(mock_warn, rubicon_client):
set_failure_mode("warn")
rubicon_client.get_project(name="does not exist")
mock_warn.assert_called_once()
# cleanup: reset to default
set_failure_mode("raise")
@patch("logging.error")
def test_failure_mode_warn(mock_logger, rubicon_client):
set_failure_mode("log")
rubicon_client.get_project(name="does not exist")
mock_logger.assert_called_once()
# cleanup: reset to default
set_failure_mode("raise")
|
0 | capitalone_repos/rubicon-ml/tests/unit/client | capitalone_repos/rubicon-ml/tests/unit/client/utils/test_tags.py | from rubicon_ml.client.utils.tags import has_tag_requirements
def test_or_single_success():
assert has_tag_requirements(["x", "y", "z"], ["y"], "or")
def test_or_multiple_success():
assert has_tag_requirements(["x", "y", "z"], ["a", "y"], "or")
def test_or_single_failure():
assert not has_tag_requirements(["x", "y", "z"], ["a"], "or")
def test_and_single_success():
assert has_tag_requirements(["x", "y", "z"], ["y"], "and")
def test_and_multiple_success():
assert has_tag_requirements(["x", "y", "z"], ["y", "z"], "and")
def test_and_single_failure():
assert not has_tag_requirements(["x", "y", "z"], ["a"], "and")
def test_and_multiple_failure():
assert not has_tag_requirements(["x", "y", "z"], ["a", "z"], "and")
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/sklearn/test_estimator_logger.py | from unittest.mock import patch
import pytest
from rubicon_ml import domain
from rubicon_ml.client.experiment import Experiment
from rubicon_ml.sklearn.estimator_logger import EstimatorLogger
def test_log_parameters_triggers_experiment_log_parameter(project_client, fake_estimator_cls):
project = project_client
experiment = Experiment(domain.Experiment(project_name=project.name), project)
estimator = fake_estimator_cls()
base_logger = EstimatorLogger(estimator=estimator, experiment=experiment, step_name="vect")
with patch.object(Experiment, "log_parameter", return_value=None) as mock_log_parameter:
base_logger.log_parameters()
assert mock_log_parameter.call_count == 3
# the step name gets prepended to each param
mock_log_parameter.assert_called_with(name="vect__ngram_range", value=(1, 2))
def test_log_unserializable_param_triggers_exception(project_client, fake_estimator_cls):
project = project_client
experiment = Experiment(domain.Experiment(project_name=project.name), project)
estimator = fake_estimator_cls(params={"unserializable": b"not serializable"})
base_logger = EstimatorLogger(estimator=estimator, experiment=experiment, step_name="vect")
with patch.object(Experiment, "log_parameter", side_effect=Exception("test")):
with pytest.warns(Warning):
base_logger.log_parameters()
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/sklearn/test_filter_estimator_logger.py | from unittest.mock import patch
import pytest
from rubicon_ml import domain
from rubicon_ml.client.experiment import Experiment
from rubicon_ml.exceptions import RubiconException
from rubicon_ml.sklearn.filter_estimator_logger import FilterEstimatorLogger
def test_select_and_ignore_exception():
with pytest.raises(RubiconException) as e:
FilterEstimatorLogger(select=["this", "should"], ignore=["fail"])
assert "provide either `select` OR `ignore`" in str(e)
def test_ignore_all(fake_estimator_cls):
logger = FilterEstimatorLogger(estimator=fake_estimator_cls(), ignore_all=True)
with patch.object(Experiment, "log_parameter", return_value=None) as mock_log_parameter:
logger.log_parameters()
mock_log_parameter.assert_not_called()
def test_ignore_parameters(project_client, fake_estimator_cls):
project = project_client
experiment = Experiment(domain.Experiment(project_name=project.name), project)
estimator = fake_estimator_cls()
logger = FilterEstimatorLogger(
estimator=estimator, experiment=experiment, step_name="vect", select=["max_df"]
)
with patch.object(Experiment, "log_parameter", return_value=None) as mock_log_parameter:
logger.log_parameters()
assert mock_log_parameter.call_count == 1
# the step name gets prepended to each param
mock_log_parameter.assert_called_with(name="vect__max_df", value=0.75)
def test_select_parameters(project_client, fake_estimator_cls):
project = project_client
experiment = Experiment(domain.Experiment(project_name=project.name), project)
estimator = fake_estimator_cls()
logger = FilterEstimatorLogger(
estimator=estimator, experiment=experiment, step_name="vect", ignore=["ngram_range"]
)
with patch.object(Experiment, "log_parameter", return_value=None) as mock_log_parameter:
logger.log_parameters()
assert mock_log_parameter.call_count == 2
# the step name gets prepended to each param
mock_log_parameter.assert_called_with(name="vect__lowercase", value=True)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/sklearn/test_pipeline.py | from tempfile import mkdtemp
from unittest.mock import patch
from pytest import raises
from rubicon_ml.sklearn import RubiconPipeline
from rubicon_ml.sklearn.estimator_logger import EstimatorLogger
from rubicon_ml.sklearn.filter_estimator_logger import FilterEstimatorLogger
from rubicon_ml.sklearn.pipeline import Pipeline, make_pipeline
def test_get_default_estimator_logger(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
pipeline = RubiconPipeline(project, steps)
logger = pipeline.get_estimator_logger()
assert isinstance(logger, EstimatorLogger)
def test_get_user_defined_estimator_logger(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_loggers=user_defined_logger)
logger = pipeline.get_estimator_logger("est")
assert isinstance(logger, FilterEstimatorLogger)
def test_fit_logs_parameters(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
with patch.object(Pipeline, "fit", return_value=None):
with patch.object(
FilterEstimatorLogger, "log_parameters", return_value=None
) as mock_log_parameters:
pipeline.fit(["fake data"])
mock_log_parameters.assert_called_once()
def test_fit_logs_fit_parameters(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
with patch.object(Pipeline, "fit", return_value=None):
with patch.object(FilterEstimatorLogger, "log_parameters", return_value=None):
pipeline.fit(["fake data"], est__test_fit_param="test_value")
parameters = pipeline.experiment.parameters()
assert len(parameters) == 1
parameter = parameters[0]
assert parameter.name == "est__test_fit_param"
assert parameter.value == "test_value"
def test_score_logs_metric(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
pipeline = RubiconPipeline(project, steps)
with patch.object(Pipeline, "score", return_value=None):
with patch.object(EstimatorLogger, "log_metric", return_value=None) as mock_log_metric:
pipeline.score(["fake data"])
mock_log_metric.assert_called_once()
def test_make_pipeline(project_client, fake_estimator_cls):
project = project_client
clf = fake_estimator_cls()
clf1 = fake_estimator_cls()
pipe = make_pipeline(
project, clf, clf1, experiment_kwargs={"name": "RubiconPipeline experiment"}
)
assert len(pipe.steps) == 2
assert pipe.steps[0][1] == clf
assert pipe.steps[1][1] == clf1
assert len(pipe.user_defined_loggers) == 0
def test_make_pipeline_with_loggers(project_client, fake_estimator_cls):
project = project_client
clf = fake_estimator_cls()
clf1 = fake_estimator_cls()
user_defined_logger = FilterEstimatorLogger()
user_defined_logger1 = FilterEstimatorLogger()
pipe = make_pipeline(
project,
(clf, user_defined_logger),
(clf1, user_defined_logger1),
experiment_kwargs={"name": "RubiconPipeline experiment"},
)
assert len(pipe.steps) == 2
assert pipe.steps[0][1] == clf
assert pipe.steps[1][1] == clf1
assert len(pipe.user_defined_loggers) == 2
assert pipe.user_defined_loggers[pipe.steps[0][0]] == user_defined_logger
assert pipe.user_defined_loggers[pipe.steps[1][0]] == user_defined_logger1
pipe = make_pipeline(
project,
clf,
(clf1, user_defined_logger1),
experiment_kwargs={"name": "RubiconPipeline experiment"},
)
assert len(pipe.steps) == 2
assert pipe.steps[0][1] == clf
assert pipe.steps[1][1] == clf1
assert len(pipe.user_defined_loggers) == 1
assert pipe.user_defined_loggers[pipe.steps[1][0]] == user_defined_logger1
def test_make_pipeline_without_project(fake_estimator_cls):
estimator = fake_estimator_cls()
steps = [("est", estimator)]
with raises(ValueError) as e:
make_pipeline(steps)
assert "project" + str(steps) + " must be of type rubicon_ml.client.project.Project" == str(
e.value
)
def test_pipeline_memory_verbose(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
cachedir = mkdtemp()
user_defined_logger = FilterEstimatorLogger()
pipeline = RubiconPipeline(project, steps, {"est": user_defined_logger}, memory=cachedir)
assert pipeline.memory == cachedir
assert pipeline.verbose is False
pipeline = RubiconPipeline(project, steps, {"est": user_defined_logger}, verbose=True)
assert pipeline.memory is None
assert pipeline.verbose is True
pipeline = RubiconPipeline(project, steps, {"est": user_defined_logger})
assert pipeline.memory is None
assert pipeline.verbose is False
def test_multiple_fit_multiple_scores(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
with patch.object(Pipeline, "fit", return_value=None):
with patch.object(
FilterEstimatorLogger, "log_parameters", return_value=None
) as mock_log_parameters:
pipeline.fit(["fake data"])
pipeline.fit("additional fake data")
assert mock_log_parameters._mock_call_count == 2
assert len(project.experiments()) == 2
with patch.object(Pipeline, "score", return_value=None):
with patch.object(EstimatorLogger, "log_metric", return_value=None) as mock_log_metric:
pipeline.score(["fake data"])
assert pipeline.experiment is None
pipeline.score(["additional fake data"])
assert mock_log_metric._mock_call_count == 2
assert len(project.experiments()) == 3
def test_multiple_scores(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
pipeline = RubiconPipeline(project, steps)
with patch.object(Pipeline, "score", return_value=None) as mock_log_metric:
with patch.object(EstimatorLogger, "log_metric", return_value=None):
# first score gets its own explicitly declared experiment
experiment = project.log_experiment(name="fake experiment")
pipeline.score(["fake data"], experiment=experiment)
pipeline.score(["additional fake data"])
experiments = project.experiments()
assert len(experiments) == 2
assert mock_log_metric._mock_call_count == 2
assert experiments[0].name == "fake experiment"
assert experiments[1].name == "RubiconPipeline experiment"
def test_multiple_fits(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
with patch.object(Pipeline, "fit", return_value=None):
with patch.object(
FilterEstimatorLogger, "log_parameters", return_value=None
) as mock_log_parameters:
# first fit gets its own explicitly declared experiment
experiment = project.log_experiment(name="fake experiment")
pipeline.fit(["fake data"], experiment=experiment)
pipeline.fit("additional fake data")
experiments = project.experiments()
assert len(experiments) == 2
assert mock_log_parameters._mock_call_count == 2
assert experiments[0].name == "fake experiment"
assert experiments[1].name == "RubiconPipeline experiment"
def test_score_samples(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
with patch.object(Pipeline, "fit", return_value=None):
with patch.object(FilterEstimatorLogger, "log_parameters", return_value=None):
pipeline.fit(["fake data"])
assert len(project.experiments()) == 1
with patch.object(Pipeline, "score_samples", return_value=None):
with patch.object(EstimatorLogger, "log_metric", return_value=None) as mock_log_metric:
pipeline.score_samples(["fake data"])
pipeline.score_samples(["additional fake data"])
experiment = project.log_experiment(name="fake experiment")
pipeline.score_samples(["additional fake data"], experiment=experiment)
assert mock_log_metric._mock_call_count == 3
assert len(project.experiments()) == 3
assert project.experiments()[2].name == "fake experiment"
def test_pipeline_slices(project_client, fake_estimator_cls):
project = project_client
steps = [
("est", fake_estimator_cls()),
("est1", fake_estimator_cls()),
("est2", fake_estimator_cls()),
]
cachedir = mkdtemp()
est_logger = FilterEstimatorLogger()
est1_logger = FilterEstimatorLogger
user_defined_loggers = {"est": est_logger, "est1": est1_logger}
pipeline = RubiconPipeline(project, steps, user_defined_loggers, memory=cachedir)
assert pipeline[1:].steps == steps[1:]
assert pipeline[1:].user_defined_loggers == {"est1": est1_logger}
assert pipeline[:-1].steps == steps[:-1]
with raises(ValueError) as e:
pipeline[::-1]
assert "Pipeline slicing only supports a step of 1" == str(e.value)
def test_sklearn_pipeline_invalid_step_count(project_client, fake_estimator_cls):
project = project_client
steps = [
("est", fake_estimator_cls()),
("est1", fake_estimator_cls()),
("est2", fake_estimator_cls()),
]
cachedir = mkdtemp()
est_logger = FilterEstimatorLogger()
est1_logger = FilterEstimatorLogger
user_defined_loggers = {"est": est_logger, "est1": est1_logger}
pipeline = RubiconPipeline(project, steps, user_defined_loggers, memory=cachedir)
with raises(ValueError) as e:
pipeline[::-1]
assert "Pipeline slicing only supports a step of 1" == str(e.value)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/viz/test_experiments_table.py | from dash import Dash
from rubicon_ml.viz import ExperimentsTable
def test_experiments_table(viz_experiments):
experiments_table = ExperimentsTable(experiments=viz_experiments, is_selectable=True)
expected_experiment_ids = [e.id for e in viz_experiments]
for experiment in experiments_table.experiments:
assert experiment.id in expected_experiment_ids
expected_experiment_ids.remove(experiment.id)
assert len(expected_experiment_ids) == 0
assert experiments_table.is_selectable is True
def test_experiments_table_load_data(viz_experiments):
experiments_table = ExperimentsTable(experiments=viz_experiments)
experiments_table.load_experiment_data()
expected_experiment_ids = [e.id for e in viz_experiments]
expected_metric_names = [m.name for m in viz_experiments[0].metrics()]
expected_parameter_names = [p.name for p in viz_experiments[0].parameters()]
for record in experiments_table.experiment_records:
assert record["id"] in expected_experiment_ids
assert all([record.get(name) is not None for name in expected_metric_names])
assert all([record.get(name) is not None for name in expected_parameter_names])
assert experiments_table.commit_hash == viz_experiments[0].commit_hash
assert experiments_table.github_url == f"test.github.url/tree/{viz_experiments[0].commit_hash}"
def test_experiments_table_layout(viz_experiments):
experiments_table = ExperimentsTable(experiments=viz_experiments)
experiments_table.load_experiment_data()
layout = experiments_table.layout
assert len(layout.children) == 4
assert layout.children[-1].children.id == "experiment-table"
assert layout.children[-2].id == "publish-modal"
def test_experiments_table_layout_not_selectable(viz_experiments):
experiments_table = ExperimentsTable(experiments=viz_experiments, is_selectable=False)
experiments_table.load_experiment_data()
layout = experiments_table.layout
assert len(layout.children) == 3
assert layout.children[-1].children.id == "experiment-table"
assert layout.children[-2].id == "publish-modal"
def test_experiments_table_register_callbacks(viz_experiments):
experiments_table = ExperimentsTable(experiments=viz_experiments)
experiments_table.app = Dash(__name__, title="test callbacks")
experiments_table.register_callbacks()
callback_values = list(experiments_table.app.callback_map.values())
assert len(callback_values) == 4
registered_callback_names = [callback["callback"].__name__ for callback in callback_values]
assert "update_selected_column_checkboxes" in registered_callback_names
assert "update_hidden_experiment_table_cols" in registered_callback_names
assert "update_selected_experiment_table_rows" in registered_callback_names
assert "toggle_publish_modal" in registered_callback_names
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/viz/test_common.py | import pytest
from rubicon_ml.viz.common.colors import get_rubicon_colorscale
from rubicon_ml.viz.common.dropdown_header import dropdown_header
@pytest.mark.parametrize("num_colors,expected", [(1, 2), (4, 4)])
def test_get_rubicon_colorscale(num_colors, expected):
colors = get_rubicon_colorscale(num_colors)
assert len(colors) == expected
def test_dropdown_header():
layout = dropdown_header(["A", "B", "C"], "A", "test left", "test right", "test-id")
assert layout.id.startswith("test-id")
assert layout.children[1].children.label == "A"
assert [child.children for child in layout.children[1].children.children] == ["A", "B", "C"]
assert layout.children[0].children.children == "test left"
assert layout.children[2].children.children == "test right"
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/viz/test_base.py | from dash import Dash, html
from rubicon_ml.viz.base import VizBase
class VizBaseTest(VizBase):
app = Dash(__name__, title="test base")
@property
def layout(self):
return html.Div(id="test-layout")
def test_base_build_layout():
base = VizBaseTest()
base.build_layout()
layout = base.app.layout
assert len(layout) == 8
assert layout.children.children[-1].children.id == "test-layout"
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/viz/test_metric_correlation_plot.py | import pytest
from dash import Dash
from rubicon_ml.viz import MetricCorrelationPlot
def test_metric_correlation_plot(viz_experiments):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
parameter_names=["test param 1", "test param 2"],
selected_metric="test metric 1",
)
expected_experiment_ids = [e.id for e in viz_experiments]
for experiment in metric_plot.experiments:
assert experiment.id in expected_experiment_ids
expected_experiment_ids.remove(experiment.id)
assert len(expected_experiment_ids) == 0
assert metric_plot.metric_names == ["test metric 0", "test metric 1"]
assert metric_plot.parameter_names == ["test param 1", "test param 2"]
assert metric_plot.selected_metric == "test metric 1"
def test_metric_correlation_plot_load_data(viz_experiments):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
)
metric_plot.load_experiment_data()
expected_experiment_ids = [e.id for e in viz_experiments]
expected_metric_names = ["test metric 0", "test metric 1"]
expected_parameter_names = [p.name for p in viz_experiments[0].parameters()]
for experiment_id, record in metric_plot.experiment_records.items():
assert experiment_id in expected_experiment_ids
for metric_name in record["metrics"].keys():
assert metric_name in expected_metric_names
for parameter_name in record["parameters"].keys():
assert parameter_name in expected_parameter_names
assert metric_plot.visible_parameter_names.sort() == expected_parameter_names.sort()
assert metric_plot.visible_metric_names.sort() == expected_metric_names.sort()
assert metric_plot.selected_metric == expected_metric_names[0]
def test_metric_correlation_plot_load_data_throws_error(viz_experiments):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
selected_metric="nonexistant metric",
)
with pytest.raises(ValueError) as e:
metric_plot.load_experiment_data()
assert "no metric named `selected_metric` 'nonexistant metric'" in str(e.value)
def test_metric_correlation_plot_layout(viz_experiments):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
selected_metric="test metric 1",
)
metric_plot.load_experiment_data()
layout = metric_plot.layout
assert len(layout.children) == 2
assert layout.children[-1].children.id == "metric-correlation-plot-container"
assert layout.children[-1].children.children.id == "metric-correlation-plot"
@pytest.mark.parametrize("is_linked,expected", [(False, 1), (True, 2)])
def test_metric_correlation_plot_register_callbacks(viz_experiments, is_linked, expected):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
)
metric_plot.app = Dash(__name__, title="test callbacks")
metric_plot.register_callbacks(link_experiment_table=is_linked)
callback_values = list(metric_plot.app.callback_map.values())
assert len(callback_values) == 1
registered_callback_name = callback_values[0]["callback"].__name__
registered_callback_len_input = len(callback_values[0]["inputs"])
assert registered_callback_name == "update_metric_plot"
assert registered_callback_len_input == expected
def test_metric_correlation_plot_get_dimensions(viz_experiments):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
selected_metric="test metric 1",
)
metric_plot.load_experiment_data()
dimension = metric_plot._get_dimension("test dimension", [1, 2, 3, 4])
assert list(dimension["values"]) == [1, 2, 3, 4]
def test_metric_correlation_plot_get_string_dimensions(viz_experiments):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
selected_metric="test metric 1",
)
metric_plot.load_experiment_data()
dimension = metric_plot._get_dimension("test dimension", ["A", "B", "A", "B", "C"])
assert dimension["tickvals"] == [0, 1, 2]
assert list(dimension["ticktext"]) == ["A", "B", "C"]
assert list(dimension["values"]) == [0, 1, 0, 1, 2]
def test_metric_correlation_plot_get_boolean_dimensions(viz_experiments):
metric_plot = MetricCorrelationPlot(
experiments=viz_experiments,
metric_names=["test metric 0", "test metric 1"],
selected_metric="test metric 1",
)
metric_plot.load_experiment_data()
dimension = metric_plot._get_dimension("test dimension", [True, False, True])
assert dimension["tickvals"] == [0, 1]
assert list(dimension["ticktext"]) == ["False", "True"]
assert list(dimension["values"]) == [1, 0, 1]
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/viz/test_dataframe_plot.py | import pytest
from dash import Dash
from rubicon_ml.viz import DataframePlot
def test_dataframe_plot(viz_experiments):
def test_plotting_func(*args, **kwargs):
return
dataframe_plot = DataframePlot(
"test dataframe",
experiments=viz_experiments,
plotting_func=test_plotting_func,
plotting_func_kwargs={"test": "test"},
x="test x",
y="test y",
)
expected_experiment_ids = [e.id for e in viz_experiments]
for experiment in dataframe_plot.experiments:
assert experiment.id in expected_experiment_ids
expected_experiment_ids.remove(experiment.id)
assert len(expected_experiment_ids) == 0
assert dataframe_plot.dataframe_name == "test dataframe"
assert dataframe_plot.plotting_func == test_plotting_func
assert dataframe_plot.plotting_func_kwargs == {"test": "test"}
assert dataframe_plot.x == "test x"
assert dataframe_plot.y == "test y"
def test_dataframe_plot_load_data(viz_experiments):
dataframe_plot = DataframePlot("test dataframe", experiments=viz_experiments)
dataframe_plot.load_experiment_data()
expected_experiment_ids = [e.id for e in viz_experiments]
for eeid in expected_experiment_ids:
assert eeid in list(dataframe_plot.data_df["experiment_id"])
expected_len_df = 0
for experiment in viz_experiments:
for dataframe in experiment.dataframes():
expected_len_df = expected_len_df + len(dataframe.get_data())
assert len(dataframe_plot.data_df) == expected_len_df
def test_dataframe_plot_layout(viz_experiments):
dataframe_plot = DataframePlot("test dataframe", experiments=viz_experiments)
dataframe_plot.load_experiment_data()
layout = dataframe_plot.layout
assert len(layout.children) == 3
assert layout.children[0].id == "dummy-callback-trigger"
assert layout.children[-1].children.id == "dataframe-plot"
@pytest.mark.parametrize("is_linked,expected", [(False, 1), (True, 2)])
def test_dataframe_plot_register_callbacks_link(viz_experiments, is_linked, expected):
dataframe_plot = DataframePlot("test dataframe", experiments=viz_experiments)
dataframe_plot.app = Dash(__name__, title="test callbacks")
dataframe_plot.register_callbacks(link_experiment_table=is_linked)
callback_values = list(dataframe_plot.app.callback_map.values())
assert len(callback_values) == 1
registered_callback_name = callback_values[0]["callback"].__name__
registered_callback_len_input = len(callback_values[0]["inputs"])
assert registered_callback_name == "update_dataframe_plot"
assert registered_callback_len_input == expected
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/viz/test_dashboard.py | from dash import Dash, html
from rubicon_ml.viz import Dashboard, ExperimentsTable, MetricCorrelationPlot
from rubicon_ml.viz.base import VizBase
class WidgetTest(VizBase):
def __init__(self, layout_id):
self.layout_id = layout_id
self.load_experiment_data_call_count = 0
self.register_callbacks_call_count = 0
@property
def layout(self):
return html.Div(id=self.layout_id)
def load_experiment_data(self):
self.load_experiment_data_call_count += 1
def register_callbacks(self, link_experiment_table=False):
self.register_callbacks_call_count += 1
def test_dashboard(viz_experiments):
widget_a = WidgetTest(layout_id="a")
widget_b = WidgetTest(layout_id="b")
dashboard = Dashboard(viz_experiments, widgets=[[widget_a, widget_b]])
expected_experiment_ids = [e.id for e in viz_experiments]
for experiment in dashboard.experiments:
assert experiment.id in expected_experiment_ids
expected_experiment_ids.remove(experiment.id)
assert dashboard.widgets == [[widget_a, widget_b]]
def test_dashboard_load_data(viz_experiments):
widget_a = WidgetTest(layout_id="a")
widget_b = WidgetTest(layout_id="b")
assert widget_a.load_experiment_data_call_count == 0
assert widget_b.load_experiment_data_call_count == 0
dashboard = Dashboard(viz_experiments, widgets=[[widget_a, widget_b]])
dashboard.load_experiment_data()
assert widget_a.load_experiment_data_call_count == 1
assert widget_b.load_experiment_data_call_count == 1
def test_dashboard_layout_horizontal(viz_experiments):
widget_a = WidgetTest(layout_id="a")
widget_b = WidgetTest(layout_id="b")
dashboard = Dashboard(viz_experiments, widgets=[[widget_a, widget_b]])
layout = dashboard.layout
layout.children[0].children[0].children == widget_a.layout
layout.children[0].children[1].children == widget_b.layout
def test_dashboard_layout_veritcal(viz_experiments):
widget_a = WidgetTest(layout_id="a")
widget_b = WidgetTest(layout_id="b")
dashboard = Dashboard(viz_experiments, widgets=[[widget_a], [widget_b]])
layout = dashboard.layout
layout.children[0].children[0].children == widget_a.layout
layout.children[1].children[0].children == widget_b.layout
def test_dashboard_register_callbacks(viz_experiments):
widget_a = WidgetTest(layout_id="a")
widget_b = WidgetTest(layout_id="b")
assert widget_a.register_callbacks_call_count == 0
assert widget_b.register_callbacks_call_count == 0
dashboard = Dashboard(viz_experiments, widgets=[[widget_a, widget_b]])
dashboard.app = Dash(__name__, title="test dashboard")
dashboard.register_callbacks()
assert widget_a.register_callbacks_call_count == 1
assert widget_b.register_callbacks_call_count == 1
def test_default_dashbaord(viz_experiments):
dashboard = Dashboard(viz_experiments)
assert isinstance(dashboard.widgets[0][0], ExperimentsTable)
assert isinstance(dashboard.widgets[1][0], MetricCorrelationPlot)
|
0 | capitalone_repos/rubicon-ml/tests/unit | capitalone_repos/rubicon-ml/tests/unit/viz/test_metric_lists_comparison.py | import pytest
from dash import Dash
from rubicon_ml.viz import MetricListsComparison
def test_metric_lists_comparison(viz_experiments):
metric_comparison = MetricListsComparison(
column_names=["var_0", "var_1", "var_2", "var_3", "var_4"],
experiments=viz_experiments,
selected_metric="test metric 2",
)
expected_experiment_ids = [e.id for e in viz_experiments]
for experiment in metric_comparison.experiments:
assert experiment.id in expected_experiment_ids
expected_experiment_ids.remove(experiment.id)
assert len(expected_experiment_ids) == 0
assert metric_comparison.column_names == ["var_0", "var_1", "var_2", "var_3", "var_4"]
assert metric_comparison.selected_metric == "test metric 2"
def test_metric_lists_comparison_load_data(viz_experiments):
metric_comparison = MetricListsComparison(experiments=viz_experiments)
metric_comparison.load_experiment_data()
expected_experiment_ids = [e.id for e in viz_experiments]
expected_metric_names = ["test metric 2", "test metric 3"]
for experiment_id, record in metric_comparison.experiment_records.items():
assert experiment_id in expected_experiment_ids
for metric_name in expected_metric_names:
assert metric_name in record
assert metric_comparison.selected_metric == expected_metric_names[0]
def test_metric_lists_comparison_load_data_throws_error(viz_experiments):
metric_comparison = MetricListsComparison(
experiments=viz_experiments,
selected_metric="nonexistant metric",
)
with pytest.raises(ValueError) as e:
metric_comparison.load_experiment_data()
assert "no metric named `selected_metric` 'nonexistant metric'" in str(e.value)
def test_metric_list_comparison_layout(viz_experiments):
metric_comparison = MetricListsComparison(experiments=viz_experiments)
metric_comparison.load_experiment_data()
layout = metric_comparison.layout
assert len(layout.children) == 2
assert layout.children[-1].children.id == "metric-heatmap-container"
assert layout.children[-1].children.children.id == "metric-heatmap"
@pytest.mark.parametrize("is_linked,expected", [(False, 1), (True, 2)])
def test_metric_correlation_plot_register_callbacks(viz_experiments, is_linked, expected):
metric_comparison = MetricListsComparison(experiments=viz_experiments)
metric_comparison.app = Dash(__name__, title="test callbacks")
metric_comparison.register_callbacks(link_experiment_table=is_linked)
callback_values = list(metric_comparison.app.callback_map.values())
assert len(callback_values) == 1
registered_callback_name = callback_values[0]["callback"].__name__
registered_callback_len_input = len(callback_values[0]["inputs"])
assert registered_callback_name == "update_metric_heatmap"
assert registered_callback_len_input == expected
|