LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
trace_shuffle.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_TRACE_SHUFFLE_H
6#define LINE_API_TRACE_TRACE_SHUFFLE_H
7
8/**
9 * @file
10 * @ingroup api_trace
11 * Random permutation of a trace.
12 *
13 * Templated port of matlab/lib/kpctoolbox/trace/trace_shuffle.m.
14 *
15 * Shuffling destroys the autocorrelation while leaving every marginal moment
16 * untouched, which is what makes it the null model for a correlation test: any
17 * statistic that moves under a shuffle is reading the ORDER of the trace, not
18 * its distribution. Callers that want an uncorrelated trace with the same
19 * marginal use this rather than resampling, because resampling would perturb
20 * the empirical moments as well.
21 */
22
23#include <algorithm>
24#include <cstddef>
25#include <numeric>
26#include <random>
27#include <vector>
28
29#include "line/util/error.h"
30
31namespace line {
32namespace trace {
33
34/** A uniformly random permutation of the samples, drawn with the given engine. */
35template <class T, class Gen>
36std::vector<T> trace_shuffle(const std::vector<T>& S, Gen& gen) {
37 if (S.empty()) throw InputError("trace_shuffle: the trace is empty");
38 // Fisher-Yates over the index set, so T needs no swap beyond a copy
39 std::vector<std::size_t> idx(S.size());
40 std::iota(idx.begin(), idx.end(), static_cast<std::size_t>(0));
41 for (std::size_t i = S.size(); i > 1; --i) {
42 std::uniform_int_distribution<std::size_t> pick(0, i - 1);
43 std::swap(idx[i - 1], idx[pick(gen)]);
44 }
45 std::vector<T> out(S.size());
46 for (std::size_t i = 0; i < S.size(); ++i) out[i] = S[idx[i]];
47 return out;
48}
49
50} // namespace trace
51} // namespace line
52
53#endif // LINE_API_TRACE_TRACE_SHUFFLE_H
InputError(const std::string &what)
Definition error.h:39
The exception types the port throws.
std::vector< T > trace_shuffle(const std::vector< T > &S, Gen &gen)
A uniformly random permutation of the samples, drawn with the given engine.