Create a Metric using the LabelKeys and LabelValues.
777016
@VisibleForTesting
  static Metric createMetric(
      io.opencensus.metrics.export.MetricDescriptor metricDescriptor,
      List<LabelValue> labelValues,
      String domain,
      Map<LabelKey, LabelValue> constantLabels) {
    Metric.Builder builder = Metric.newBuilder();
    builder.setType(generateType(metricDescriptor.getName(), domain));
    Map<String, String> stringTagMap = Maps.newHashMap();
    List<LabelKey> labelKeys = metricDescriptor.getLabelKeys();
    for (int i = 0; i < labelValues.size(); i++) {
      String value = labelValues.get(i).getValue();
      if (value == null) {
        continue;
      }
      stringTagMap.put(labelKeys.get(i).getKey(), value);
    }
    for (Map.Entry<LabelKey, LabelValue> constantLabel : constantLabels.entrySet()) {
      String constantLabelKey = constantLabel.getKey().getKey();
      String constantLabelValue = constantLabel.getValue().getValue();
      constantLabelValue = constantLabelValue == null ? "" : constantLabelValue;
      stringTagMap.put(constantLabelKey, constantLabelValue);
    }
    builder.putAllLabels(stringTagMap);
    return builder.build();
  }
1355249
def new_metric(name, class_, *args, **kwargs):
    

    with LOCK:
        try:
            item = REGISTRY[name]
        except KeyError:
            item = REGISTRY[name] = class_(*args, **kwargs)
            return item

    raise DuplicateMetricError("Metric {} already exists of type {}".format(name, type(item).__name__))
182435
def build_message(self, metric, value, timestamp, tags={}):
        """"""
        if not metric or metric.split(None, 1)[0] != metric:
            raise ValueError('"metric" must not have whitespace in it')
        if not isinstance(value, (int, float)):
            raise TypeError('"value" must be an int or a float, not a {}'.format(
                type(value).__name__))

        tags_suffix = ''.join(';{}={}'.format(x[0], x[1]) for x in sorted(tags.items()))

        message = u'{}{}{} {} {}\n'.format(
            self.prefix + '.' if self.prefix else '',
            metric,
            tags_suffix,
            value,
            int(round(timestamp))
        )
        message = message.encode('utf-8')
        return message
28403
def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict):
        """"""
        # Check whether or not it's time for validation as well
        self.log_count += 1
        log_valid = (
            valid_loader is not None
            and self.valid_every_X
            and not (self.log_count % self.valid_every_X)
        )

        metrics_dict = {}

        # Calculate custom metrics
        if self.config["log_train_metrics_func"] is not None:
            func = self.config["log_train_metrics_func"]
            func_list = func if isinstance(func, list) else [func]
            for func in func_list:
                metrics_dict = self._calculate_custom_metrics(
                    model, train_loader, func, metrics_dict, split="train"
                )
        if self.config["log_valid_metrics_func"] is not None and log_valid:
            func = self.config["log_valid_metrics_func"]
            func_list = func if isinstance(func, list) else [func]
            for func in func_list:
                metrics_dict = self._calculate_custom_metrics(
                    model, valid_loader, func, metrics_dict, split="valid"
                )

        # Calculate standard metrics
        metrics_dict = self._calculate_standard_metrics(
            model, train_loader, self.log_train_metrics, metrics_dict, "train"
        )

        if log_valid:
            metrics_dict = self._calculate_standard_metrics(
                model, valid_loader, self.log_valid_metrics, metrics_dict, "valid"
            )

        return metrics_dict
1282554
def draw_plot(self, metrics, labels=None, ylabel=""):
        
        metrics = metrics if isinstance(metrics, list) else [metrics]
        # Loop through metrics
        title = ""
        for i, m in enumerate(metrics):
            label = labels[i] if labels else m.name
            # TODO: use a standard formating function for values
            title += ("   " if title else "") + "{}: {}".format(label, m.data[-1])
            self.ax.plot(m.formatted_steps, m.data, label=label)
        self.ax.set_title(title)
        self.ax.set_ylabel(ylabel)
        self.ax.legend()
        self.ax.set_xlabel("Steps")
        self.ax.xaxis.set_major_locator(plt.AutoLocator())
1030838
def update_metric(self, metric, labels, pre_sliced=False):
        """"""
        for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)):
            if not pre_sliced:
                labels_slice = [label[islice] for label in labels]
            else:
                labels_slice = labels[current_exec]
            metric.update(labels_slice, texec.outputs)
1018710
def _eval_metric(input_, topk, correct_predictions, examples, phase):
  """"""
  my_parameters = {}
  if phase in (Phase.test, Phase.infer):
    dtype = tf.float32
    # Create the variables using tf.Variable because we don't want to share.
    count = tf.Variable(tf.constant(0, dtype=dtype),
                        name='count_%d' % topk,
                        collections=[bookkeeper.GraphKeys.TEST_VARIABLES],
                        trainable=False)
    correct = tf.Variable(tf.constant(0, dtype=dtype),
                          name='correct_%d' % topk,
                          collections=[bookkeeper.GraphKeys.TEST_VARIABLES],
                          trainable=False)
    my_parameters['count'] = count
    my_parameters['correct'] = correct
    with input_.g.device(count.device):
      examples = tf.assign_add(count, examples)
    with input_.g.device(correct.device):
      correct_predictions = tf.assign_add(correct, correct_predictions)
  return correct_predictions, examples, my_parameters
1230826
def set_metric(slug, value, category=None, expire=None, date=None):
    """"""
    get_r().set_metric(slug, value, category=category, expire=expire, date=date)
473399
def gauge(self, key, gauge=None, default=float("nan"), **dims):
        """"""
        return super(MetricsRegistry, self).gauge(
            self.metadata.register(key, **dims), gauge=gauge, default=default)
1344797
def do_metric_create_raw(mc, args):
    ''''''
    try:
        mc.metrics.create(**args.jsonbody)
    except (osc_exc.ClientException, k_exc.HttpError) as he:
        raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
    else:
        print('Successfully created metric')
137086
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'event_type' in _dict:
            args['event_type'] = _dict.get('event_type')
        if 'results' in _dict:
            args['results'] = [
                MetricTokenAggregationResult._from_dict(x)
                for x in (_dict.get('results'))
            ]
        return cls(**args)
1158713
def mmap_key(metric_name, name, labelnames, labelvalues):
    """"""
    # ensure labels are in consistent order for identity
    labels = dict(zip(labelnames, labelvalues))
    return json.dumps([metric_name, name, labels], sort_keys=True)
515446
public static MetricReader create(Options options) {
    checkNotNull(options, "options");
    return new MetricReader(
        checkNotNull(options.getMetricProducerManager(), "metricProducerManager"),
        checkNotNull(options.getSpanName(), "spanName"));
  }
939103
def CreateGaugeMetadata(metric_name,
                        value_type,
                        fields=None,
                        docstring=None,
                        units=None):
  """"""
  return rdf_stats.MetricMetadata(
      varname=metric_name,
      metric_type=rdf_stats.MetricMetadata.MetricType.GAUGE,
      value_type=MetricValueTypeFromPythonType(value_type),
      fields_defs=FieldDefinitionProtosFromTuples(fields or []),
      docstring=docstring,
      units=units)
288106
def make_label(loss, key):
    ''''''
    algo, rate, mu, half, reg = key
    slots, args = ['{:.3f}', '{}', 'm={:.3f}'], [loss, algo, mu]
    if algo in 'SGD NAG RMSProp Adam ESGD'.split():
        slots.append('lr={:.2e}')
        args.append(rate)
    if algo in 'RMSProp ADADELTA ESGD'.split():
        slots.append('rmsh={}')
        args.append(half)
        slots.append('rmsr={:.2e}')
        args.append(reg)
    return ' '.join(slots).format(*args)
75816
protected void processOneMetric(List<String> resultStrings, Server server, Result result, Object value, String addTagName,
									String addTagValue) {
		String metricName = this.metricNameStrategy.formatName(result);

		//
		// Skip any non-numeric values since OpenTSDB only supports numeric metrics.
		//
		if (isNumeric(value)) {
			StringBuilder resultString = new StringBuilder();

			formatResultString(resultString, metricName, result.getEpoch() / 1000L, value);
			addTags(resultString, server);

			if (addTagName != null) {
				addTag(resultString, addTagName, addTagValue);
			}

			if (!typeNames.isEmpty()) {
				this.addTypeNamesTags(resultString, result);
			}

			resultStrings.add(resultString.toString());
		} else {
			log.debug("Skipping non-numeric value for metric {}; value={}", metricName, value);
		}
	}
813752
private void addMetric(
      List<Metric> metrics,
      String name,
      TagList tags,
      Object value) {
    long now = System.currentTimeMillis();
    if (onlyNumericMetrics) {
      value = asNumber(value);
    }
    if (value != null) {

      TagList newTags = counters.matches(MonitorConfig.builder(name).withTags(tags).build())
          ? getTagListWithAdditionalTag(tags, DataSourceType.COUNTER)
          : getTagListWithAdditionalTag(tags, DataSourceType.GAUGE);
      Metric m = new Metric(name, newTags, now, value);
      metrics.add(m);
    }
  }