LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
sim_fd_emcfd.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_SIM_SIM_FD_EMCFD_H
6#define LINE_API_SIM_SIM_FD_EMCFD_H
7
8/**
9 * @file
10 * @ingroup api_sim
11 * Gradient of a noisy function by central differences with a tuned step.
12 *
13 * Port of matlab/src/api/sim/sim_fd_emcfd.m and sim_fd_emcfd_pilot_deltas.m
14 * (JAR jline.api.sim.SimFdEmcfd, Python line_solver.api.sim.fdtune): the
15 * Estimation-Minimization Central Finite-Difference (EM-CFD) scheme of Li and
16 * Lam (2020).
17 *
18 * THE STEP IS NOT GUESSED, IT IS ESTIMATED. The MSE of the central difference
19 * averaged over n2 pairs at step d is B^2 d^4 + sigma^2/(2 n2 d^2), with
20 * B = f'''(x0)/6 and sigma^2 = Var fhat(x0), minimized at
21 * d* = (sigma^2/(4 n2 B^2))^(1/6). The E-stage spends n1 = max(3, floor(lambda n))
22 * pairs at varied pilot steps and regresses the differences on 2d and 2d^3
23 * (Li and Lam, eq. (2)) to estimate B; sigma^2 comes from the regression
24 * residuals. The M-stage runs the remaining n2 = n - n1 pairs at d* and returns
25 * their average quotient. A vector output shares one step,
26 * d*^6 = sum_j w_j sigma_j^2 / (4 n2 sum_j w_j B_j^2), with default weights
27 * 1/fbar_j^2 (zero where the pilot mean fbar_j vanishes).
28 *
29 * The pilot steps are the stratified half-normal quantiles
30 * s n1^(-1/10) Phi^{-1}(1/2 + (i - 1/2)/(2 n1)) rather than the paper's i.i.d.
31 * normal draw: the same moments, and the same steps in all four codebases.
32 *
33 * Reference: H. Li, H. Lam (2020). Optimally tuning finite-difference
34 * estimators. Proceedings of the 2020 Winter Simulation Conference, 457-468.
35 */
36
37#include <algorithm>
38#include <cmath>
39#include <cstddef>
40#include <functional>
41#include <limits>
42#include <string>
43#include <vector>
44
46#include "line/util/error.h"
47
48namespace line {
49namespace sim {
50
51/** Options of sim_fd_emcfd, with the reference defaults. */
53 double lambda = 0.2; ///< E-stage allocation ratio in (0,1)
54 double pilot_scale = 0.1; ///< standard deviation of the pilot step law
55 double min_step = 0.0; ///< lower bound on every step used
56 double max_step = std::numeric_limits<double>::infinity(); ///< upper bound
57 std::vector<double> weights; ///< per-component weights; empty = default
58};
59
60/** Result of sim_fd_emcfd. */
62 std::vector<double> grad; ///< gradient estimate per component
63 std::vector<double> stderr_; ///< standard error of grad
64 double delta = 0.0; ///< M-stage step
65 std::vector<double> B; ///< E-stage estimate of f'''/6
66 std::vector<double> sigma2; ///< E-stage noise variance estimate
67 std::vector<double> pilot_grad; ///< E-stage regression slope
68 std::vector<double> pilot_deltas; ///< E-stage steps
69 std::vector<double> weights; ///< weights of the step criterion
70 std::size_t n1 = 0, n2 = 0, nevals = 0;
71};
72
73/**
74 * The E-stage perturbation sizes, clipped to `max_step`.
75 *
76 * @param n1 number of pilot pairs
77 * @param pilot_scale standard deviation of the pilot step law
78 * @param max_step upper bound on the steps
79 */
80inline std::vector<double> sim_fd_emcfd_pilot_deltas(
81 std::size_t n1, double pilot_scale,
82 double max_step = std::numeric_limits<double>::infinity()) {
83 std::vector<double> d(n1);
84 const double scale = pilot_scale * std::pow(static_cast<double>(n1), -0.1);
85 for (std::size_t i = 1; i <= n1; ++i) {
86 const double q = sim_norminv(0.5 + 0.5 * (static_cast<double>(i) - 0.5) / static_cast<double>(n1));
87 d[i - 1] = std::min(scale * q, max_step);
88 }
89 return d;
90}
91
92/**
93 * EM-CFD gradient estimate.
94 *
95 * `fhat(x, k)` returns a noisy, unbiased estimate of f(x), one entry per
96 * component; k in 1..n is the replication index, which a simulation caller maps
97 * to a seed. Both evaluations of pair k receive the same k, so a caller may pair
98 * them with common random numbers; distinct pairs must be independent.
99 *
100 * @param fhat noisy evaluator
101 * @param x0 point at which the derivative is wanted
102 * @param n total number of differencing pairs (2n calls), at least 4
103 * @param o options
104 */
106 const std::function<std::vector<double>(double, std::size_t)>& fhat,
107 double x0, std::size_t n, const SimFdEmcfdOptions& o = SimFdEmcfdOptions()) {
108 if (n < 4)
109 throw InputError("sim_fd_emcfd needs at least 4 differencing pairs, got " + std::to_string(n) + ".");
110 if (!(o.lambda > 0.0 && o.lambda < 1.0))
111 throw InputError("sim_fd_emcfd: the allocation ratio lambda must lie in (0,1).");
112 if (!(o.pilot_scale > 0.0) || !std::isfinite(o.pilot_scale))
113 throw InputError("sim_fd_emcfd: the pilot scale must be a positive finite number.");
114 if (!(o.min_step >= 0.0) || !(o.max_step > 0.0) || o.min_step > o.max_step)
115 throw InputError("sim_fd_emcfd: the step bounds must satisfy 0 <= min_step <= max_step, max_step > 0.");
116 const std::size_t n1 = std::max<std::size_t>(
117 3, static_cast<std::size_t>(std::floor(o.lambda * static_cast<double>(n))));
118 if (n1 >= n)
119 throw InputError("sim_fd_emcfd: the E-stage (" + std::to_string(n1) +
120 " pairs) leaves no pair for the M-stage; increase n.");
121 const std::size_t n2 = n - n1;
122
123 auto checked = [&](const std::vector<double>& v, std::size_t m) {
124 if (v.size() != m)
125 throw InputError("sim_fd_emcfd: the evaluator returned " + std::to_string(v.size()) +
126 " components where " + std::to_string(m) + " were expected.");
127 };
128
129 // ---- E-stage --------------------------------------------------------
130 const std::vector<double> d = sim_fd_emcfd_pilot_deltas(n1, o.pilot_scale, o.max_step);
131 std::size_t m = 0;
132 std::vector<std::vector<double>> Y(n1);
133 std::vector<double> fsum;
134 for (std::size_t i = 0; i < n1; ++i) {
135 const std::vector<double> fp = fhat(x0 + d[i], i + 1);
136 const std::vector<double> fm = fhat(x0 - d[i], i + 1);
137 if (i == 0) {
138 m = fp.size();
139 fsum.assign(m, 0.0);
140 }
141 checked(fp, m);
142 checked(fm, m);
143 Y[i].resize(m);
144 for (std::size_t j = 0; j < m; ++j) {
145 Y[i][j] = fp[j] - fm[j];
146 fsum[j] += fp[j] + fm[j];
147 }
148 }
149 double s2 = 0.0, s4 = 0.0, s6 = 0.0, dmax = 0.0;
150 for (std::size_t i = 0; i < n1; ++i) {
151 const double d2 = d[i] * d[i];
152 s2 += d2;
153 s4 += d2 * d2;
154 s6 += d2 * d2 * d2;
155 dmax = std::max(dmax, d[i]);
156 }
157 const double det = s2 * s6 - s4 * s4;
158 if (!(det > 0.0)) throw InputError("sim_fd_emcfd: the pilot steps are degenerate; increase pilot_scale.");
159
161 out.B.assign(m, 0.0);
162 out.pilot_grad.assign(m, 0.0);
163 out.sigma2.assign(m, 0.0);
164 std::vector<double> fbar(m, 0.0);
165 for (std::size_t j = 0; j < m; ++j) {
166 double s1y = 0.0, s3y = 0.0;
167 for (std::size_t i = 0; i < n1; ++i) {
168 s1y += d[i] * Y[i][j];
169 s3y += d[i] * d[i] * d[i] * Y[i][j];
170 }
171 out.B[j] = (s2 * s3y - s4 * s1y) / (2.0 * det);
172 out.pilot_grad[j] = (s6 * s1y - s4 * s3y) / (2.0 * det);
173 double ss = 0.0;
174 for (std::size_t i = 0; i < n1; ++i) {
175 const double res = Y[i][j] - 2.0 * d[i] * out.pilot_grad[j] - 2.0 * d[i] * d[i] * d[i] * out.B[j];
176 ss += res * res;
177 }
178 // Var(y) -> 2 sigma^2 as d -> 0, and the fit spends two degrees of freedom.
179 out.sigma2[j] = ss / static_cast<double>(n1 - 2) / 2.0;
180 fbar[j] = fsum[j] / (2.0 * static_cast<double>(n1));
181 }
182
183 out.weights.assign(m, 0.0);
184 if (o.weights.empty()) {
185 bool any = false;
186 for (std::size_t j = 0; j < m; ++j)
187 if (std::fabs(fbar[j]) > 0.0) {
188 out.weights[j] = 1.0 / (fbar[j] * fbar[j]);
189 any = true;
190 }
191 if (!any) std::fill(out.weights.begin(), out.weights.end(), 1.0);
192 } else {
193 if (o.weights.size() != m)
194 throw InputError("sim_fd_emcfd: the weights must be " + std::to_string(m) + " finite non-negative values.");
195 for (std::size_t j = 0; j < m; ++j) {
196 if (!(o.weights[j] >= 0.0) || !std::isfinite(o.weights[j]))
197 throw InputError("sim_fd_emcfd: the weights must be " + std::to_string(m) +
198 " finite non-negative values.");
199 out.weights[j] = o.weights[j];
200 }
201 }
202
203 double num = 0.0, den = 0.0;
204 for (std::size_t j = 0; j < m; ++j) {
205 num += out.weights[j] * out.sigma2[j];
206 den += out.weights[j] * out.B[j] * out.B[j];
207 }
208 double delta;
209 if (den > 0.0 && num > 0.0)
210 delta = std::pow(num / (4.0 * static_cast<double>(n2) * den), 1.0 / 6.0);
211 else if (den > 0.0)
212 delta = o.min_step; // no noise: the bias alone sets the step
213 else if (std::isfinite(o.max_step))
214 delta = o.max_step;
215 else
216 delta = dmax;
217 delta = std::min(std::max(delta, o.min_step), o.max_step);
218 if (!(delta > 0.0)) delta = dmax;
219
220 // ---- M-stage --------------------------------------------------------
221 std::vector<std::vector<double>> Q(n2, std::vector<double>(m, 0.0));
222 out.grad.assign(m, 0.0);
223 for (std::size_t k = 0; k < n2; ++k) {
224 const std::size_t idx = n1 + k + 1;
225 const std::vector<double> fp = fhat(x0 + delta, idx);
226 const std::vector<double> fm = fhat(x0 - delta, idx);
227 checked(fp, m);
228 checked(fm, m);
229 for (std::size_t j = 0; j < m; ++j) {
230 Q[k][j] = (fp[j] - fm[j]) / (2.0 * delta);
231 out.grad[j] += Q[k][j];
232 }
233 }
234 out.stderr_.assign(m, std::numeric_limits<double>::quiet_NaN());
235 for (std::size_t j = 0; j < m; ++j) {
236 out.grad[j] /= static_cast<double>(n2);
237 if (n2 > 1) {
238 double ss = 0.0;
239 for (std::size_t k = 0; k < n2; ++k) {
240 const double e = Q[k][j] - out.grad[j];
241 ss += e * e;
242 }
243 out.stderr_[j] = std::sqrt(ss / static_cast<double>(n2 - 1)) / std::sqrt(static_cast<double>(n2));
244 }
245 }
246 out.delta = delta;
247 out.pilot_deltas = d;
248 out.n1 = n1;
249 out.n2 = n2;
250 out.nevals = 2 * n;
251 return out;
252}
253
254} // namespace sim
255} // namespace line
256
257#endif // LINE_API_SIM_SIM_FD_EMCFD_H
InputError(const std::string &what)
Definition error.h:105
The exception types the port throws.
SimFdEmcfdResult sim_fd_emcfd(const std::function< std::vector< double >(double, std::size_t)> &fhat, double x0, std::size_t n, const SimFdEmcfdOptions &o=SimFdEmcfdOptions())
EM-CFD gradient estimate.
double sim_norminv(double p)
Standard normal quantile function.
Definition sim_dist.h:62
std::vector< double > sim_fd_emcfd_pilot_deltas(std::size_t n1, double pilot_scale, double max_step=std::numeric_limits< double >::infinity())
The E-stage perturbation sizes, clipped to max_step.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Normal and Student t quantiles used by the output-analysis routines.
Options of sim_fd_emcfd, with the reference defaults.
double max_step
upper bound
std::vector< double > weights
per-component weights; empty = default
double pilot_scale
standard deviation of the pilot step law
double min_step
lower bound on every step used
double lambda
E-stage allocation ratio in (0,1).
Result of sim_fd_emcfd.
std::vector< double > stderr_
standard error of grad
std::vector< double > sigma2
E-stage noise variance estimate.
std::vector< double > weights
weights of the step criterion
std::vector< double > pilot_grad
E-stage regression slope.
std::vector< double > B
E-stage estimate of f'''/6.
std::vector< double > grad
gradient estimate per component
double delta
M-stage step.
std::vector< double > pilot_deltas
E-stage steps.