LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mtrace_mean.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_API_TRACE_MTRACE_MEAN_H
6#define LINE_API_TRACE_MTRACE_MEAN_H
7
8/**
9 * @file
10 * @ingroup api_trace
11 * Per-type sample mean of a trace.
12 *
13 * Templated port of matlab/lib/kpctoolbox/trace/mtrace_mean.m, cross-checked
14 * against jar/src/main/java/jline/api/trace/Mtrace_mean.java (identical,
15 * including the 0-indexed type vector: type c ranges over 0..ntypes-1, unlike
16 * the m3a mtrace_* family which uses the values of unique(A)).
17 *
18 * Both references return NaN for a type that never occurs. Rational
19 * arithmetic has no NaN, so the per-type counts are returned alongside the
20 * means and count[c] == 0 marks an undefined entry.
21 *
22 * ARITHMETIC: a sum and one division per type, exact in Rational.
23 */
24
25#include <cstddef>
26#include <vector>
27
29#include "line/num/number.h"
30#include "line/util/error.h"
31
32namespace line {
33namespace trace {
34
35/** Return value of mtrace_mean. */
36template <class T>
38 std::vector<T> mean; ///< one mean per type; undefined where count = 0
39 std::vector<long> count; ///< samples of each type
40};
41
42/**
43 * @brief Per-type sample mean of a trace.
44 *
45 * @param Tv the trace
46 * @param ntypes number of types
47 * @param type type of each sample, in 0..ntypes-1
48 */
49template <class T>
50MtraceMeanResult<T> mtrace_mean(const std::vector<T>& Tv, long ntypes,
51 const std::vector<int>& type) {
52 detail::require_marked(Tv, type, "mtrace_mean");
53 if (ntypes <= 0) throw InputError("mtrace_mean: ntypes must be positive");
55 out.mean.assign(static_cast<std::size_t>(ntypes), num_traits<T>::from_int(0));
56 out.count.assign(static_cast<std::size_t>(ntypes), 0);
57 for (long c = 0; c < ntypes; ++c) {
59 long ctr = 0;
60 for (std::size_t i = 0; i < Tv.size(); ++i) {
61 if (type[i] != static_cast<int>(c)) continue;
62 sum += Tv[i];
63 ++ctr;
64 }
65 out.count[static_cast<std::size_t>(c)] = ctr;
66 if (ctr > 0)
67 out.mean[static_cast<std::size_t>(c)] = sum / num_traits<T>::from_int(ctr);
68 }
69 return out;
70}
71
72} // namespace trace
73} // namespace line
74
75#endif // LINE_API_TRACE_MTRACE_MEAN_H
InputError(const std::string &what)
Definition error.h:39
The exception types the port throws.
MtraceMeanResult< T > mtrace_mean(const std::vector< T > &Tv, long ntypes, const std::vector< int > &type)
Per-type sample mean of a trace.
Definition mtrace_mean.h:50
Number-type abstraction for the templated API port.
Return value of mtrace_mean.
Definition mtrace_mean.h:37
std::vector< T > mean
one mean per type; undefined where count = 0
Definition mtrace_mean.h:38
std::vector< long > count
samples of each type
Definition mtrace_mean.h:39
Shared declarations for the empirical trace statistics domain.