Merge pull request #781 from efiop/master

metrics
This commit is contained in:
Ruslan Kuprieiev
2018-06-16 16:16:36 +03:00
committed by GitHub
13 changed files with 194 additions and 63 deletions
+54 -6
View File
@@ -18,7 +18,7 @@ from dvc.command.imp import CmdImport
from dvc.command.config import CmdConfig
from dvc.command.checkout import CmdCheckout
from dvc.command.remote import CmdRemoteAdd, CmdRemoteRemove, CmdRemoteModify, CmdRemoteList
from dvc.command.metrics import CmdMetrics
from dvc.command.metrics import CmdMetricsShow, CmdMetricsAdd, CmdMetricsRemove
from dvc.command.install import CmdInstall
from dvc.stage import Stage
from dvc import VERSION
@@ -138,6 +138,11 @@ def parse_args(argv=None):
action='append',
default=[],
help='Declare output regular file or directory (sync to Git, not DVC cache).')
run_parser.add_argument('-M',
'--metrics-no-cache',
action='append',
default=[],
help='Declare output metric file or directory (not cached by DVC).')
run_parser.add_argument('-f',
'--file',
help='Specify name of the state file')
@@ -240,6 +245,11 @@ def parse_args(argv=None):
'--cwd',
default=os.path.curdir,
help='Directory to reproduce from.')
repro_parser.add_argument('-m',
'--metrics',
action='store_true',
default=False,
help='Show metrics after reproduction')
repro_parser.set_defaults(func=CmdRepro)
# Remove
@@ -382,19 +392,57 @@ def parse_args(argv=None):
'metrics',
parents=[parent_parser],
help='Get metrics from all branches')
metrics_parser.add_argument(
metrics_subparsers = metrics_parser.add_subparsers(
dest='cmd',
help='Use dvc metrics CMD --help for command-specific help')
_fix_subparsers(metrics_subparsers)
metrics_show_parser = metrics_subparsers.add_parser(
'show',
parents=[parent_parser],
help='Show metrics')
metrics_show_parser.add_argument(
'path',
nargs='?',
help='Path to metrics file')
metrics_parser.add_argument(
metrics_show_parser.add_argument(
'--json-path',
help='JSON path')
metrics_parser.add_argument(
metrics_show_parser.add_argument(
'--tsv-path',
help='TSV path \'row,column\'(e.g. \'1,2\')')
metrics_parser.add_argument(
metrics_show_parser.add_argument(
'--htsv-path',
help='Headed TSV path \'row,column\'(e.g. \'Name,3\'')
metrics_parser.set_defaults(func=CmdMetrics)
metrics_show_parser.add_argument(
'--all-branches',
action='store_true',
default=False,
help='Show metrics for all branches')
metrics_show_parser.set_defaults(func=CmdMetricsShow)
metrics_add_parser = metrics_subparsers.add_parser(
'add',
parents=[parent_parser],
help='Add metrics')
metrics_add_parser.add_argument(
'path',
help='Path to metrics file')
metrics_add_parser.set_defaults(func=CmdMetricsAdd)
metrics_remove_parser = metrics_subparsers.add_parser(
'remove',
parents=[parent_parser],
help='Remove metrics')
metrics_remove_parser.add_argument(
'path',
help='Path to metrics file')
metrics_remove_parser.set_defaults(func=CmdMetricsRemove)
# Install
install_parser = subparsers.add_parser(
+18 -6
View File
@@ -1,11 +1,23 @@
from dvc.command.common.base import CmdBase
class CmdMetrics(CmdBase):
class CmdMetricsShow(CmdBase):
def run(self):
for branch, metric in self.project.metrics(self.args.path,
json_path=self.args.json_path,
tsv_path=self.args.tsv_path,
htsv_path=self.args.htsv_path).items():
self.project.logger.info("{}: {}".format(branch, metric))
self.project.metrics_show(self.args.path,
json_path=self.args.json_path,
tsv_path=self.args.tsv_path,
htsv_path=self.args.htsv_path,
all_branches=self.args.all_branches)
return 0
class CmdMetricsAdd(CmdBase):
def run(self):
self.project.metrics_add(self.args.path)
return 0
class CmdMetricsRemove(CmdBase):
def run(self):
self.project.metrics_remove(self.args.path)
return 0
+2
View File
@@ -18,6 +18,8 @@ class CmdRepro(CmdBase):
self.project.reproduce(target,
recursive=recursive,
force=self.args.force)
if self.args.metrics:
self.project.metrics_show()
except ReproductionError as ex:
msg = 'Failed to reproduce \'{}\''.format(target)
self.project.logger.error(msg, ex)
+8 -2
View File
@@ -8,12 +8,16 @@ from dvc.exceptions import DvcException
class CmdRun(CmdBase):
def run(self):
fname = self.stage_file_name(self.args.file, self.args.outs, self.args.outs_no_cache)
fname = self.stage_file_name(self.args.file,
self.args.outs,
self.args.outs_no_cache,
self.args.metrics_no_cache)
try:
self.project.run(cmd=' '.join(self.args.command),
outs=self.args.outs,
outs_no_cache=self.args.outs_no_cache,
metrics_no_cache=self.args.metrics_no_cache,
deps=self.args.deps,
fname=fname,
cwd=self.args.cwd,
@@ -25,7 +29,7 @@ class CmdRun(CmdBase):
return 0
@staticmethod
def stage_file_name(args_file, args_outs, args_outs_no_cache):
def stage_file_name(args_file, args_outs, args_outs_no_cache, args_metrics_no_cache):
if args_file:
return args_file
@@ -33,6 +37,8 @@ class CmdRun(CmdBase):
result = CmdRun._stage_file_basename(args_outs[0])
elif args_outs_no_cache:
result = CmdRun._stage_file_basename(args_outs_no_cache[0])
elif args_metrics_no_cache:
result = CmdRun._stage_file_basename(args_metrics_no_cache[0])
else:
result = Stage.STAGE_FILE
+8 -6
View File
@@ -21,18 +21,19 @@ OUTS_MAP = {'hdfs': OutputHDFS,
'': OutputLOCAL}
SCHEMA[schema.Optional(OutputLOCAL.PARAM_CACHE)] = bool
SCHEMA[schema.Optional(OutputLOCAL.PARAM_METRIC)] = bool
def _get(stage, p, info, cache):
def _get(stage, p, info, cache, metric):
parsed = urlparse(p)
if parsed.scheme == 'remote':
sect = stage.project.config._config[Config.SECTION_REMOTE_FMT.format(parsed.netloc)]
remote = Remote(stage.project, sect)
return OUTS_MAP[remote.scheme](stage, p, info, cache=cache, remote=remote)
return OUTS_MAP[remote.scheme](stage, p, info, cache=cache, remote=remote, metric=metric)
for o in OUTS:
if o.supported(p):
return o(stage, p, info, cache=cache, remote=None)
return o(stage, p, info, cache=cache, remote=None, metric=metric)
raise DvcException('Output \'{}\' is not supported'.format(p))
@@ -41,12 +42,13 @@ def loadd_from(stage, d_list):
for d in d_list:
p = d.pop(DependencyBase.PARAM_PATH)
cache = d.pop(OutputLOCAL.PARAM_CACHE, True)
ret.append(_get(stage, p, info=d, cache=cache))
metric = d.pop(OutputLOCAL.PARAM_METRIC, False)
ret.append(_get(stage, p, info=d, cache=cache, metric=metric))
return ret
def loads_from(stage, s_list, use_cache=True):
def loads_from(stage, s_list, use_cache=True, metric=False):
ret = []
for s in s_list:
ret.append(_get(stage, s, info={}, cache=use_cache))
ret.append(_get(stage, s, info={}, cache=use_cache, metric=metric))
return ret
+4 -1
View File
@@ -4,16 +4,19 @@ from dvc.exceptions import DvcException
class OutputGS(DependencyGS):
PARAM_CACHE = 'cache'
PARAM_METRIC = 'metric'
def __init__(self, stage, path, info=None, remote=None, cache=True):
def __init__(self, stage, path, info=None, remote=None, cache=True, metric=False):
super(OutputGS, self).__init__(stage, path, info, remote=remote)
self.use_cache = cache
self.metric = metric
if cache and self.project.cache.gs == None:
raise DvcException("No cache location setup for \'gs\' outputs.")
def dumpd(self):
ret = super(OutputGS, self).dumpd()
ret[self.PARAM_CACHE] = self.use_cache
ret[self.PARAM_METRIC] = self.metric
return ret
def changed(self):
+4 -1
View File
@@ -4,16 +4,19 @@ from dvc.exceptions import DvcException
class OutputHDFS(DependencyHDFS):
PARAM_CACHE = 'cache'
PARAM_METRIC = 'metric'
def __init__(self, stage, path, info=None, remote=None, cache=True):
def __init__(self, stage, path, info=None, remote=None, cache=True, metric=False):
super(OutputHDFS, self).__init__(stage, path, info, remote=remote)
self.use_cache = cache
self.metric = metric
if cache and self.project.cache.hdfs == None:
raise DvcException("No cache location setup for \'hdfs\' outputs.")
def dumpd(self):
ret = super(OutputHDFS, self).dumpd()
ret[self.PARAM_CACHE] = self.use_cache
ret[self.PARAM_METRIC] = self.metric
return ret
def changed(self):
+4 -1
View File
@@ -12,13 +12,15 @@ from dvc.utils import remove
class OutputLOCAL(DependencyLOCAL):
PARAM_CACHE = 'cache'
PARAM_METRIC = 'metric'
DoesNotExistError = OutputDoesNotExistError
IsNotFileOrDirError = OutputIsNotFileOrDirError
def __init__(self, stage, path, info=None, remote=None, cache=True):
def __init__(self, stage, path, info=None, remote=None, cache=True, metric=False):
super(OutputLOCAL, self).__init__(stage, path, info, remote=remote)
self.use_cache = cache
self.metric = metric
@property
def md5(self):
@@ -31,6 +33,7 @@ class OutputLOCAL(DependencyLOCAL):
def dumpd(self):
ret = super(OutputLOCAL, self).dumpd()
ret[self.PARAM_CACHE] = self.use_cache
ret[self.PARAM_METRIC] = self.metric
return ret
def changed(self):
+4 -1
View File
@@ -4,16 +4,19 @@ from dvc.exceptions import DvcException
class OutputS3(DependencyS3):
PARAM_CACHE = 'cache'
PARAM_METRIC = 'metric'
def __init__(self, stage, path, info=None, remote=None, cache=True):
def __init__(self, stage, path, info=None, remote=None, cache=True, metric=False):
super(OutputS3, self).__init__(stage, path, info, remote=remote)
self.use_cache = cache
self.metric = metric
if cache and self.project.cache.s3 == None:
raise DvcException("No cache location setup for \'s3\' outputs.")
def dumpd(self):
ret = super(OutputS3, self).dumpd()
ret[self.PARAM_CACHE] = self.use_cache
ret[self.PARAM_METRIC] = self.metric
return ret
def changed(self):
+55 -7
View File
@@ -144,6 +144,7 @@ class Project(object):
deps=[],
outs=[],
outs_no_cache=[],
metrics_no_cache=[],
fname=Stage.STAGE_FILE,
cwd=os.curdir,
no_exec=False):
@@ -153,6 +154,7 @@ class Project(object):
cwd=cwd,
outs=outs,
outs_no_cache=outs_no_cache,
metrics_no_cache=metrics_no_cache,
deps=deps)
if not no_exec:
stage.run()
@@ -319,6 +321,10 @@ class Project(object):
def _read_metric(self, path, json_path=None, tsv_path=None, htsv_path=None):
ret = None
if not os.path.exists(path):
return ret
try:
with open(path, 'r') as fd:
if json_path:
@@ -330,24 +336,66 @@ class Project(object):
else:
ret = fd.read()
except Exception as exc:
self.logger.error('Unable to read metric in \'{}\''.format(path), exc)
self.logger.debug('Unable to read metric in \'{}\''.format(path), exc)
return ret
def metrics(self, path, json_path=None, tsv_path=None, htsv_path=None):
def metrics_show(self, path=None, json_path=None, tsv_path=None, htsv_path=None, all_branches=False):
res = {}
saved = self.scm.active_branch()
for branch in self.scm.list_branches():
branches = self.scm.list_branches() if all_branches else [saved]
for branch in branches:
self.scm.checkout(branch)
self.checkout()
res[branch] = self._read_metric(path,
json_path=json_path,
tsv_path=tsv_path,
htsv_path=htsv_path)
metrics = filter(lambda o: o.metric, self.outs())
fnames = [path] if path else map(lambda o: o.path, metrics)
for fname in fnames:
rel = os.path.relpath(fname)
metric = self._read_metric(fname,
json_path=json_path,
tsv_path=tsv_path,
htsv_path=htsv_path)
if not metric:
continue
res[branch] = {}
res[branch][rel] = metric
self.scm.checkout(saved)
self.checkout()
for branch, val in res.items():
self.logger.info('{}:'.format(branch))
for fname, metric in val.items():
self.logger.info('\t{}: {}'.format(fname, metric))
return res
def _metrics_modify(self, path, val):
apath = os.path.abspath(path)
for stage in self.stages():
for out in stage.outs:
if apath != out.path:
continue
if out.path_info['scheme'] != 'local':
msg = 'Output \'{}\' scheme \'{}\' is not supported for metrics'
raise DvcException(msg.format(out.path, out.path_info['scheme']))
if out.use_cache:
msg = 'Cached output \'{}\' is not supported for metrics'
raise DvcException(msg.format(out.rel_path))
out.metric = val
stage.dump()
def metrics_add(self, path):
self._metrics_modify(path, True)
def metrics_remove(self, path):
self._metrics_modify(path, False)
def graph(self):
G = nx.DiGraph()
stages = self.stages()
+2
View File
@@ -180,6 +180,7 @@ class Stage(object):
deps=[],
outs=[],
outs_no_cache=[],
metrics_no_cache=[],
fname=None,
cwd=os.curdir):
cwd = os.path.abspath(cwd)
@@ -192,6 +193,7 @@ class Stage(object):
stage.outs = output.loads_from(stage, outs, use_cache=True)
stage.outs += output.loads_from(stage, outs_no_cache, use_cache=False)
stage.outs += output.loads_from(stage, metrics_no_cache, use_cache=False, metric=True)
stage.deps = dependency.loads_from(stage, deps)
return stage
+24 -28
View File
@@ -32,33 +32,29 @@ class TestMetrics(TestDvc):
self.dvc.scm.checkout('master')
def test(self):
ret = self.dvc.metrics('metric')
self.assertEqual(len(ret), 4)
self.assertTrue(ret['master'] == None)
self.assertTrue(ret['foo'] == 'foo')
self.assertTrue(ret['bar'] == 'bar')
self.assertTrue(ret['baz'] == 'baz')
ret = self.dvc.metrics_show('metric', all_branches=True)
self.assertEqual(len(ret), 3)
self.assertTrue(ret['foo']['metric'] == 'foo')
self.assertTrue(ret['bar']['metric'] == 'bar')
self.assertTrue(ret['baz']['metric'] == 'baz')
ret = self.dvc.metrics('metric_json', json_path='branch')
self.assertEqual(len(ret), 4)
self.assertTrue(ret['master'] == None)
self.assertTrue(ret['foo'] == ['foo'])
self.assertTrue(ret['bar'] == ['bar'])
self.assertTrue(ret['baz'] == ['baz'])
ret = self.dvc.metrics_show('metric_json', json_path='branch', all_branches=True)
self.assertEqual(len(ret), 3)
self.assertTrue(ret['foo']['metric_json'] == ['foo'])
self.assertTrue(ret['bar']['metric_json'] == ['bar'])
self.assertTrue(ret['baz']['metric_json'] == ['baz'])
ret = self.dvc.metrics('metric_tsv', tsv_path='0,0')
self.assertEqual(len(ret), 4)
self.assertTrue(ret['master'] == None)
self.assertTrue(ret['foo'] == ['foo'])
self.assertTrue(ret['bar'] == ['bar'])
self.assertTrue(ret['baz'] == ['baz'])
ret = self.dvc.metrics_show('metric_tsv', tsv_path='0,0', all_branches=True)
self.assertEqual(len(ret), 3)
self.assertTrue(ret['foo']['metric_tsv'] == ['foo'])
self.assertTrue(ret['bar']['metric_tsv'] == ['bar'])
self.assertTrue(ret['baz']['metric_tsv'] == ['baz'])
ret = self.dvc.metrics('metric_htsv', htsv_path='branch,0')
self.assertEqual(len(ret), 4)
self.assertTrue(ret['master'] == None)
self.assertTrue(ret['foo'] == ['foo'])
self.assertTrue(ret['bar'] == ['bar'])
self.assertTrue(ret['baz'] == ['baz'])
ret = self.dvc.metrics_show('metric_htsv', htsv_path='branch,0', all_branches=True)
self.assertEqual(len(ret), 3)
self.assertTrue(ret['foo']['metric_htsv'] == ['foo'])
self.assertTrue(ret['bar']['metric_htsv'] == ['bar'])
self.assertTrue(ret['baz']['metric_htsv'] == ['baz'])
class TestMetricsCLI(TestMetrics):
@@ -67,14 +63,14 @@ class TestMetricsCLI(TestMetrics):
if os.name == 'nt':
return
#FIXME check output
ret = main(['metrics', 'metric', '-v'])
ret = main(['metrics', 'show', '--all-branches', 'metric', '-v'])
self.assertEqual(ret, 0)
ret = main(['metrics', 'metric_json', '--json-path', 'branch'])
ret = main(['metrics', 'show', '--all-branches', 'metric_json', '--json-path', 'branch'])
self.assertEqual(ret, 0)
ret = main(['metrics', 'metric_tsv', '--tsv-path', '0,0'])
ret = main(['metrics', 'show', '--all-branches', 'metric_tsv', '--tsv-path', '0,0'])
self.assertEqual(ret, 0)
ret = main(['metrics', 'metric_htsv', '--htsv-path', 'branch,0'])
ret = main(['metrics', 'show', '--all-branches', 'metric_htsv', '--htsv-path', 'branch,0'])
self.assertEqual(ret, 0)
+7 -4
View File
@@ -76,14 +76,17 @@ class TestCmdRun(TestDvc):
outs = [fname, 'dummy']
dvcfile = os.path.basename(fname) + Stage.STAGE_FILE_SUFFIX
ret = CmdRun.stage_file_name(None, [], [])
ret = CmdRun.stage_file_name(None, [], [], [])
self.assertEqual(ret, Stage.STAGE_FILE)
ret = CmdRun.stage_file_name(None, [], outs)
ret = CmdRun.stage_file_name(None, [], outs, [])
self.assertEqual(ret, dvcfile)
ret = CmdRun.stage_file_name(None, outs, [])
ret = CmdRun.stage_file_name(None, outs, [], [])
self.assertEqual(ret, dvcfile)
ret = CmdRun.stage_file_name(fname, [], [])
ret = CmdRun.stage_file_name(None, [], [], outs)
self.assertEqual(ret, dvcfile)
ret = CmdRun.stage_file_name(fname, [], [], [])
self.assertEqual(ret, fname)