LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_sens_table.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_SOLVERS_SENS_SOLVER_SENS_TABLE_H
6#define LINE_SOLVERS_SENS_SOLVER_SENS_TABLE_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Performance sensitivities with respect to service rates.
12 *
13 * Port of `matlab/src/solvers/@@NetworkSolver/getSensitivityTable.m`. One row
14 * per (station, class) carrying dTput/dRate, dRespT/dRate, dQLen/dRate and
15 * dUtil/dRate, produced by one of two branches:
16 *
17 * `exact` Analytic differentiation of a product-form recursion. A closed
18 * model goes through `pfqn_sens` (differentiated MVA) evaluated AT
19 * CHAIN LEVEL, an open one through the closed-form BCMP derivatives,
20 * whose stations decouple. Exact to working precision and cheaper
21 * than one extra solve, but defined only where the recursion is:
22 * single-server stations plus delays, and not a mixed model.
23 *
24 * `fd` Forward or central differences on the CALLER'S OWN solver. The
25 * service at (station, class) is rate-scaled by (1 +/- h), the same
26 * solve is re-run and the quotient formed. It costs 1 + M*R solves
27 * (forward) or 2*M*R (central) and is the only branch that applies to
28 * a model with no product form.
29 *
30 * WHY THE SOLVER IS A CALLBACK. The reference reaches this through a method on
31 * NetworkSolver, so `self` names both the model and the engine; there is no
32 * solver base class here, and the finite-difference branch needs to re-run
33 * THE SAME engine with THE SAME options -- an MVA table produced by perturbing
34 * a model that is then solved by CTMC is not a sensitivity of anything. The
35 * callback is that engine, already bound to the struct passed in, and it is
36 * called after this code has written the perturbed service into it.
37 *
38 * A SIMULATION SOLVER MUST BE RUN WITH COMMON RANDOM NUMBERS, or the quotient
39 * measures Monte Carlo error rather than a derivative. There is no seed to pin
40 * here -- the callback owns its options -- so `SensOptions::simulation` only
41 * widens the default step to 1e-2, and a caller wiring a stochastic engine in
42 * is responsible for handing it a fixed seed.
43 *
44 * TUNED STEP. A simulator differenced centrally with no step given, whose
45 * caller also supplies `SensOptions::replicate`, does not use a fixed step: the
46 * step is estimated per row by the EM-CFD scheme of Li and Lam (2020), see
47 * sim_fd_emcfd.h, over FD_EMCFD_PAIRS replications. Before every solve of
48 * pair k the hook is called as replicate(k, FD_EMCFD_PAIRS), and the caller
49 * must then run the engine with seed (its seed + k - 1) and samples/npairs
50 * samples (the cost of the fixed-step central sweep); replicate(0, 0) restores
51 * its normal options. The step used for each row is reported in
52 * SensTable::step.
53 */
54
55#include <cmath>
56#include <cstddef>
57#include <functional>
58#include <limits>
59#include <string>
60#include <vector>
61
66#include "line/num/number.h"
69#include "line/util/error.h"
70#include "line/util/matrix.h"
71
72namespace line {
73namespace sens {
74
75/** The name-value contract of getSensitivityTable. */
77 std::string method = "auto"; ///< auto | exact | fd
78 std::string scheme = "forward"; ///< forward | central
79 /** Relative step of the rate perturbation; negative selects the default. */
80 double step = -1.0;
81 /** True when the callback is a simulator, which widens the default step. */
82 bool simulation = false;
83 /**
84 * Replication hook of the tuned simulator central branch: (k, npairs)
85 * before a solve of pair k, (0, 0) to restore. Empty disables the branch.
86 */
87 std::function<void(std::size_t, std::size_t)> replicate;
88};
89
90/** Replications of the tuned simulator central branch. */
91constexpr std::size_t FD_EMCFD_PAIRS = 32;
92/** E-stage allocation ratio of the tuned simulator central branch. */
93constexpr double FD_EMCFD_LAMBDA = 0.25;
94
95/** One (station, class) row of the table. */
96template <class T>
97struct SensRow {
98 std::string station, jobclass;
100};
101
102/** What the table carries, plus the branch that produced it. */
103template <class T>
104struct SensTable {
105 std::vector<SensRow<T>> rows;
106 std::string method; ///< "exact" or "fd", the branch actually taken
107 /** Relative finite-difference step of each row; empty on the exact branch. */
108 std::vector<double> step;
109 /** The analytic Jacobian, set only on the CLOSED exact branch. */
110 bool has_jacobian = false;
112};
113
114namespace detail {
115
116/**
117 * Scope of the analytic branch: single-server stations (a delay is allowed) and
118 * not a mixed open-and-closed model. Class switching IS supported -- the branch
119 * aggregates classes into chains before differentiating.
120 */
121template <class T>
122bool sens_exact_in_scope(const qn::NetworkStruct<T>& sn, std::string& why) {
124 try {
126 } catch (const std::exception&) {
127 why = "the product-form parameters of this model could not be extracted";
128 return false;
129 }
130 for (double s : p.S)
131 if (std::isfinite(s) && s > 1.0) {
132 why = "exact sensitivities support single-server stations only";
133 return false;
134 }
135 bool any_open = false, any_closed = false;
136 for (double n : p.N) {
137 if (std::isinf(n)) any_open = true;
138 else any_closed = true;
139 }
140 if (any_open && any_closed) {
141 why = "exact sensitivities do not yet support mixed (open+closed) networks";
142 return false;
143 }
144 return true;
145}
146
147/** (nstations x nclasses) mask of the pairs that carry visits. */
148template <class T>
149std::vector<std::vector<bool>> sens_visit_mask(const qn::NetworkStruct<T>& sn) {
150 std::vector<std::vector<bool>> out(sn.nstations, std::vector<bool>(sn.nclasses, false));
151 for (std::size_t c = 0; c < sn.nchains; ++c) {
152 if (sn.visits[c].empty()) continue;
153 for (std::size_t i = 1; i <= sn.nstations; ++i) {
154 // Resolved through the node, not stateful_of_station: that helper
155 // THROWS on a station with no stateful node, and a mask is not the
156 // place to discover one.
157 const std::size_t nd = sn.node_of_station(i);
158 const std::size_t sf = nd ? sn.stateful_index(nd) : 0;
159 if (sf == 0) continue;
160 for (std::size_t r = 0; r < sn.nclasses; ++r)
161 if (num_traits<T>::to_double(sn.visits[c](sf - 1, r)) > lang::GlobalConstants::Zero)
162 out[i - 1][r] = true;
163 }
164 }
165 return out;
166}
167
168} // namespace detail
169
170/**
171 * Build the sensitivity table of `sn` under `solve`.
172 *
173 * `exact_available` is the reference's `supportsExactSensitivity()`: true for
174 * the engines that evaluate the product-form recursion this branch
175 * differentiates (MVA and NC), false for every other. Asking for `exact` where
176 * it is false is an error rather than a silent downgrade, exactly as in the
177 * reference, because the two branches answer to different precision.
178 *
179 * `solve` is called with `sn` already carrying whatever perturbation this code
180 * has written, and must report the metrics of that struct.
181 */
182template <class T>
184 bool exact_available,
185 const std::function<mva::MvaSolution<T>()>& solve) {
186 using lang::Distrib;
187 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
188 if (opt.method != "auto" && opt.method != "exact" && opt.method != "fd")
189 throw InputError("getSensitivityTable: the method must be 'auto', 'exact' or 'fd'");
190 if (opt.scheme != "forward" && opt.scheme != "central")
191 throw InputError("getSensitivityTable: the scheme must be 'forward' or 'central'");
192
193 std::string why;
194 const bool in_scope = detail::sens_exact_in_scope(sn, why);
195 bool use_exact;
196 if (opt.method == "exact") {
197 if (!exact_available)
198 throw UnsupportedError(ErrorKind{"Analysis"},
199 "getSensitivityTable: exact analytic sensitivities differentiate a product-form "
200 "recursion and are available on the MVA and NC engines only; use 'fd'");
201 if (!in_scope) throw UnsupportedError(ErrorKind{"Model"}, "getSensitivityTable: " + why);
202 use_exact = true;
203 } else if (opt.method == "fd") {
204 use_exact = false;
205 } else {
206 use_exact = exact_available && in_scope;
207 }
208
210 const std::size_t R = sn.nclasses, Mq = p.queue_stations.size(), C = sn.nchains;
211
212 std::vector<std::vector<bool>> mask(Mq, std::vector<bool>(R, false));
213 std::vector<std::vector<double>> steps; // per-row FD step, empty on the exact branch
214 Matrix<T> dT(Mq, R, zero), dR(Mq, R, zero), dQ(Mq, R, zero), dU(Mq, R, zero);
215 SensTable<T> out;
216
217 if (use_exact) {
218 out.method = "exact";
219 bool is_open = false;
220 for (double n : p.N)
221 if (std::isinf(n)) is_open = true;
222
223 Matrix<T> rates(Mq, R, zero);
224 for (std::size_t i = 0; i < Mq; ++i) {
225 const std::size_t st = p.queue_stations[i];
226 for (std::size_t r = 0; r < R; ++r) {
227 rates(i, r) = sn.rates(st - 1, r);
228 const double rd = num_traits<T>::to_double(rates(i, r));
229 mask[i][r] = std::isfinite(rd) && rd > 0.0 && p.D(i, r) > zero;
230 }
231 }
232
233 // chainOf(r), and the per-chain aggregates the recursion is evaluated on:
234 // a product-form model is solved per CHAIN, and with class switching a
235 // class is only a share of one.
236 std::vector<std::size_t> chain_of(R, 0);
237 Matrix<T> Dc(Mq, C, zero);
238 std::vector<T> Zc(C, zero);
239 std::vector<int> Nc(C, 0);
240 std::vector<T> lambdac(C, zero);
241 for (std::size_t c = 0; c < C; ++c) {
242 double nsum = 0.0;
243 for (std::size_t r = 0; r < R; ++r) {
244 if (!sn.chains[c][r]) continue;
245 chain_of[r] = c;
246 for (std::size_t i = 0; i < Mq; ++i) Dc(i, c) = T(Dc(i, c) + p.D(i, r));
247 for (std::size_t z = 0; z < p.Z.rows(); ++z) Zc[c] = T(Zc[c] + p.Z(z, r));
248 if (std::isfinite(p.N[r])) nsum += p.N[r];
249 // a class reached only by class switching has no source rate (NaN): it adds no external arrivals
250 if (!std::isnan(num_traits<T>::to_double(p.lambda[r]))) lambdac[c] = T(lambdac[c] + p.lambda[r]);
251 }
252 Nc[c] = static_cast<int>(nsum + 0.5);
253 }
254
255 if (!is_open) {
256 const pfqn::SensResult<T> s = pfqn::pfqn_sens(Dc, Nc, Zc);
257 out.has_jacobian = true;
258 out.jacobian = s;
259 for (std::size_t i = 0; i < Mq; ++i)
260 for (std::size_t r = 0; r < R; ++r) {
261 if (!mask[i][r]) continue;
262 const std::size_t c = chain_of[r];
263 if (!(Dc(i, c) > zero)) continue;
264 const T rate = rates(i, r);
265 const T Dir = p.D(i, r);
266 const T visits = T(Dir * rate); // chain-normalized visit ratio
267 const std::size_t pidx = i * C + c;
268 const T chain = T(-Dir / rate); // dDc(i,c)/dmu(i,r)
269 const T Xc = s.XN[c];
270 const T Qc = s.QN(i, c);
271 const T dXc = T(s.dX(c, pidx) * chain);
272 const T dQc = T(s.dQ[pidx](i, c) * chain);
273 // Class share of the chain queue here, and its own rate dependence.
274 const T alpha = T(Dir / Dc(i, c));
275 const T dalpha = T(chain * (Dc(i, c) - Dir) / (Dc(i, c) * Dc(i, c)));
276 const T Qir = T(alpha * Qc);
277 const T dQir = T(dalpha * Qc + alpha * dQc);
278 const T Tir = T(Xc * visits);
279 const T dTir = T(dXc * visits);
280 dT(i, r) = dTir;
281 dQ(i, r) = dQir;
282 dU(i, r) = T(dXc * Dir + Xc * chain);
283 // Per-visit response time by Little's law, R = Q/T.
284 if (Tir > zero) dR(i, r) = T((dQir * Tir - Qir * dTir) / (Tir * Tir));
285 }
286 } else {
287 // The stations decouple, so only the own service rate moves the
288 // measures at (i, r); the throughput is fixed by the arrival rate.
289 Matrix<T> rho(Mq, R, zero);
290 std::vector<T> Ui(Mq, zero);
291 for (std::size_t i = 0; i < Mq; ++i)
292 for (std::size_t r = 0; r < R; ++r) {
293 if (p.D(i, r) > zero) rho(i, r) = T(lambdac[chain_of[r]] * p.D(i, r));
294 Ui[i] = T(Ui[i] + rho(i, r));
295 }
296 for (std::size_t i = 0; i < Mq; ++i) {
297 const T denom = T(one - Ui[i]);
298 for (std::size_t r = 0; r < R; ++r) {
299 if (!mask[i][r]) continue;
300 const T rate = rates(i, r);
301 const T svct = T(one / rate); // per-visit service time
302 const T drho = T(-rho(i, r) / rate);
303 const T dUi = drho; // own class only
304 const T dsvct = T(-svct / rate);
305 dR(i, r) = T((dsvct * denom + svct * dUi) / (denom * denom));
306 dQ(i, r) = T((drho * denom + rho(i, r) * dUi) / (denom * denom));
307 dU(i, r) = drho;
308 dT(i, r) = zero; // open throughput = lambda*visits, fixed
309 }
310 }
311 }
312 } else {
313 out.method = "fd";
314 const bool central = opt.scheme == "central";
315 double h = opt.step;
316 if (!(h > 0.0)) h = opt.simulation ? 1e-2 : 1e-4;
317 if (!std::isfinite(h) || h <= 0.0 || h >= 1.0)
318 throw InputError("getSensitivityTable: the finite-difference step must be in (0,1)");
319 const T hT = num_traits<T>::from_double(h);
320
321 const std::vector<std::vector<bool>> visited = detail::sens_visit_mask(sn);
322 for (std::size_t i = 0; i < Mq; ++i) {
323 const std::size_t st = p.queue_stations[i];
324 for (std::size_t r = 0; r < R; ++r) {
325 const double rd = num_traits<T>::to_double(sn.rates(st - 1, r));
326 mask[i][r] = std::isfinite(rd) && rd > 0.0 && visited[st - 1][r];
327 }
328 }
329 steps.assign(Mq, std::vector<double>(R, h));
330
331 // A simulator differenced centrally with no step given takes the tuned
332 // step, provided the caller can replicate its engine.
333 const bool tuned = central && !(opt.step > 0.0) && opt.simulation &&
334 static_cast<bool>(opt.replicate);
335 if (tuned) {
338 eo.pilot_scale = 0.1;
339 eo.min_step = 1e-4;
340 eo.max_step = 0.5;
341 for (std::size_t i = 0; i < Mq; ++i) {
342 const std::size_t st = p.queue_stations[i];
343 for (std::size_t r = 0; r < R; ++r) {
344 if (!mask[i][r]) continue;
345 const T rate = sn.rates(st - 1, r);
346 const Distrib<T> saved = sn.service[st - 1][r];
347 // The variable is the relative perturbation x, mu -> mu(1+x),
348 // so d(.)/dmu = f'(0)/mu.
349 auto fhat = [&](double x, std::size_t k) {
350 sn.set_service(st, r + 1, lang::dist_scale_rate(
351 saved, T(one + num_traits<T>::from_double(x))));
352 sn.refresh_rates();
353 opt.replicate(k, FD_EMCFD_PAIRS);
354 const mva::MvaSolution<T> s = solve();
355 return std::vector<double>{
356 num_traits<T>::to_double(s.Tp(st - 1, r)),
357 num_traits<T>::to_double(s.R(st - 1, r)),
358 num_traits<T>::to_double(s.Q(st - 1, r)),
359 num_traits<T>::to_double(s.U(st - 1, r))};
360 };
362 try {
363 res = sim::sim_fd_emcfd(fhat, 0.0, FD_EMCFD_PAIRS, eo);
364 } catch (...) {
365 opt.replicate(0, 0);
366 sn.set_service(st, r + 1, saved);
367 sn.refresh_rates();
368 throw;
369 }
370 opt.replicate(0, 0);
371 sn.set_service(st, r + 1, saved);
372 sn.refresh_rates();
373 dT(i, r) = T(num_traits<T>::from_double(res.grad[0]) / rate);
374 dR(i, r) = T(num_traits<T>::from_double(res.grad[1]) / rate);
375 dQ(i, r) = T(num_traits<T>::from_double(res.grad[2]) / rate);
376 dU(i, r) = T(num_traits<T>::from_double(res.grad[3]) / rate);
377 steps[i][r] = res.delta;
378 }
379 }
380 } else {
381 const mva::MvaSolution<T> base = solve();
382 for (std::size_t i = 0; i < Mq; ++i) {
383 const std::size_t st = p.queue_stations[i];
384 for (std::size_t r = 0; r < R; ++r) {
385 if (!mask[i][r]) continue;
386 const T rate = sn.rates(st - 1, r);
387 const Distrib<T> saved = sn.service[st - 1][r];
388
389 sn.set_service(st, r + 1, lang::dist_scale_rate(saved, T(one + hT)));
390 sn.refresh_rates();
391 const mva::MvaSolution<T> up = solve();
392
393 mva::MvaSolution<T> down = base;
394 T denom = T(rate * hT);
395 if (central) {
396 sn.set_service(st, r + 1, lang::dist_scale_rate(saved, T(one - hT)));
397 sn.refresh_rates();
398 down = solve();
399 denom = T(num_traits<T>::from_int(2) * rate * hT);
400 }
401
402 dT(i, r) = T((up.Tp(st - 1, r) - down.Tp(st - 1, r)) / denom);
403 dR(i, r) = T((up.R(st - 1, r) - down.R(st - 1, r)) / denom);
404 dQ(i, r) = T((up.Q(st - 1, r) - down.Q(st - 1, r)) / denom);
405 dU(i, r) = T((up.U(st - 1, r) - down.U(st - 1, r)) / denom);
406
407 // Restore before moving on: the sweep perturbs one pair at a
408 // time and every later quotient is taken at the base point.
409 sn.set_service(st, r + 1, saved);
410 sn.refresh_rates();
411 }
412 }
413 } // fixed step
414 }
415
416 for (std::size_t i = 0; i < Mq; ++i) {
417 const std::size_t st = p.queue_stations[i];
418 const std::size_t nd = sn.node_of_station(st);
419 for (std::size_t r = 0; r < R; ++r) {
420 if (!mask[i][r]) continue;
421 SensRow<T> row;
422 row.station = nd > 0 ? sn.nodes[nd - 1].name : sn.stations[st - 1].name;
423 row.jobclass = sn.classes[r].name;
424 row.dTput = dT(i, r);
425 row.dRespT = dR(i, r);
426 row.dQLen = dQ(i, r);
427 row.dUtil = dU(i, r);
428 out.rows.push_back(row);
429 if (!steps.empty()) out.step.push_back(steps[i][r]);
430 }
431 }
432 return out;
433}
434
435} // namespace sens
436} // namespace line
437
438#endif // LINE_SOLVERS_SENS_SOLVER_SENS_TABLE_H
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
Rate-scaled copy of a distribution, preserving its shape.
The exception types the port throws.
Dense matrix and non-owning view.
The option and result types every MVA analyzer shares.
Distrib< T > dist_scale_rate(const Distrib< T > &d, const T &factor)
The law of X / factor, in the same family as d.
PfParams< T > sn_get_product_form_params(const qn::NetworkStruct< T > &sn)
Port of sn_get_product_form_params.
SensResult< T > pfqn_sens(const Matrix< T > &L, const std::vector< int > &N, const std::vector< T > &Z, const std::vector< int > &mi)
Exact analytic derivatives of the mean performance measures {X,Q,U,R} of a closed product-form (BCMP)...
Definition pfqn_sens.h:348
constexpr double FD_EMCFD_LAMBDA
E-stage allocation ratio of the tuned simulator central branch.
SensTable< T > solver_sensitivity_table(qn::NetworkStruct< T > &sn, const SensOptions &opt, bool exact_available, const std::function< mva::MvaSolution< T >()> &solve)
Build the sensitivity table of sn under solve.
constexpr std::size_t FD_EMCFD_PAIRS
Replications of the tuned simulator central branch.
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.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
std::vector< T > solve(const Matrix< T > &A, const std::vector< T > &b)
Convenience: solve Ax = b, leaving A and b untouched.
Definition lu.h:158
A queueing network and its refreshed NetworkStruct.
Number-type abstraction for the templated API port.
Exact analytic derivatives of the mean performance measures {X,Q,U,R} of a closed product-form (BCMP)...
Gradient of a noisy function by central differences with a tuned step.
Port of matlab/src/api/sn/sn_get_product_form_params.m: the CLASS-level product-form parameters.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
static constexpr double Zero
Definition lang_types.h:825
Class-level results, the [Q,U,R,T,C,X] of the MATLAB analyzers.
Definition mva_types.h:97
The [lambda,D,N,Z,mu,S,V] of the reference.
std::vector< double > S
(Mq) server counts
Matrix< T > Z
(max(1,Mz) x R) demand at the delay stations
std::vector< double > N
(R) population, infinite on an open class
Matrix< T > D
(Mq x R) demand at the queueing stations
std::vector< std::size_t > queue_stations
(Mq) 1-based station indices
std::vector< T > lambda
(R) arrival rate, zero on a closed class
Matrix< T > QN
(M x R) mean queue length
Definition pfqn_sens.h:66
Matrix< T > dX
(R x P) dX(r)/dparam(p)
Definition pfqn_sens.h:72
std::vector< T > XN
(R) throughput
Definition pfqn_sens.h:65
std::vector< Matrix< T > > dQ
(P) matrices M x R, dQ[p](i,r)
Definition pfqn_sens.h:73
The name-value contract of getSensitivityTable.
std::function< void(std::size_t, std::size_t)> replicate
Replication hook of the tuned simulator central branch: (k, npairs) before a solve of pair k,...
bool simulation
True when the callback is a simulator, which widens the default step.
double step
Relative step of the rate perturbation; negative selects the default.
std::string scheme
forward | central
std::string method
auto | exact | fd
One (station, class) row of the table.
What the table carries, plus the branch that produced it.
std::vector< SensRow< T > > rows
std::vector< double > step
Relative finite-difference step of each row; empty on the exact branch.
pfqn::SensResult< T > jacobian
std::string method
"exact" or "fd", the branch actually taken
bool has_jacobian
The analytic Jacobian, set only on the CLOSED exact branch.
Options of sim_fd_emcfd, with the reference defaults.
double max_step
upper bound
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 > grad
gradient estimate per component
double delta
M-stage step.