lib.py 21.3 KB
Newer Older
J
Jeff Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2017 VisualDL Authors. All Rights Reserve.
#
# 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.
# =======================================================================
走神的阿圆's avatar
走神的阿圆 已提交
15
import csv
C
chenjian 已提交
16
import io
走神的阿圆's avatar
走神的阿圆 已提交
17
import math
C
chenjian 已提交
18 19 20 21 22
import os
import sys
import time
from functools import partial  # noqa: F401

S
superjom 已提交
23
import numpy as np
C
chenjian 已提交
24 25

from visualdl.component import components
走神的阿圆's avatar
走神的阿圆 已提交
26
from visualdl.io import bfile
C
chenjian 已提交
27
from visualdl.server.log import logger
走神的阿圆's avatar
走神的阿圆 已提交
28 29
from visualdl.utils.importance import calc_all_hyper_param_importance
from visualdl.utils.list_util import duplicate_removal
C
chenjian 已提交
30 31
from visualdl.utils.string_util import decode_tag
from visualdl.utils.string_util import encode_tag
S
superjom 已提交
32

走神的阿圆's avatar
走神的阿圆 已提交
33 34
MODIFY_PREFIX = {}
MODIFIED_RUNS = []
走神的阿圆's avatar
走神的阿圆 已提交
35 36
EMBEDDING_NAME = {}
embedding_names = []
走神的阿圆's avatar
走神的阿圆 已提交
37 38


走神的阿圆's avatar
走神的阿圆 已提交
39 40 41 42
def s2ms(timestamp):
    return timestamp * 1000 if timestamp < 2000000000 else timestamp


走神的阿圆's avatar
走神的阿圆 已提交
43 44 45 46 47 48
def transfer_abnomal_scalar_value(scalar_value):
    if math.isnan(scalar_value) or math.isinf(scalar_value):
        scalar_value = str(scalar_value)
    return scalar_value


49
def get_components(log_reader):
50 51
    components = log_reader.components(update=True)
    return list(components)
S
superjom 已提交
52

S
superjom 已提交
53

54
def get_runs(log_reader):
走神的阿圆's avatar
走神的阿圆 已提交
55 56 57 58 59 60 61
    runs = []
    for item in log_reader.runs():
        if item in log_reader.tags2name:
            runs.append(log_reader.tags2name[item])
        else:
            runs.append(item)
    return runs
62 63


C
chenjian 已提交
64 65 66 67 68 69 70 71 72 73
def get_graph_runs(graph_reader):
    runs = []
    for item in graph_reader.runs():
        if item in graph_reader.runs2displayname:
            runs.append(graph_reader.runs2displayname[item])
        else:
            runs.append(item)
    return runs


74 75
def get_tags(log_reader):
    return log_reader.tags()
S
superjom 已提交
76 77


78 79 80 81 82 83 84 85 86
def get_logs(log_reader, component):
    all_tag = log_reader.data_manager.get_reservoir(component).keys
    tags = {}
    for item in all_tag:
        index = item.rfind('/')
        run = item[0:index]
        tag = encode_tag(item[index + 1:])
        if run in tags.keys():
            tags[run].append(tag)
87
        else:
88
            tags[run] = [tag]
走神的阿圆's avatar
走神的阿圆 已提交
89 90 91
        if run not in log_reader.tags2name.keys():
            log_reader.tags2name[run] = run
            log_reader.name2tags[run] = run
走神的阿圆's avatar
走神的阿圆 已提交
92 93 94 95 96 97 98
    fake_tags = {}
    for key, value in tags.items():
        if key in log_reader.tags2name:
            fake_tags[log_reader.tags2name[key]] = value
        else:
            fake_tags[key] = value

走神的阿圆's avatar
走神的阿圆 已提交
99 100 101 102 103
    run2tag = {'runs': [], 'tags': []}
    for run, tags in fake_tags.items():
        run2tag['runs'].append(run)
        run2tag['tags'].append(tags)

走神的阿圆's avatar
走神的阿圆 已提交
104 105 106 107 108 109 110 111 112 113 114 115
    run_prefix = os.getenv('VISUALDL_RUN_PREFIX')
    global MODIFY_PREFIX, MODIFIED_RUNS
    if component not in MODIFY_PREFIX:
        MODIFY_PREFIX.update({component: False})
    if run_prefix and not MODIFY_PREFIX[component]:
        MODIFY_PREFIX[component] = True
        temp_name2tags = log_reader.name2tags.copy()
        for key, value in temp_name2tags.items():
            if key in MODIFIED_RUNS:
                continue
            index = key.find(run_prefix)
            if index != -1:
C
chenjian 已提交
116
                temp_key = key[index + len(run_prefix):]
走神的阿圆's avatar
走神的阿圆 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129

                log_reader.name2tags.pop(key)
                log_reader.name2tags.update({temp_key: value})

                log_reader.tags2name.pop(value)
                log_reader.tags2name.update({value: temp_key})

                run2tag['runs'][run2tag['runs'].index(key)] = temp_key
            else:
                temp_key = key

            MODIFIED_RUNS.append(temp_key)

走神的阿圆's avatar
走神的阿圆 已提交
130
    return run2tag
131 132


走神的阿圆's avatar
走神的阿圆 已提交
133 134
for name in components.keys():
    exec("get_%s_tags=partial(get_logs, component='%s')" % (name, name))
135 136


走神的阿圆's avatar
走神的阿圆 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
def get_hparam_data(log_reader, type='tsv'):
    result = get_hparam_list(log_reader)
    delimeter = '\t' if 'tsv' == type else ','
    header = ['Trial ID']
    hparams_header = []
    metrics_header = []
    for item in result:
        hparams_header += item['hparams'].keys()
        metrics_header += item['metrics'].keys()
    name_set = set()
    h_header = []
    for hparam in hparams_header:
        if hparam in name_set:
            continue
        name_set.add(hparam)
        h_header.append(hparam)
    name_set = set()
    m_header = []
    for metric in metrics_header:
        if metric in name_set:
            continue
        name_set.add(metric)
        m_header.append(metric)
    trans_result = []
    for item in result:
        temp = {'Trial ID': item.get('name', '')}
        temp.update(item.get('hparams', {}))
        temp.update(item.get('metrics', {}))
        trans_result.append(temp)
    header = header + h_header + m_header
    with io.StringIO() as fp:
        csv_writer = csv.writer(fp, delimiter=delimeter)
        csv_writer.writerow(header)
        for item in trans_result:
            row = []
            for col_name in header:
                row.append(item.get(col_name, ''))
            csv_writer.writerow(row)
        result = fp.getvalue()
        return result


def get_hparam_importance(log_reader):
    indicator = get_hparam_indicator(log_reader)
C
chenjian 已提交
181 182 183 184 185 186
    hparams = [
        item for item in indicator['hparams'] if (item['type'] != 'string')
    ]
    metrics = [
        item for item in indicator['metrics'] if (item['type'] != 'string')
    ]
走神的阿圆's avatar
走神的阿圆 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

    result = calc_all_hyper_param_importance(hparams, metrics)

    return result


# flake8: noqa: C901
def get_hparam_indicator(log_reader):
    run2tag = get_logs(log_reader, 'hyper_parameters')
    runs = run2tag['runs']
    hparams = {}
    metrics = {}
    records_list = []
    for run in runs:
        run = log_reader.name2tags[run] if run in log_reader.name2tags else run
        log_reader.load_new_data()
C
chenjian 已提交
203 204
        records = log_reader.data_manager.get_reservoir(
            "hyper_parameters").get_items(run, decode_tag('hparam'))
走神的阿圆's avatar
走神的阿圆 已提交
205 206 207 208 209 210 211 212
        records_list.append([records, run])
    records_list.sort(key=lambda x: x[0][0].timestamp)
    runs = [run for r, run in records_list]
    for records, run in records_list:
        for hparamInfo in records[0].hparam.hparamInfos:
            type = hparamInfo.WhichOneof("type")
            if "float_value" == type:
                if hparamInfo.name not in hparams.keys():
C
chenjian 已提交
213 214 215 216 217 218 219 220 221
                    hparams[hparamInfo.name] = {
                        'name': hparamInfo.name,
                        'type': 'continuous',
                        'values': [hparamInfo.float_value]
                    }
                elif hparamInfo.float_value not in hparams[
                        hparamInfo.name]['values']:
                    hparams[hparamInfo.name]['values'].append(
                        hparamInfo.float_value)
走神的阿圆's avatar
走神的阿圆 已提交
222 223
            elif "string_value" == type:
                if hparamInfo.name not in hparams.keys():
C
chenjian 已提交
224 225 226 227 228 229 230 231 232
                    hparams[hparamInfo.name] = {
                        'name': hparamInfo.name,
                        'type': 'string',
                        'values': [hparamInfo.string_value]
                    }
                elif hparamInfo.string_value not in hparams[
                        hparamInfo.name]['values']:
                    hparams[hparamInfo.name]['values'].append(
                        hparamInfo.string_value)
走神的阿圆's avatar
走神的阿圆 已提交
233 234
            elif "int_value" == type:
                if hparamInfo.name not in hparams.keys():
C
chenjian 已提交
235 236 237 238 239 240 241 242 243
                    hparams[hparamInfo.name] = {
                        'name': hparamInfo.name,
                        'type': 'numeric',
                        'values': [hparamInfo.int_value]
                    }
                elif hparamInfo.int_value not in hparams[
                        hparamInfo.name]['values']:
                    hparams[hparamInfo.name]['values'].append(
                        hparamInfo.int_value)
走神的阿圆's avatar
走神的阿圆 已提交
244
            else:
C
chenjian 已提交
245 246
                raise TypeError(
                    "Invalid hparams param value type `%s`." % type)
走神的阿圆's avatar
走神的阿圆 已提交
247 248

        for metricInfo in records[0].hparam.metricInfos:
C
chenjian 已提交
249 250 251 252 253
            metrics[metricInfo.name] = {
                'name': metricInfo.name,
                'type': 'continuous',
                'values': []
            }
走神的阿圆's avatar
走神的阿圆 已提交
254 255
            for run in runs:
                try:
C
chenjian 已提交
256 257 258 259
                    metrics_data = get_hparam_metric(log_reader, run,
                                                     metricInfo.name)
                    metrics[metricInfo.name]['values'].append(
                        metrics_data[-1][-1])
走神的阿圆's avatar
走神的阿圆 已提交
260 261
                    break
                except:
C
chenjian 已提交
262 263 264
                    logger.error(
                        'Missing data of metrics! Please make sure use add_scalar to log metrics data.'
                    )
走神的阿圆's avatar
走神的阿圆 已提交
265 266 267 268 269
            if len(metrics[metricInfo.name]['values']) == 0:
                metrics.pop(metricInfo.name)
            else:
                metrics[metricInfo.name].pop('values')

C
chenjian 已提交
270 271 272 273
    results = {
        'hparams': [value for key, value in hparams.items()],
        'metrics': [value for key, value in metrics.items()]
    }
走神的阿圆's avatar
走神的阿圆 已提交
274 275 276 277 278 279 280 281 282

    return results


def get_hparam_metric(log_reader, run, tag):
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("scalar").get_items(
        run, decode_tag(tag))
C
chenjian 已提交
283 284 285 286
    results = [[
        s2ms(item.timestamp), item.id,
        transfer_abnomal_scalar_value(item.value)
    ] for item in records]
走神的阿圆's avatar
走神的阿圆 已提交
287 288 289 290 291 292 293 294 295 296 297 298
    return results


def get_hparam_list(log_reader):
    run2tag = get_logs(log_reader, 'hyper_parameters')
    runs = run2tag['runs']
    results = []

    records_list = []
    for run in runs:
        run = log_reader.name2tags[run] if run in log_reader.name2tags else run
        log_reader.load_new_data()
C
chenjian 已提交
299 300
        records = log_reader.data_manager.get_reservoir(
            "hyper_parameters").get_items(run, decode_tag('hparam'))
走神的阿圆's avatar
走神的阿圆 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313
        records_list.append([records, run])
    records_list.sort(key=lambda x: x[0][0].timestamp)
    for records, run in records_list:
        hparams = {}
        for hparamInfo in records[0].hparam.hparamInfos:
            hparam_type = hparamInfo.WhichOneof("type")
            if "float_value" == hparam_type:
                hparams[hparamInfo.name] = hparamInfo.float_value
            elif "string_value" == hparam_type:
                hparams[hparamInfo.name] = hparamInfo.string_value
            elif "int_value" == hparam_type:
                hparams[hparamInfo.name] = hparamInfo.int_value
            else:
C
chenjian 已提交
314 315
                raise TypeError(
                    "Invalid hparams param value type `%s`." % hparam_type)
走神的阿圆's avatar
走神的阿圆 已提交
316 317 318 319

        metrics = {}
        for metricInfo in records[0].hparam.metricInfos:
            try:
C
chenjian 已提交
320 321
                metrics_data = get_hparam_metric(log_reader, run,
                                                 metricInfo.name)
走神的阿圆's avatar
走神的阿圆 已提交
322 323
                metrics[metricInfo.name] = metrics_data[-1][-1]
            except:
C
chenjian 已提交
324 325 326
                logger.error(
                    'Missing data of metrics! Please make sure use add_scalar to log metrics data.'
                )
走神的阿圆's avatar
走神的阿圆 已提交
327 328
                metrics[metricInfo.name] = None

C
chenjian 已提交
329
        results.append({'name': run, 'hparams': hparams, 'metrics': metrics})
走神的阿圆's avatar
走神的阿圆 已提交
330 331 332
    return results


333
def get_scalar(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
334
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
335 336 337
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("scalar").get_items(
        run, decode_tag(tag))
C
chenjian 已提交
338 339 340 341
    results = [[
        s2ms(item.timestamp), item.id,
        transfer_abnomal_scalar_value(item.value)
    ] for item in records]
342
    return results
343 344


走神的阿圆's avatar
走神的阿圆 已提交
345
def get_scalar_data(log_reader, run, tag, type='tsv'):
走神的阿圆's avatar
走神的阿圆 已提交
346 347
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    log_reader.load_new_data()
348
    result = log_reader.get_log_data('scalar', run, decode_tag(tag))
走神的阿圆's avatar
走神的阿圆 已提交
349
    delimeter = '\t' if 'tsv' == type else ','
走神的阿圆's avatar
走神的阿圆 已提交
350
    with io.StringIO() as fp:
走神的阿圆's avatar
走神的阿圆 已提交
351
        csv_writer = csv.writer(fp, delimiter=delimeter)
走神的阿圆's avatar
走神的阿圆 已提交
352 353 354 355 356 357
        csv_writer.writerow(['id', 'tag', 'timestamp', 'value'])
        csv_writer.writerows(result)
        result = fp.getvalue()
        return result


358
def get_image_tag_steps(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
359
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
360 361 362 363 364
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("image").get_items(
        run, decode_tag(tag))
    result = [{
        "step": item.id,
走神的阿圆's avatar
走神的阿圆 已提交
365
        "wallTime": s2ms(item.timestamp)
366 367
    } for item in records]
    return result
368 369


370
def get_individual_image(log_reader, run, tag, step_index):
走神的阿圆's avatar
走神的阿圆 已提交
371
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
372 373 374 375
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("image").get_items(
        run, decode_tag(tag))
    return records[step_index].image.encoded_image_string
376 377


走神的阿圆's avatar
走神的阿圆 已提交
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
def get_text_tag_steps(log_reader, run, tag):
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("text").get_items(
        run, decode_tag(tag))
    result = [{
        "step": item.id,
        "wallTime": s2ms(item.timestamp)
    } for item in records]
    return result


def get_individual_text(log_reader, run, tag, step_index):
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("text").get_items(
        run, decode_tag(tag))
    return records[step_index].text.encoded_text_string


398
def get_audio_tag_steps(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
399
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
400 401 402 403 404
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("audio").get_items(
        run, decode_tag(tag))
    result = [{
        "step": item.id,
走神的阿圆's avatar
走神的阿圆 已提交
405
        "wallTime": s2ms(item.timestamp)
406 407
    } for item in records]
    return result
408 409


410
def get_individual_audio(log_reader, run, tag, step_index):
走神的阿圆's avatar
走神的阿圆 已提交
411
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
412 413 414
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("audio").get_items(
        run, decode_tag(tag))
P
Peter Pan 已提交
415
    result = records[step_index].audio.encoded_audio_string
416
    return result
417 418


走神的阿圆's avatar
走神的阿圆 已提交
419
def get_pr_curve(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
420
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
走神的阿圆's avatar
走神的阿圆 已提交
421 422 423 424 425 426 427 428
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("pr_curve").get_items(
        run, decode_tag(tag))
    results = []
    for item in records:
        pr_curve = item.pr_curve
        length = len(pr_curve.precision)
        num_thresholds = [float(v) / length for v in range(1, length + 1)]
C
chenjian 已提交
429 430 431 432 433 434 435 436 437
        results.append([
            s2ms(item.timestamp), item.id,
            list(pr_curve.precision),
            list(pr_curve.recall),
            list(pr_curve.TP),
            list(pr_curve.FP),
            list(pr_curve.TN),
            list(pr_curve.FN), num_thresholds
        ])
走神的阿圆's avatar
走神的阿圆 已提交
438
    return results
P
Peter Pan 已提交
439 440


P
Peter Pan 已提交
441 442 443 444 445 446 447 448 449 450
def get_roc_curve(log_reader, run, tag):
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("roc_curve").get_items(
        run, decode_tag(tag))
    results = []
    for item in records:
        roc_curve = item.roc_curve
        length = len(roc_curve.tpr)
        num_thresholds = [float(v) / length for v in range(1, length + 1)]
C
chenjian 已提交
451 452 453 454 455 456 457 458 459
        results.append([
            s2ms(item.timestamp), item.id,
            list(roc_curve.tpr),
            list(roc_curve.fpr),
            list(roc_curve.TP),
            list(roc_curve.FP),
            list(roc_curve.TN),
            list(roc_curve.FN), num_thresholds
        ])
P
Peter Pan 已提交
460
    return results
走神的阿圆's avatar
走神的阿圆 已提交
461 462 463


def get_pr_curve_step(log_reader, run, tag=None):
走神的阿圆's avatar
走神的阿圆 已提交
464
    fake_run = run
走神的阿圆's avatar
走神的阿圆 已提交
465
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
P
Peter Pan 已提交
466
    run2tag = get_pr_curve_tags(log_reader)  # noqa: F821
走神的阿圆's avatar
走神的阿圆 已提交
467
    tag = run2tag['tags'][run2tag['runs'].index(fake_run)][0]
走神的阿圆's avatar
走神的阿圆 已提交
468 469 470
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("pr_curve").get_items(
        run, decode_tag(tag))
走神的阿圆's avatar
走神的阿圆 已提交
471
    results = [[s2ms(item.timestamp), item.id] for item in records]
走神的阿圆's avatar
走神的阿圆 已提交
472 473 474
    return results


P
Peter Pan 已提交
475 476 477
def get_roc_curve_step(log_reader, run, tag=None):
    fake_run = run
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
P
Peter Pan 已提交
478
    run2tag = get_roc_curve_tags(log_reader)  # noqa: F821
P
Peter Pan 已提交
479 480 481 482 483 484 485
    tag = run2tag['tags'][run2tag['runs'].index(fake_run)][0]
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("roc_curve").get_items(
        run, decode_tag(tag))
    results = [[s2ms(item.timestamp), item.id] for item in records]
    return results

P
Peter Pan 已提交
486

走神的阿圆's avatar
走神的阿圆 已提交
487 488 489 490
def get_embeddings_list(log_reader):
    run2tag = get_logs(log_reader, 'embeddings')

    for run, _tags in zip(run2tag['runs'], run2tag['tags']):
走神的阿圆's avatar
走神的阿圆 已提交
491
        run = log_reader.name2tags[run] if run in log_reader.name2tags else run
走神的阿圆's avatar
走神的阿圆 已提交
492 493 494 495 496
        for tag in _tags:
            name = path = os.path.join(run, tag)
            if name in EMBEDDING_NAME:
                return embedding_names
            EMBEDDING_NAME.update({name: {'run': run, 'tag': tag}})
C
chenjian 已提交
497 498
            records = log_reader.data_manager.get_reservoir(
                "embeddings").get_items(run, decode_tag(tag))
走神的阿圆's avatar
走神的阿圆 已提交
499 500 501
            row_len = len(records[0].embeddings.embeddings)
            col_len = len(records[0].embeddings.embeddings[0].vectors)
            shape = [row_len, col_len]
C
chenjian 已提交
502 503 504 505 506
            embedding_names.append({
                'name': name,
                'shape': shape,
                'path': path
            })
走神的阿圆's avatar
走神的阿圆 已提交
507 508 509 510 511 512 513 514 515 516 517
    return embedding_names


def get_embedding_labels(log_reader, name):
    run = EMBEDDING_NAME[name]['run']
    tag = EMBEDDING_NAME[name]['tag']
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("embeddings").get_items(
        run, decode_tag(tag))
    labels = []
    for item in records[0].embeddings.embeddings:
518 519 520 521 522
        labels.append(item.label)

    label_meta = records[0].embeddings.label_meta
    if label_meta:
        labels = [label_meta] + labels
走神的阿圆's avatar
走神的阿圆 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

    with io.StringIO() as fp:
        csv_writer = csv.writer(fp, delimiter='\t')
        csv_writer.writerows(labels)
        labels = fp.getvalue()

    # labels = "\n".join(str(i) for i in labels)
    return labels


def get_embedding_tensors(log_reader, name):
    run = EMBEDDING_NAME[name]['run']
    tag = EMBEDDING_NAME[name]['tag']
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("embeddings").get_items(
        run, decode_tag(tag))
    vectors = []
    for item in records[0].embeddings.embeddings:
        vectors.append(item.vectors)
    vectors = np.array(vectors).flatten().astype(np.float32).tobytes()
    return vectors


546
def get_histogram(log_reader, run, tag):
走神的阿圆's avatar
走神的阿圆 已提交
547
    run = log_reader.name2tags[run] if run in log_reader.name2tags else run
548 549 550 551 552 553 554 555 556 557 558
    log_reader.load_new_data()
    records = log_reader.data_manager.get_reservoir("histogram").get_items(
        run, decode_tag(tag))

    results = []
    for item in records:
        histogram = item.histogram
        hist = histogram.hist
        bin_edges = histogram.bin_edges
        histogram_data = []
        for index in range(len(hist)):
C
chenjian 已提交
559 560
            histogram_data.append(
                [bin_edges[index], bin_edges[index + 1], hist[index]])
走神的阿圆's avatar
走神的阿圆 已提交
561
        results.append([s2ms(item.timestamp), item.id, histogram_data])
562 563 564 565

    return results


C
chenjian 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
def get_graph(graph_reader,
              run,
              nodeid=None,
              expand=False,
              keep_state=False,
              expand_all=False,
              refresh=True):
    result = ""
    run = graph_reader.displayname2runs[
        run] if run in graph_reader.displayname2runs else run
    if nodeid is not None:
        refresh = False
    result = graph_reader.get_graph(run, nodeid, expand, keep_state,
                                    expand_all, refresh)
    return result


def get_graph_search(graph_reader, run, nodeid, keep_state=False,
                     is_node=True):
    result = ""
    run = graph_reader.displayname2runs[
        run] if run in graph_reader.displayname2runs else run
    result = graph_reader.search_graph_node(
        run, nodeid, keep_state=keep_state, is_node=is_node)
    return result


def get_graph_all_nodes(graph_reader, run):
    result = ""
    run = graph_reader.displayname2runs[
        run] if run in graph_reader.displayname2runs else run
    result = graph_reader.get_all_nodes(run)
598 599 600
    return result


601
def retry(ntimes, function, time2sleep, *args, **kwargs):
602
    """
603 604
    try to execute `function` `ntimes`, if exception catched, the thread will
    sleep `time2sleep` seconds.
605
    """
O
Oraoto 已提交
606
    for i in range(ntimes):
607 608
        try:
            return function(*args, **kwargs)
T
Thuan Nguyen 已提交
609
        except Exception:
C
chenjian 已提交
610
            if i < ntimes - 1:
611 612 613 614 615 616
                error_info = '\n'.join(map(str, sys.exc_info()))
                logger.error("Unexpected error: %s" % error_info)
                time.sleep(time2sleep)
            else:
                import traceback
                traceback.print_exc()
617

T
Thuan Nguyen 已提交
618

619 620 621 622 623 624 625 626 627
def cache_get(cache):
    def _handler(key, func, *args, **kwargs):
        data = cache.get(key)
        if data is None:
            logger.warning('update cache %s' % key)
            data = func(*args, **kwargs)
            cache.set(key, data)
            return data
        return data
T
Thuan Nguyen 已提交
628

629
    return _handler