Creates a composite EvalMetric given a list of metric names.
174560
def _create_eval_metric_composite(metric_names: List[str]) -> mx.metric.CompositeEvalMetric:
        
        metrics = [EarlyStoppingTrainer._create_eval_metric(metric_name) for metric_name in metric_names]
        return mx.metric.create(metrics)
567167
def _generate_metrics(bam_fname, config_file, ref_file,
                      bait_file, target_file):
    
    with open(config_file) as in_handle:
        config = yaml.safe_load(in_handle)
    broad_runner = broad.runner_from_config(config)
    bam_fname = os.path.abspath(bam_fname)
    path = os.path.dirname(bam_fname)
    out_dir = os.path.join(path, "metrics")
    utils.safe_makedir(out_dir)
    with utils.chdir(out_dir):
        with tx_tmpdir() as tmp_dir:
            cur_bam = os.path.basename(bam_fname)
            if not os.path.exists(cur_bam):
                os.symlink(bam_fname, cur_bam)
            gen_metrics = PicardMetrics(broad_runner, tmp_dir)
            gen_metrics.report(cur_bam, ref_file,
                               _bam_is_paired(bam_fname),
                               bait_file, target_file)
    return out_dir
432543
private static Metric createInternal(
      MetricDescriptor metricDescriptor, List<TimeSeries> timeSeriesList) {
    Utils.checkNotNull(metricDescriptor, "metricDescriptor");
    checkTypeMatch(metricDescriptor.getType(), timeSeriesList);
    return new AutoValue_Metric(metricDescriptor, timeSeriesList);
  }
1152073
def CreateCounterMetadata(metric_name, fields=None, docstring=None, units=None):
  """"""
  return rdf_stats.MetricMetadata(
      varname=metric_name,
      metric_type=rdf_stats.MetricMetadata.MetricType.COUNTER,
      value_type=rdf_stats.MetricMetadata.ValueType.INT,
      fields_defs=FieldDefinitionProtosFromTuples(fields or []),
      docstring=docstring,
      units=units)
1265542
def _build_session_metric_values(self, session_name):
    """"""

    # result is a list of api_pb2.MetricValue instances.
    result = []
    metric_infos = self._experiment.metric_infos
    for metric_info in metric_infos:
      metric_name = metric_info.name
      try:
        metric_eval = metrics.last_metric_eval(
            self._context.multiplexer,
            session_name,
            metric_name)
      except KeyError:
        # It's ok if we don't find the metric in the session.
        # We skip it here. For filtering and sorting purposes its value is None.
        continue

      # metric_eval is a 3-tuple of the form [wall_time, step, value]
      result.append(api_pb2.MetricValue(name=metric_name,
                                        wall_time_secs=metric_eval[0],
                                        training_step=metric_eval[1],
                                        value=metric_eval[2]))
    return result
217515
private Response serveOneOrAll(List<water.ModelMetrics> list) {
    JsonArray metricsArray = new JsonArray();

    for (water.ModelMetrics metrics : list) {
      JsonObject metricsJson = metrics.toJSON();
      metricsArray.add(metricsJson);
    }

    JsonObject result = new JsonObject();
    result.add("metrics", metricsArray);
    return Response.done(result);
  }
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__))
1042917
@Override
    public List<Metric> transform(QueryContext queryContext, List<Metric>... listOfList) {
        List<Metric> result = new ArrayList<>();

        for (List<Metric> list : listOfList) {
            for (Metric metric : list) {
                result.add(metric);
            }
        }
        return result;
    }
571217
def convert_multidim_measurements(all_phases):
  """"""
  # Combine actual attachments with attachments we make from multi-dim
  # measurements.
  attachment_names = list(itertools.chain.from_iterable(
      phase.attachments.keys() for phase in all_phases))
  attachment_names.extend(itertools.chain.from_iterable([
      'multidim_' + name for name, meas in phase.measurements.items()
      if meas.dimensions is not None
  ] for phase in all_phases if phase.measurements))
  attachment_name_maker = UniqueNameMaker(attachment_names)

  for phase in all_phases:
    # Process multi-dim measurements into unique attachments.
    for name, measurement in sorted(phase.measurements.items()):
      if measurement.dimensions:
        old_name = name
        name = attachment_name_maker.make_unique('multidim_%s' % name)
        attachment = multidim_measurement_to_attachment(name, measurement)
        phase.attachments[name] = attachment
        phase.measurements.pop(old_name)
  return all_phases
768032
@Override
    public List<Metric> transform(QueryContext context, List<Metric> metrics) {
        if (metrics == null) {
            throw new MissingDataException("The metrics list cannot be null or empty while performing arithmetic transformations.");
        }
        if (metrics.isEmpty()) {
            return metrics;
        }

        Metric result = new Metric(getResultScopeName(), RESULT_METRIC_NAME);
        Map<Long, Double> resultDatapoints = new HashMap<>();
        Iterator<Entry<Long, Double>> it = metrics.get(0).getDatapoints().entrySet().iterator();

        while (it.hasNext()) {
            Entry<Long, Double> entry = it.next();
            List<Double> operands = null;

            try {
                operands = getOperands(entry.getKey(), metrics);
            } catch (MissingDataException mde) {
                continue;
            }
            resultDatapoints.put(entry.getKey(), performOperation(operands));
        }
        result.setDatapoints(resultDatapoints);
        MetricDistiller.setCommonAttributes(metrics, result);

        List<Metric> resultMetrics = new ArrayList<>();

        Collections.addAll(resultMetrics, result);
        return resultMetrics;
    }
465676
def _build_metric_list_to_collect(self, additional_metrics):
        
        metrics_to_collect = {}

        # Defaut metrics
        for default_metrics in itervalues(self.DEFAULT_METRICS):
            metrics_to_collect.update(default_metrics)

        # Additional metrics metrics
        for option in additional_metrics:
            additional_metrics = self.AVAILABLE_METRICS.get(option)
            if not additional_metrics:
                if option in self.DEFAULT_METRICS:
                    self.log.warning(
                        u"`%s` option is deprecated. The corresponding metrics are collected by default.", option
                    )
                else:
                    self.log.warning(
                        u"Failed to extend the list of metrics to collect: unrecognized `%s` option", option
                    )
                continue

            self.log.debug(u"Adding `%s` corresponding metrics to the list of metrics to collect.", option)
            metrics_to_collect.update(additional_metrics)

        return metrics_to_collect
131839
static Map<String, Double> processMetrics(String prefix, Iterable<MetricsInfo> metrics) {
    Map<String, Double> map = new HashMap<>();
    for (MetricsInfo r : metrics) {
      try {
        map.put(prefix + r.getName(), Double.valueOf(r.getValue()));
      } catch (NumberFormatException ne) {
        LOG.log(Level.SEVERE, "Could not parse metric, Name: "
            + r.getName() + " Value: " + r.getValue(), ne);
      }
    }
    return map;
  }
47885
def CreateEventMetadata(metric_name,
                        bins=None,
                        fields=None,
                        docstring=None,
                        units=None):
  """"""
  return rdf_stats.MetricMetadata(
      varname=metric_name,
      bins=bins or [],
      metric_type=rdf_stats.MetricMetadata.MetricType.EVENT,
      value_type=rdf_stats.MetricMetadata.ValueType.DISTRIBUTION,
      fields_defs=FieldDefinitionProtosFromTuples(fields or []),
      docstring=docstring,
      units=units)
284174
@Override
    public List<Metric> transform(QueryContext context, List<Metric> metrics) {
        SystemAssert.requireArgument(metrics != null, "Cannot transform null metric/metrics");

        List<Metric> result = new ArrayList<>(metrics.size());

        for (Metric metric : metrics) {
            Map<Long, Double> sortedDatapoints = new TreeMap<>();
            Double prevSum = 0.0;

            sortedDatapoints.putAll(metric.getDatapoints());
            for (Entry<Long, Double> entry : sortedDatapoints.entrySet()) {
                prevSum += entry.getValue();
                sortedDatapoints.put(entry.getKey(), prevSum);
            }
            metric.setDatapoints(sortedDatapoints);
            result.add(metric);
        }
        return result;
    }
1110230
def text_fd_to_metric_families(fd):
    
    name = None
    allowed_names = []
    eof = False

    seen_metrics = set()

    def build_metric(name, documentation, typ, unit, samples):
        if name in seen_metrics:
            raise ValueError("Duplicate metric: " + name)
        seen_metrics.add(name)
        if typ is None:
            typ = 'unknown'
        if documentation is None:
            documentation = ''
        if unit is None:
            unit = ''
        if unit and not name.endswith("_" + unit):
            raise ValueError("Unit does not match metric name: " + name)
        if unit and typ in ['info', 'stateset']:
            raise ValueError("Units not allowed for this metric type: " + name)
        if typ in ['histogram', 'gaugehistogram']:
            _check_histogram(samples, name)
        metric = Metric(name, documentation, typ, unit)
        # TODO: check labelvalues are valid utf8
        metric.samples = samples
        return metric

    for line in fd:
        if line[-1] == '\n':
            line = line[:-1]

        if eof:
            raise ValueError("Received line after # EOF: " + line)

        if line == '# EOF':
            eof = True
        elif line.startswith('#'):
            parts = line.split(' ', 3)
            if len(parts) < 4:
                raise ValueError("Invalid line: " + line)
            if parts[2] == name and samples:
                raise ValueError("Received metadata after samples: " + line)
            if parts[2] != name:
                if name is not None:
                    yield build_metric(name, documentation, typ, unit, samples)
                # New metric
                name = parts[2]
                unit = None
                typ = None
                documentation = None
                group = None
                seen_groups = set()
                group_timestamp = None
                group_timestamp_samples = set()
                samples = []
                allowed_names = [parts[2]]

            if parts[1] == 'HELP':
                if documentation is not None:
                    raise ValueError("More than one HELP for metric: " + line)
                if len(parts) == 4:
                    documentation = _unescape_help(parts[3])
                elif len(parts) == 3:
                    raise ValueError("Invalid line: " + line)
            elif parts[1] == 'TYPE':
                if typ is not None:
                    raise ValueError("More than one TYPE for metric: " + line)
                typ = parts[3]
                if typ == 'untyped':
                    raise ValueError("Invalid TYPE for metric: " + line)
                allowed_names = {
                    'counter': ['_total', '_created'],
                    'summary': ['_count', '_sum', '', '_created'],
                    'histogram': ['_count', '_sum', '_bucket', '_created'],
                    'gaugehistogram': ['_gcount', '_gsum', '_bucket'],
                    'info': ['_info'],
                }.get(typ, [''])
                allowed_names = [name + n for n in allowed_names]
            elif parts[1] == 'UNIT':
                if unit is not None:
                    raise ValueError("More than one UNIT for metric: " + line)
                unit = parts[3]
            else:
                raise ValueError("Invalid line: " + line)
        else:
            sample = _parse_sample(line)
            if sample.name not in allowed_names:
                if name is not None:
                    yield build_metric(name, documentation, typ, unit, samples)
                # Start an unknown metric.
                name = sample.name
                documentation = None
                unit = None
                typ = 'unknown'
                samples = []
                group = None
                group_timestamp = None
                group_timestamp_samples = set()
                seen_groups = set()
                allowed_names = [sample.name]

            if typ == 'stateset' and name not in sample.labels:
                raise ValueError("Stateset missing label: " + line)
            if (typ in ['histogram', 'gaugehistogram'] and name + '_bucket' == sample.name
                    and (float(sample.labels.get('le', -1)) < 0
                         or sample.labels['le'] != floatToGoString(sample.labels['le']))):
                raise ValueError("Invalid le label: " + line)
            if (typ == 'summary' and name == sample.name
                    and (not (0 <= float(sample.labels.get('quantile', -1)) <= 1)
                         or sample.labels['quantile'] != floatToGoString(sample.labels['quantile']))):
                raise ValueError("Invalid quantile label: " + line)

            g = tuple(sorted(_group_for_sample(sample, name, typ).items()))
            if group is not None and g != group and g in seen_groups:
                raise ValueError("Invalid metric grouping: " + line)
            if group is not None and g == group:
                if (sample.timestamp is None) != (group_timestamp is None):
                    raise ValueError("Mix of timestamp presence within a group: " + line)
                if group_timestamp is not None and group_timestamp > sample.timestamp and typ != 'info':
                    raise ValueError("Timestamps went backwards within a group: " + line)
            else:
                group_timestamp_samples = set()

            series_id = (sample.name, tuple(sorted(sample.labels.items())))
            if sample.timestamp != group_timestamp or series_id not in group_timestamp_samples:
                # Not a duplicate due to timestamp truncation.
                samples.append(sample)
            group_timestamp_samples.add(series_id)

            group = g
            group_timestamp = sample.timestamp
            seen_groups.add(g)

            if typ == 'stateset' and sample.value not in [0, 1]:
                raise ValueError("Stateset samples can only have values zero and one: " + line)
            if typ == 'info' and sample.value != 1:
                raise ValueError("Info samples can only have value one: " + line)
            if typ == 'summary' and name == sample.name and sample.value < 0:
                raise ValueError("Quantile values cannot be negative: " + line)
            if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount', '_gsum'] and math.isnan(
                    sample.value):
                raise ValueError("Counter-like samples cannot be NaN: " + line)
            if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount',
                                           '_gsum'] and sample.value < 0:
                raise ValueError("Counter-like samples cannot be negative: " + line)
            if sample.exemplar and not (
                    typ in ['histogram', 'gaugehistogram']
                    and sample.name.endswith('_bucket')):
                raise ValueError("Invalid line only histogram/gaugehistogram buckets can have exemplars: " + line)

    if name is not None:
        yield build_metric(name, documentation, typ, unit, samples)

    if not eof:
        raise ValueError("Missing # EOF at end")
189529
async def metrics(self, offs, size=None):
        '''
        
        '''
        for i, (indx, item) in enumerate(self._metrics.iter(offs)):

            if size is not None and i >= size:
                return

            yield indx, item
91136
private Metric reduce(List<Metric> metrics) {
		SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");

		/*
		 * if (metrics.isEmpty()) { return new Metric(defaultScope, defaultMetricName); }
		 */
		MetricDistiller distiller = new MetricDistiller();

		distiller.distill(metrics);

		Map<Long, List<Double>> collated = collate(metrics);
		Map<Long, Double> minDatapoints = reduce(collated);
		String newMetricName = distiller.getMetric() == null ? defaultMetricName : distiller.getMetric();
		String newScopeName = distiller.getScope() == null ? defaultScope : distiller.getScope();
		Metric newMetric = new Metric(newScopeName, newMetricName);

		newMetric.setDisplayName(distiller.getDisplayName());
		newMetric.setUnits(distiller.getUnits());
		newMetric.setTags(distiller.getTags());
		newMetric.setDatapoints(minDatapoints);
		return newMetric;
	}