LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
workflow.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_LANG_WORKFLOW_WORKFLOW_H
6#define LINE_LANG_WORKFLOW_WORKFLOW_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * An activity workflow reduced to one phase-type law.
12 *
13 * Port of matlab/src/lang/workflow/Workflow.m and WorkflowActivity.m, and of
14 * their twins jline.lang.workflow.Workflow (JAR) and
15 * line_solver.lang.workflow.Workflow (Python). A workflow is a precedence
16 * graph over activities, each carrying a host demand; `to_ph` composes those
17 * laws into a single phase-type distribution.
18 *
19 * WHAT THIS IS NOT. `include/line/api/wf/` holds the workflow pattern
20 * DETECTORS of `jline.api.wf`, which read a link matrix and report sequences,
21 * branches, parallel blocks and loops. This header is the algebra those
22 * patterns feed: the composition that turns a precedence graph into an
23 * (alpha, T) pair. An LQN fork-join is also a different object -- its branches
24 * contend for a host, so it yields a response time under contention rather
25 * than the order statistic of independent activity times returned here.
26 *
27 * A precedence graph that is SERIES-PARALLEL is reduced exactly, by recursive
28 * composition of the series-parallel tree, which handles arbitrary nesting (a
29 * fork inside a loop, a branch that is itself a fork-join). Any other graph
30 * falls back to the block composition, which is a heuristic and is documented
31 * as one.
32 *
33 * A LOOP repeats its body a GEOMETRIC number of times of mean COUNT, the
34 * POST_LOOP semantics of an activity graph (`getStruct.m:528-567`): a count of
35 * at least one runs the body once and takes the back edge with probability
36 * 1-1/COUNT, and a fractional count runs the body at most once, with
37 * probability COUNT. The COUNT-fold convolution is a different law with the
38 * same mean; it stays available as `compose_repeat` for a caller that wants
39 * exactly that.
40 *
41 * An EXTERNAL CALL has no separate representation: an activity whose host
42 * demand is the law of the call response time composes exactly like a local
43 * computation, and an asynchronous call blocks the caller for no time and is
44 * simply left out of the workflow.
45 *
46 * A QUORUM (partial) AND-join is REFUSED by name rather than served as a full
47 * join, because the first k of n branches to finish is not their maximum.
48 */
49
50#include <algorithm>
51#include <map>
52#include <string>
53#include <vector>
54
60#include "line/util/error.h"
61#include "line/util/matrix.h"
62
63namespace line {
64namespace workflow {
65
66using lang::Distrib;
67using lang::GlobalConstants;
68// The precedence kinds of `ActivityPrecedenceType.m`, shared with the LQN layer
71
72/**
73 * One precedence of the activity graph.
74 *
75 * `pre_params` carries the AND-join quorum when there is one; `post_params`
76 * carries the OR-fork probabilities or the loop count.
77 */
78template <class T>
79struct Precedence {
80 std::vector<std::string> pre_acts;
81 std::vector<std::string> post_acts;
82 PrecedenceType pre_type = PrecedenceType::PRE_SEQ;
83 PrecedenceType post_type = PrecedenceType::POST_SEQ;
84 std::vector<T> pre_params;
85 std::vector<T> post_params;
86};
87
88/** A phase-type law as the composition rules pass it around. */
89template <class T>
90struct PhLaw {
91 std::vector<T> alpha;
93};
94
95/**
96 * A computational activity.
97 *
98 * Carries no call list: an external call is an activity whose host demand is
99 * the law of the call response time.
100 */
101template <class T>
103public:
104 /** Order of the Erlang surrogate of a deterministic host demand (sn_nonmarkov_toph's default nonmkvorder). */
105 static constexpr std::size_t kDetPhases = 20;
106
107 WorkflowActivity() = default;
108 WorkflowActivity(const std::string& name, const Distrib<T>& host_demand)
109 : name_(name), host_demand_(host_demand) {}
110
111 const std::string& name() const { return name_; }
112
113 const Distrib<T>& host_demand() const { return host_demand_; }
114 void set_host_demand(const Distrib<T>& d) { host_demand_ = d; }
115
116 T host_demand_mean() const { return host_demand_.mean; }
117 T host_demand_scv() const { return host_demand_.scv; }
118
119 /**
120 * The (alpha, T) pair of this activity.
121 *
122 * A zero-time activity is one immediate phase, the representation used
123 * throughout this class; a Markovian law hands back its own pair; anything
124 * else is fitted to an acyclic phase-type on its first two moments, as the
125 * MATLAB and JAR twins do.
126 */
128 const T zero = num_traits<T>::from_int(0);
129 PhLaw<T> out;
130
131 if (host_demand_.type == ProcessType::IMMEDIATE ||
133 out.alpha.assign(1, num_traits<T>::from_int(1));
134 out.S = Matrix<T>(1, 1, zero);
136 return out;
137 }
138
139 if (host_demand_.has_map()) {
140 out.S = host_demand_.D0;
141 out.alpha = init_prob_of(host_demand_);
142 return out;
143 }
144
145 const T scv = host_demand_.scv;
146 // A deterministic law has no finite PH representation and a two-moment
147 // fit would need infinitely many phases: it is replaced by the Erlang of
148 // order kDetPhases, the Det surrogate of sn_nonmarkov_toph. It used to
149 // be an Exp of the same mean, which got even the mean of a fork-join of
150 // Det leaves wrong.
151 const Distrib<T> ph =
153 ? lang::aph_fit_mean_scv(host_demand_.mean, scv)
154 : lang::erlang_fit_mean_order<T>(host_demand_.mean, kDetPhases);
155 out.S = ph.D0;
156 out.alpha = init_prob_of(ph);
157 return out;
158 }
159
160 std::size_t num_phases() const { return ph_representation().S.rows(); }
161
162 /**
163 * Optional external metadata, MATLAB's `act.metadata` and the JAR's `getMetadata()`.
164 *
165 * Set by `io::wfcommons_load`. Keyed by field name; each value is the JSON TEXT of
166 * the field (`"4"`, `"\"mem\""`, `["a","b"]`), which keeps arrays and objects
167 * intact without making the lang layer depend on a JSON library. It plays no part
168 * in `to_ph()`.
169 */
170 const std::map<std::string, std::string>& metadata() const { return metadata_; }
171 void set_metadata(const std::map<std::string, std::string>& m) { metadata_ = m; }
172 bool has_metadata() const { return !metadata_.empty(); }
173
174private:
175 /**
176 * The initial vector of a Markovian law.
177 *
178 * `Distrib::phase_type` stores alpha in `params`, so a PH/APH/ME hands it
179 * back directly. For every other Markovian family D1 = (-D0 e) alpha, so
180 * ANY row with a positive exit rate recovers alpha -- and it cannot be row
181 * 0, since a canonical bidiagonal APH never completes from phase 1.
182 */
183 static std::vector<T> init_prob_of(const Distrib<T>& d) {
184 const std::size_t n = d.D0.rows();
185 const T zero = num_traits<T>::from_int(0);
186 if ((d.type == ProcessType::PH || d.type == ProcessType::APH ||
187 d.type == ProcessType::ME) &&
188 d.params.size() == n) {
189 return std::vector<T>(d.params.begin(), d.params.begin() + static_cast<long>(n));
190 }
191 for (std::size_t i = 0; i < n; ++i) {
192 T out = zero;
193 for (std::size_t j = 0; j < n; ++j) out += d.D1(i, j);
194 if (!(out > zero)) continue;
195 std::vector<T> alpha(n);
196 for (std::size_t j = 0; j < n; ++j) alpha[j] = T(d.D1(i, j) / out);
197 return alpha;
198 }
199 // No phase completes: start in phase 0, which is what a degenerate
200 // representation leaves as the only defensible reading
201 std::vector<T> alpha(n, zero);
202 if (n > 0) alpha[0] = num_traits<T>::from_int(1);
203 return alpha;
204 }
205
206 std::string name_;
207 Distrib<T> host_demand_;
208 std::map<std::string, std::string> metadata_;
209};
210
211/** A node of the series-parallel tree. */
212enum class SPNodeType { LEAF, SERIAL, PAR, OR, LOOP };
213
214template <class T>
215struct SPNode {
217 /** Activity index for a LEAF, npos otherwise. */
218 std::size_t act = static_cast<std::size_t>(-1);
219 std::vector<std::size_t> kids;
220 std::size_t parent = static_cast<std::size_t>(-1);
221 /** Branch probabilities for an OR node. */
222 std::vector<T> probs;
223 /** Loop count for a LOOP node. */
226 bool valid = false;
227};
228
229/**
230 * The flat series-parallel tree.
231 *
232 * `execs` carries the expected number of executions of each node per workflow
233 * execution, which is the weight by which an LQN metric reconstruction splits
234 * a layer result back over entries, activities and calls.
235 */
236template <class T>
237struct SPTree {
238 std::vector<SPNode<T>> nodes;
239 std::size_t root = static_cast<std::size_t>(-1);
240 /** Node index of each activity's leaf, npos when the activity has none. */
241 std::vector<std::size_t> leaf_of;
242 std::vector<T> execs;
243};
244
245template <class T>
246class Workflow {
247public:
248 static constexpr std::size_t npos = static_cast<std::size_t>(-1);
249
250 explicit Workflow(const std::string& name) : name_(name) {}
251
252 const std::string& name() const { return name_; }
253
254 /** Add an activity; the name must be unique. */
255 std::size_t add_activity(const std::string& name, const Distrib<T>& host_demand) {
256 if (activity_map_.find(name) != activity_map_.end())
257 throw InputError("Workflow: activity '" + name + "' is already declared");
258 activities_.push_back(WorkflowActivity<T>(name, host_demand));
259 const std::size_t idx = activities_.size() - 1;
260 activity_map_[name] = idx;
262 return idx;
263 }
264
265 /** Add an activity with an exponential host demand of the given mean. */
266 std::size_t add_activity(const std::string& name, const T& mean) {
268 }
269
270 void add_precedence(const Precedence<T>& prec) {
271 precedences_.push_back(prec);
273 }
274
275 std::size_t num_activities() const { return activities_.size(); }
276 const std::vector<WorkflowActivity<T>>& activities() const { return activities_; }
277 const std::vector<Precedence<T>>& precedences() const { return precedences_; }
278
279 std::size_t activity_index(const std::string& name) const {
280 auto it = activity_map_.find(name);
281 return it == activity_map_.end() ? npos : it->second;
282 }
283
284 WorkflowActivity<T>& activity(const std::string& name) {
285 const std::size_t i = activity_index(name);
286 if (i == npos) throw InputError("Workflow: activity '" + name + "' not found");
287 return activities_[i];
288 }
289
290 /** Activity by index, the form a series-parallel LEAF node names it in. */
291 const WorkflowActivity<T>& activity_at(std::size_t i) const {
292 if (i >= activities_.size()) throw InputError("Workflow: activity index out of range");
293 return activities_[i];
294 }
295
296 /**
297 * Validate the workflow, throwing on the first defect.
298 *
299 * A quorum AND-join is refused here rather than composed as a full join.
300 */
301 void validate() const {
302 if (activities_.empty())
303 throw InputError("Workflow must have at least one activity.");
304
305 for (const Precedence<T>& prec : precedences_) {
306 for (const std::string& nm : prec.pre_acts)
307 if (activity_index(nm) == npos)
308 throw InputError("Activity '" + nm +
309 "' referenced in precedence not found in workflow.");
310 for (const std::string& nm : prec.post_acts)
311 if (activity_index(nm) == npos)
312 throw InputError("Activity '" + nm +
313 "' referenced in precedence not found in workflow.");
314 }
315
316 for (const Precedence<T>& prec : precedences_) {
317 if (prec.post_type == PrecedenceType::POST_OR) {
318 if (prec.post_params.empty())
319 throw InputError("OR-fork must have probabilities specified.");
320 T total = num_traits<T>::from_int(0);
321 for (const T& p : prec.post_params) total += p;
322 const double gap =
323 std::abs(num_traits<T>::to_double(total) - 1.0);
324 if (gap > GlobalConstants::FineTol)
325 throw InputError("OR-fork probabilities must sum to 1.");
326 }
327 if (prec.post_type == PrecedenceType::POST_LOOP) {
328 if (prec.post_params.size() != 1)
329 throw InputError("Loop count must be a single positive number.");
330 if (!(prec.post_params[0] > num_traits<T>::from_int(0)))
331 throw InputError("Loop count must be a positive number.");
332 }
333 if (prec.pre_type == PrecedenceType::PRE_AND && !prec.pre_params.empty()) {
334 const double quorum = num_traits<T>::to_double(prec.pre_params[0]);
335 const double nb = static_cast<double>(prec.pre_acts.size());
336 if (quorum > 0.0 && quorum < nb)
337 throw UnsupportedError(ErrorKind{"JoinPartial"},
338 "AND-join with quorum " + std::to_string(static_cast<long>(quorum)) +
339 " of " + std::to_string(static_cast<long>(nb)) +
340 " is not supported by Workflow: a partial join is not the maximum of the "
341 "branches. Use a full join, or SolverLN with method='default', which "
342 "routes the join explicitly.");
343 }
344 }
345 }
346
347 /**
348 * The composed law of the workflow.
349 *
350 * The generator is acyclic unless a geometric loop closes a cycle over a
351 * multi-phase body, which `is_acyclic_generator` reports; the returned
352 * Distrib is typed APH or PH accordingly.
353 */
355 if (cached_valid_) return cached_ph_;
356 validate();
357
358 PhLaw<T> law;
359 if (!compose_series_parallel(law)) {
360 // Not series-parallel: fall back to the block composition
361 law = build_ctmc();
362 }
363
364 cached_ph_ = Distrib<T>::phase_type(law.alpha, law.S, is_acyclic_generator(law.S));
365 cached_valid_ = true;
366 return cached_ph_;
367 }
368
369 /**
370 * Recompose the law after a demand change.
371 *
372 * Only the series-parallel nodes on the path from a dirty leaf to the root
373 * recompose; nodes whose subtree is unchanged keep their cached law. The
374 * topology is not rebuilt.
375 */
377
378 /**
379 * Draw `n` workflow execution times from the composed law.
380 *
381 * MATLAB samples `wf.toPH().sample(n)`, i.e. `map_sample` on the renewal
382 * MAP (D0 = S, D1 = (-S e) alpha), and native Python's `Workflow.sample`
383 * walks the same absorbing chain; this is that walk, starting each draw in
384 * a phase drawn from alpha (the renewal MAP's embedded stationary law).
385 * The generator follows the tree's Monte Carlo convention, a
386 * `pfqn::McRng` advanced by the call, so draws match MATLAB and numpy in
387 * distribution only, never digit for digit.
388 */
389 std::vector<T> sample(std::size_t n, pfqn::McRng& rng) {
390 const Distrib<T> d = to_ph();
391 mam::Map<T> m;
392 m.D0 = d.D0;
393 m.D1 = d.D1;
394 return mam::map_sample(m, n, rng, d.params);
395 }
396
397 /**
398 * Change the host demand of one activity.
399 *
400 * Marks only that leaf dirty, which is the entry point an iterative solver
401 * uses when it updates call-response laws at each iteration.
402 */
403 void set_activity_demand(const std::string& name, const Distrib<T>& host_demand) {
404 const std::size_t i = activity_index(name);
405 if (i == npos) throw InputError("Workflow: activity '" + name + "' not found");
406 activities_[i].set_host_demand(host_demand);
408 }
409
410 /**
411 * Change only the mean of one activity, preserving its shape.
412 *
413 * The law is scaled in time rather than refitted, so its SCV, its skewness
414 * and its order are preserved and the cached tree keeps its shape.
415 */
416 void set_activity_demand_mean(const std::string& name, const T& mean_value) {
417 if (!(mean_value > num_traits<T>::from_int(0)))
418 throw InputError("The activity mean must be a positive finite scalar.");
419 const std::size_t i = activity_index(name);
420 if (i == npos) throw InputError("Workflow: activity '" + name + "' not found");
421
422 const Distrib<T>& d = activities_[i].host_demand();
423 const T old_mean = d.mean;
424 if (d.type == ProcessType::IMMEDIATE ||
426 activities_[i].set_host_demand(Distrib<T>::exp_mean(mean_value));
428 return;
429 }
430
431 const T factor = T(old_mean / mean_value);
432 activities_[i].set_host_demand(lang::dist_scale_rate(d, factor));
433 // The SCV is invariant under a time scaling
434 rescale_activity_leaf(i, factor);
435 }
436
437 /** Discard the cached law and the decomposition. */
439 cached_valid_ = false;
440 sp_tree_.nodes.clear();
441 sp_tree_.root = npos;
442 sp_tree_.leaf_of.clear();
443 sp_tree_.execs.clear();
444 sp_built_ = false;
445 sp_failed_ = false;
446 }
447
448 /** Mark one activity law dirty, keeping every other cached block. */
449 void invalidate_activity(std::size_t act_idx) {
450 cached_valid_ = false;
451 if (!sp_built_) return;
452 if (act_idx >= sp_tree_.leaf_of.size() || sp_tree_.leaf_of[act_idx] == npos) {
453 // Activity outside the decomposition: rebuild it entirely
455 return;
456 }
457 invalidate_branch(sp_tree_, sp_tree_.leaf_of[act_idx]);
458 }
459
460 /**
461 * Time-scale a cached leaf in place: S -> S*FACTOR with alpha fixed.
462 *
463 * Ancestors still recompose, because they mix phases of several leaves,
464 * but the tree keeps its shape and no acyclic phase-type is refitted.
465 */
466 void rescale_activity_leaf(std::size_t act_idx, const T& factor) {
467 cached_valid_ = false;
468 if (!sp_built_) return;
469 if (act_idx >= sp_tree_.leaf_of.size() || sp_tree_.leaf_of[act_idx] == npos) {
471 return;
472 }
473 const std::size_t k = sp_tree_.leaf_of[act_idx];
474 invalidate_branch(sp_tree_, k);
475 SPNode<T>& node = sp_tree_.nodes[k];
476 if (node.law.S.rows() > 0) {
477 for (std::size_t i = 0; i < node.law.S.rows(); ++i)
478 for (std::size_t j = 0; j < node.law.S.cols(); ++j)
479 node.law.S(i, j) = T(node.law.S(i, j) * factor);
480 node.valid = true;
481 }
482 }
483
484 /**
485 * The cached series-parallel decomposition, or null when the precedence
486 * graph is not series-parallel.
487 */
489 if (!sp_built_ && !sp_failed_) build_sp_tree();
490 return sp_built_ ? &sp_tree_ : nullptr;
491 }
492
493 // -----------------------------------------------------------------
494 // Composition rules
495 // -----------------------------------------------------------------
496
497 /**
498 * Serial composition: the second law starts when the first absorbs.
499 *
500 * S = [S1, (-S1 e) alpha2; 0, S2]
501 *
502 * A defective alpha1 carries an atom at zero, which starts the second law
503 * immediately; this is `aph_simplify` pattern 1.
504 */
505 static PhLaw<T> compose_serial(const PhLaw<T>& a, const PhLaw<T>& b) {
506 const T zero = num_traits<T>::from_int(0);
507 const std::size_t n1 = a.S.rows(), n2 = b.S.rows();
508
509 PhLaw<T> out;
510 out.S = Matrix<T>(n1 + n2, n1 + n2, zero);
511 for (std::size_t i = 0; i < n1; ++i)
512 for (std::size_t j = 0; j < n1; ++j) out.S(i, j) = a.S(i, j);
513 for (std::size_t i = 0; i < n2; ++i)
514 for (std::size_t j = 0; j < n2; ++j) out.S(n1 + i, n1 + j) = b.S(i, j);
515
516 for (std::size_t i = 0; i < n1; ++i) {
517 T rate = zero;
518 for (std::size_t j = 0; j < n1; ++j) rate += a.S(i, j);
519 rate = T(-rate);
520 for (std::size_t j = 0; j < n2; ++j) out.S(i, n1 + j) = T(rate * b.alpha[j]);
521 }
522
523 T defect = num_traits<T>::from_int(1);
524 for (const T& v : a.alpha) defect -= v;
525 out.alpha.assign(n1 + n2, zero);
526 for (std::size_t i = 0; i < n1; ++i) out.alpha[i] = a.alpha[i];
527 for (std::size_t j = 0; j < n2; ++j) out.alpha[n1 + j] = T(defect * b.alpha[j]);
528 return out;
529 }
530
531 /**
532 * Parallel (AND-fork/join) composition: the time until BOTH complete.
533 *
534 * States (i,j) with both active carry the Kronecker sum S1 (+) S2; when one
535 * branch absorbs the chain moves into that branch's own survivor block, so
536 * the law is the maximum of the two.
537 */
538 static PhLaw<T> compose_parallel(const PhLaw<T>& a, const PhLaw<T>& b) {
539 const T zero = num_traits<T>::from_int(0);
540 const std::size_t n1 = a.S.rows(), n2 = b.S.rows();
541 const std::size_t nboth = n1 * n2;
542 const std::size_t ntot = nboth + n1 + n2;
543
544 std::vector<T> abs1(n1, zero), abs2(n2, zero);
545 for (std::size_t i = 0; i < n1; ++i) {
546 T r = zero;
547 for (std::size_t j = 0; j < n1; ++j) r += a.S(i, j);
548 abs1[i] = T(-r);
549 }
550 for (std::size_t i = 0; i < n2; ++i) {
551 T r = zero;
552 for (std::size_t j = 0; j < n2; ++j) r += b.S(i, j);
553 abs2[i] = T(-r);
554 }
555
556 PhLaw<T> out;
557 out.S = Matrix<T>(ntot, ntot, zero);
558
559 // Kronecker sum on the block where both are still running
560 for (std::size_t i = 0; i < n1; ++i)
561 for (std::size_t j = 0; j < n2; ++j) {
562 const std::size_t r = i * n2 + j;
563 for (std::size_t ii = 0; ii < n1; ++ii)
564 out.S(r, ii * n2 + j) += a.S(i, ii);
565 for (std::size_t jj = 0; jj < n2; ++jj)
566 out.S(r, i * n2 + jj) += b.S(j, jj);
567 // one branch absorbs, the other keeps running
568 out.S(r, nboth + i) += abs2[j];
569 out.S(r, nboth + n1 + j) += abs1[i];
570 }
571
572 for (std::size_t i = 0; i < n1; ++i)
573 for (std::size_t j = 0; j < n1; ++j) out.S(nboth + i, nboth + j) = a.S(i, j);
574 for (std::size_t i = 0; i < n2; ++i)
575 for (std::size_t j = 0; j < n2; ++j)
576 out.S(nboth + n1 + i, nboth + n1 + j) = b.S(i, j);
577
578 out.alpha.assign(ntot, zero);
579 for (std::size_t i = 0; i < n1; ++i)
580 for (std::size_t j = 0; j < n2; ++j)
581 out.alpha[i * n2 + j] = T(a.alpha[i] * b.alpha[j]);
582 return out;
583 }
584
585 /**
586 * Probabilistic mixture: a block-diagonal generator whose initial vector
587 * picks branch i with probability PROBS[i]. `aph_simplify` pattern 3,
588 * generalised to any number of branches.
589 */
590 static PhLaw<T> compose_mixture(const std::vector<PhLaw<T>>& laws,
591 const std::vector<T>& probs) {
592 const T zero = num_traits<T>::from_int(0);
593 std::size_t total = 0;
594 for (const PhLaw<T>& l : laws) total += l.S.rows();
595
596 PhLaw<T> out;
597 out.S = Matrix<T>(total, total, zero);
598 out.alpha.assign(total, zero);
599
600 std::size_t off = 0;
601 for (std::size_t b = 0; b < laws.size(); ++b) {
602 const std::size_t nb = laws[b].S.rows();
603 for (std::size_t i = 0; i < nb; ++i) {
604 for (std::size_t j = 0; j < nb; ++j) out.S(off + i, off + j) = laws[b].S(i, j);
605 out.alpha[off + i] = T(probs[b] * laws[b].alpha[i]);
606 }
607 off += nb;
608 }
609 return out;
610 }
611
612 /**
613 * Geometric repetition of a phase-type law, the POST_LOOP semantics.
614 *
615 * For COUNT >= 1 the body runs at least once and repeats on absorption
616 * with probability P = 1-1/COUNT, so
617 *
618 * S_out = S + P/D (-S e) alpha, alpha_out = alpha / D
619 *
620 * with D = 1 - P(1 - alpha e) the correction for an atom at zero in alpha.
621 * The ORDER is that of the body, unlike the COUNT-fold convolution, and the
622 * mean is COUNT times the body mean in both cases.
623 *
624 * For COUNT < 1 the body runs at most once, with probability COUNT; the
625 * skipped branch is an immediate phase.
626 */
627 static PhLaw<T> compose_loop_geometric(const PhLaw<T>& body, const T& count) {
628 const T zero = num_traits<T>::from_int(0);
629 const T one = num_traits<T>::from_int(1);
630 const std::size_t n = body.S.rows();
631 const double c = num_traits<T>::to_double(count);
632
633 PhLaw<T> out;
634 if (!(c > 0.0)) {
635 out.alpha.assign(1, one);
636 out.S = Matrix<T>(1, 1, zero);
638 return out; // zero-time branch
639 }
640
641 if (std::abs(c - 1.0) <= GlobalConstants::FineTol) return body;
642
643 if (c < 1.0) {
644 // Executed with probability COUNT, skipped otherwise
645 out.alpha.assign(n + 1, zero);
646 for (std::size_t i = 0; i < n; ++i) out.alpha[i] = T(count * body.alpha[i]);
647 out.alpha[n] = T(one - count);
648 out.S = Matrix<T>(n + 1, n + 1, zero);
649 for (std::size_t i = 0; i < n; ++i)
650 for (std::size_t j = 0; j < n; ++j) out.S(i, j) = body.S(i, j);
652 return out; // zero-time skip branch
653 }
654
655 const T p = T(one - one / count);
656 T defect = one;
657 for (const T& v : body.alpha) defect -= v;
658 const T denom = T(one - p * defect);
659
660 out.alpha.assign(n, zero);
661 for (std::size_t i = 0; i < n; ++i) out.alpha[i] = T(body.alpha[i] / denom);
662
663 out.S = body.S;
664 for (std::size_t i = 0; i < n; ++i) {
665 T rate = zero;
666 for (std::size_t j = 0; j < n; ++j) rate += body.S(i, j);
667 rate = T(-rate * p / denom);
668 for (std::size_t j = 0; j < n; ++j) out.S(i, j) += T(rate * body.alpha[j]);
669 }
670 return out;
671 }
672
673 /**
674 * COUNT-fold convolution of a phase-type law.
675 *
676 * The DETERMINISTIC repetition, kept for a caller that genuinely wants an
677 * exact number of executions. POST_LOOP is geometric and uses
678 * `compose_loop_geometric` instead.
679 */
680 static PhLaw<T> compose_repeat(const PhLaw<T>& body, long count) {
681 if (count <= 0) {
682 PhLaw<T> out;
683 out.alpha.assign(1, num_traits<T>::from_int(1));
684 out.S = Matrix<T>(1, 1, num_traits<T>::from_int(0));
686 return out;
687 }
688 PhLaw<T> out = body;
689 for (long i = 1; i < count; ++i) out = compose_serial(out, body);
690 return out;
691 }
692
693 /**
694 * True when the phase graph of S has no cycle.
695 *
696 * A geometric loop over a body of two or more phases closes a cycle, so the
697 * composed law is a PH and not an APH.
698 */
699 static bool is_acyclic_generator(const Matrix<T>& S) {
700 const std::size_t n = S.rows();
701 std::vector<std::vector<bool>> A(n, std::vector<bool>(n, false));
702 std::vector<std::size_t> in_deg(n, 0);
703 for (std::size_t i = 0; i < n; ++i)
704 for (std::size_t j = 0; j < n; ++j) {
705 if (i == j) continue;
706 if (std::abs(num_traits<T>::to_double(S(i, j))) > GlobalConstants::ArcTol) {
707 A[i][j] = true;
708 ++in_deg[j];
709 }
710 }
711
712 std::vector<std::size_t> queue;
713 for (std::size_t i = 0; i < n; ++i)
714 if (in_deg[i] == 0) queue.push_back(i);
715 std::size_t visited = 0, head = 0;
716 while (head < queue.size()) {
717 const std::size_t cur = queue[head++];
718 ++visited;
719 for (std::size_t j = 0; j < n; ++j) {
720 if (!A[cur][j]) continue;
721 if (--in_deg[j] == 0) queue.push_back(j);
722 }
723 }
724 return visited == n;
725 }
726
727 // -----------------------------------------------------------------
728 // Precedence factories, named as in MATLAB and the JAR
729 // -----------------------------------------------------------------
730
731 static Precedence<T> Serial(const std::string& pre, const std::string& post) {
733 p.pre_acts.push_back(pre);
734 p.post_acts.push_back(post);
735 p.pre_type = PrecedenceType::PRE_SEQ;
736 p.post_type = PrecedenceType::POST_SEQ;
737 return p;
738 }
739
740 static std::vector<Precedence<T>> SerialSequence(const std::vector<std::string>& acts) {
741 std::vector<Precedence<T>> out;
742 for (std::size_t i = 0; i + 1 < acts.size(); ++i)
743 out.push_back(Serial(acts[i], acts[i + 1]));
744 return out;
745 }
746
747 static Precedence<T> AndFork(const std::string& pre,
748 const std::vector<std::string>& posts) {
750 p.pre_acts.push_back(pre);
751 p.post_acts = posts;
752 p.pre_type = PrecedenceType::PRE_SEQ;
753 p.post_type = PrecedenceType::POST_AND;
754 return p;
755 }
756
757 /** An empty QUORUM means a full join; a partial one is refused by validate. */
758 static Precedence<T> AndJoin(const std::vector<std::string>& pres,
759 const std::string& post,
760 const std::vector<T>& quorum = std::vector<T>()) {
762 p.pre_acts = pres;
763 p.post_acts.push_back(post);
764 p.pre_type = PrecedenceType::PRE_AND;
765 p.post_type = PrecedenceType::POST_SEQ;
766 p.pre_params = quorum;
767 return p;
768 }
769
770 static Precedence<T> OrFork(const std::string& pre, const std::vector<std::string>& posts,
771 const std::vector<T>& probs) {
773 p.pre_acts.push_back(pre);
774 p.post_acts = posts;
775 p.pre_type = PrecedenceType::PRE_SEQ;
776 p.post_type = PrecedenceType::POST_OR;
777 p.post_params = probs;
778 return p;
779 }
780
781 static Precedence<T> OrJoin(const std::vector<std::string>& pres,
782 const std::string& post) {
784 p.pre_acts = pres;
785 p.post_acts.push_back(post);
786 p.pre_type = PrecedenceType::PRE_OR;
787 p.post_type = PrecedenceType::POST_SEQ;
788 return p;
789 }
790
791 /**
792 * A loop: PRE runs once, then POSTS[0..n-2] repeat a geometric number of
793 * times of mean COUNT and POSTS[n-1] continues after the loop.
794 */
795 static Precedence<T> Loop(const std::string& pre, const std::vector<std::string>& posts,
796 const T& count) {
798 p.pre_acts.push_back(pre);
799 p.post_acts = posts;
800 p.pre_type = PrecedenceType::PRE_SEQ;
801 p.post_type = PrecedenceType::POST_LOOP;
802 p.post_params.push_back(count);
803 return p;
804 }
805
806private:
807 // -----------------------------------------------------------------
808 // Series-parallel decomposition
809 // -----------------------------------------------------------------
810
811 /** How a parsed sequence terminated. */
812 enum class ParseStatus { END, STOP, JOIN, FAIL };
813
814 struct ParseState {
815 /** Index of the precedence each activity heads / is reached by. */
816 std::vector<std::size_t> out_p, in_p;
817 std::vector<bool> consumed;
818 };
819
820 bool compose_series_parallel(PhLaw<T>& out) {
821 if (!sp_built_) {
822 if (sp_failed_) return false;
823 build_sp_tree();
824 if (!sp_built_) return false;
825 }
826 out = compose_node(sp_tree_.root);
827 return true;
828 }
829
830 /**
831 * Decompose the precedence graph into a series-parallel tree.
832 *
833 * The decomposition is attempted once per topology: on failure `sp_failed_`
834 * is set and the block path takes over.
835 */
836 bool build_sp_tree() {
837 sp_tree_.nodes.clear();
838 sp_tree_.root = npos;
839 sp_tree_.leaf_of.clear();
840 sp_tree_.execs.clear();
841 sp_built_ = false;
842 sp_failed_ = true;
843
844 const std::size_t n = activities_.size();
845 if (n == 0) return false;
846
847 ParseState S;
848 S.out_p.assign(n, npos);
849 S.in_p.assign(n, npos);
850 S.consumed.assign(n, false);
851
852 // An activity may head at most one precedence and be reached by at most
853 // one precedence; otherwise the graph is not series-parallel
854 for (std::size_t p = 0; p < precedences_.size(); ++p) {
855 for (const std::string& nm : precedences_[p].pre_acts) {
856 const std::size_t i = activity_index(nm);
857 if (i == npos || S.out_p[i] != npos) return false;
858 S.out_p[i] = p;
859 }
860 for (const std::string& nm : precedences_[p].post_acts) {
861 const std::size_t j = activity_index(nm);
862 if (j == npos || S.in_p[j] != npos) return false;
863 S.in_p[j] = p;
864 }
865 }
866
867 std::vector<std::size_t> starts;
868 for (std::size_t i = 0; i < n; ++i)
869 if (S.in_p[i] == npos) starts.push_back(i);
870 if (starts.size() != 1) return false;
871
872 std::vector<std::size_t> kids;
873 std::size_t stop_at = npos;
874 const ParseStatus st = sp_parse_seq(S, starts[0], std::vector<std::size_t>(), kids, stop_at);
875 if (st != ParseStatus::END) return false;
876 for (std::size_t i = 0; i < n; ++i)
877 if (!S.consumed[i]) return false;
878
879 const std::size_t root = sp_serial_node(kids);
880 if (root == npos) return false;
881
882 sp_tree_.root = root;
883 sp_tree_.leaf_of.assign(n, npos);
884 for (std::size_t k = 0; k < sp_tree_.nodes.size(); ++k)
885 if (sp_tree_.nodes[k].type == SPNodeType::LEAF)
886 sp_tree_.leaf_of[sp_tree_.nodes[k].act] = k;
887 sp_tree_.execs = sp_execution_counts(sp_tree_);
888
889 sp_built_ = true;
890 sp_failed_ = false;
891 return true;
892 }
893
894 /** Parse a maximal sequence of blocks starting at CUR. */
895 ParseStatus sp_parse_seq(ParseState& S, std::size_t cur,
896 const std::vector<std::size_t>& stop_set,
897 std::vector<std::size_t>& kids, std::size_t& stop_at) {
898 stop_at = npos;
899 while (true) {
900 if (cur == npos) return ParseStatus::END;
901 if (std::find(stop_set.begin(), stop_set.end(), cur) != stop_set.end()) {
902 stop_at = cur;
903 return ParseStatus::STOP;
904 }
905 if (S.consumed[cur]) return ParseStatus::FAIL;
906 S.consumed[cur] = true;
907 kids.push_back(sp_add_node(SPNodeType::LEAF, cur, std::vector<std::size_t>(),
908 std::vector<T>(), num_traits<T>::from_int(0)));
909
910 const std::size_t p = S.out_p[cur];
911 if (p == npos) return ParseStatus::END;
912 const Precedence<T>& prec = precedences_[p];
913 if (prec.pre_acts.size() > 1) {
914 // CUR is the tail of a branch: the caller composes the join
915 stop_at = p;
916 return ParseStatus::JOIN;
917 }
918
919 std::vector<std::size_t> post_inds = sp_indices_of(prec.post_acts);
920 for (std::size_t i : post_inds)
921 if (i == npos) return ParseStatus::FAIL;
922
923 std::size_t knode = npos, next_act = npos;
924 switch (prec.post_type) {
925 case PrecedenceType::POST_AND:
926 if (!sp_parse_fork(S, post_inds, std::vector<T>(), stop_set, true, knode,
927 next_act))
928 return ParseStatus::FAIL;
929 kids.push_back(knode);
930 cur = next_act;
931 break;
932 case PrecedenceType::POST_OR:
933 if (prec.post_params.size() != post_inds.size()) return ParseStatus::FAIL;
934 if (!sp_parse_fork(S, post_inds, prec.post_params, stop_set, false, knode,
935 next_act))
936 return ParseStatus::FAIL;
937 kids.push_back(knode);
938 cur = next_act;
939 break;
940 case PrecedenceType::POST_LOOP:
941 if (!sp_parse_loop(S, post_inds, prec.post_params, stop_set, knode, next_act))
942 return ParseStatus::FAIL;
943 kids.push_back(knode);
944 cur = next_act;
945 break;
946 case PrecedenceType::POST_SEQ:
947 if (post_inds.size() != 1) return ParseStatus::FAIL;
948 cur = post_inds[0];
949 break;
950 default:
951 // POST_CACHE and any other pattern is not a workflow
952 // composition rule
953 return ParseStatus::FAIL;
954 }
955 }
956 }
957
958 /** Parse the branches of a fork and their join. */
959 bool sp_parse_fork(ParseState& S, const std::vector<std::size_t>& branch_heads,
960 const std::vector<T>& probs, const std::vector<std::size_t>& stop_set,
961 bool is_and, std::size_t& knode, std::size_t& next_act) {
962 const std::size_t nb = branch_heads.size();
963 std::vector<std::size_t> branch_nodes(nb, npos), bstop(nb, npos);
964 std::vector<ParseStatus> bstatus(nb, ParseStatus::FAIL);
965
966 for (std::size_t b = 0; b < nb; ++b) {
967 std::vector<std::size_t> bkids;
968 std::size_t sa = npos;
969 const ParseStatus st = sp_parse_seq(S, branch_heads[b], stop_set, bkids, sa);
970 if (st == ParseStatus::FAIL) return false;
971 const std::size_t bn = sp_serial_node(bkids);
972 if (bn == npos) return false;
973 branch_nodes[b] = bn;
974 bstatus[b] = st;
975 bstop[b] = sa;
976 }
977
978 const bool all_join =
979 std::all_of(bstatus.begin(), bstatus.end(),
980 [](ParseStatus s) { return s == ParseStatus::JOIN; });
981 const bool all_end = std::all_of(bstatus.begin(), bstatus.end(),
982 [](ParseStatus s) { return s == ParseStatus::END; });
983 const bool all_stop = std::all_of(bstatus.begin(), bstatus.end(),
984 [](ParseStatus s) { return s == ParseStatus::STOP; });
985 const bool same_stop =
986 std::all_of(bstop.begin(), bstop.end(),
987 [&bstop](std::size_t x) { return x == bstop[0]; });
988
989 if (all_join) {
990 if (!same_stop) return false;
991 const Precedence<T>& join_prec = precedences_[bstop[0]];
992 if (join_prec.pre_acts.size() != nb) return false;
993 if (is_and) {
994 if (join_prec.pre_type != PrecedenceType::PRE_AND) return false;
995 } else {
996 if (join_prec.pre_type != PrecedenceType::PRE_OR) return false;
997 }
998 const std::vector<std::size_t> post_inds = sp_indices_of(join_prec.post_acts);
999 if (post_inds.size() != 1 || post_inds[0] == npos) return false;
1000 next_act = post_inds[0];
1001 } else if (all_end) {
1002 // Branches terminate the workflow. An AND-fork with no join still
1003 // synchronises at the end of the workflow
1004 next_act = npos;
1005 } else if (!is_and && all_stop && same_stop) {
1006 next_act = bstop[0];
1007 } else {
1008 return false;
1009 }
1010
1011 knode = sp_add_node(is_and ? SPNodeType::PAR : SPNodeType::OR, npos, branch_nodes, probs,
1012 num_traits<T>::from_int(0));
1013 return true;
1014 }
1015
1016 /**
1017 * Parse a loop block: the last post activity continues after the loop, the
1018 * others form the body.
1019 */
1020 bool sp_parse_loop(ParseState& S, const std::vector<std::size_t>& post_inds,
1021 const std::vector<T>& counts, const std::vector<std::size_t>& stop_set,
1022 std::size_t& knode, std::size_t& next_act) {
1023 if (counts.size() != 1) return false;
1024 const T count = counts[0];
1025
1026 std::vector<std::size_t> body_acts;
1027 std::size_t end_act = npos;
1028 if (post_inds.size() >= 2) {
1029 body_acts.assign(post_inds.begin(), post_inds.end() - 1);
1030 end_act = post_inds.back();
1031 } else {
1032 body_acts.push_back(post_inds[0]);
1033 }
1034
1035 std::vector<std::size_t> loop_stop = stop_set;
1036 loop_stop.insert(loop_stop.end(), body_acts.begin(), body_acts.end());
1037 if (end_act != npos) loop_stop.push_back(end_act);
1038
1039 std::vector<std::size_t> body_kids;
1040 std::size_t j = 0;
1041 while (j < body_acts.size()) {
1042 const std::size_t a = body_acts[j];
1043 if (S.consumed[a]) {
1044 ++j;
1045 continue;
1046 }
1047 std::vector<std::size_t> this_stop;
1048 for (std::size_t x : loop_stop)
1049 if (x != a) this_stop.push_back(x);
1050
1051 std::vector<std::size_t> kk;
1052 std::size_t sa = npos;
1053 const ParseStatus st = sp_parse_seq(S, a, this_stop, kk, sa);
1054 if (st == ParseStatus::FAIL) return false;
1055 body_kids.insert(body_kids.end(), kk.begin(), kk.end());
1056
1057 if (st == ParseStatus::END) {
1058 ++j;
1059 } else if (st == ParseStatus::STOP) {
1060 const auto it = std::find(body_acts.begin(), body_acts.end(), sa);
1061 if (it != body_acts.end()) {
1062 j = static_cast<std::size_t>(it - body_acts.begin());
1063 } else if (end_act != npos && sa == end_act) {
1064 j = body_acts.size();
1065 } else {
1066 return false;
1067 }
1068 } else {
1069 // A join reached from inside the body crosses the loop
1070 // boundary, so the graph is not series-parallel
1071 return false;
1072 }
1073 }
1074
1075 const std::size_t body_node = sp_serial_node(body_kids);
1076 if (body_node == npos) return false;
1077
1078 knode = sp_add_node(SPNodeType::LOOP, npos, std::vector<std::size_t>(1, body_node),
1079 std::vector<T>(), count);
1080 next_act = end_act;
1081 return true;
1082 }
1083
1084 /** Wrap a list of nodes in a serial node; a single node is returned as is. */
1085 std::size_t sp_serial_node(const std::vector<std::size_t>& kids) {
1086 if (kids.empty()) return npos;
1087 if (kids.size() == 1) return kids[0];
1088 return sp_add_node(SPNodeType::SERIAL, npos, kids, std::vector<T>(),
1089 num_traits<T>::from_int(0));
1090 }
1091
1092 std::size_t sp_add_node(SPNodeType type, std::size_t act,
1093 const std::vector<std::size_t>& kids, const std::vector<T>& probs,
1094 const T& count) {
1095 SPNode<T> node;
1096 node.type = type;
1097 node.act = act;
1098 node.kids = kids;
1099 node.probs = probs;
1100 node.count = count;
1101 sp_tree_.nodes.push_back(node);
1102 const std::size_t k = sp_tree_.nodes.size() - 1;
1103 for (std::size_t c : kids) sp_tree_.nodes[c].parent = k;
1104 return k;
1105 }
1106
1107 std::vector<std::size_t> sp_indices_of(const std::vector<std::string>& names) const {
1108 std::vector<std::size_t> out(names.size(), npos);
1109 for (std::size_t i = 0; i < names.size(); ++i) out[i] = activity_index(names[i]);
1110 return out;
1111 }
1112
1113 /**
1114 * Compose one node. A cached node is returned untouched, so a demand change
1115 * only recomposes the path from the dirty leaf to the root.
1116 */
1117 PhLaw<T> compose_node(std::size_t k) {
1118 SPNode<T>& node = sp_tree_.nodes[k];
1119 if (node.valid) return node.law;
1120
1121 PhLaw<T> law;
1122 switch (node.type) {
1123 case SPNodeType::LEAF:
1124 law = activities_[node.act].ph_representation();
1125 break;
1126 case SPNodeType::SERIAL: {
1127 const std::vector<std::size_t> kids = node.kids;
1128 law = compose_node(kids[0]);
1129 for (std::size_t i = 1; i < kids.size(); ++i)
1130 law = compose_serial(law, compose_node(kids[i]));
1131 break;
1132 }
1133 case SPNodeType::PAR: {
1134 const std::vector<std::size_t> kids = node.kids;
1135 law = compose_node(kids[0]);
1136 for (std::size_t i = 1; i < kids.size(); ++i)
1137 law = compose_parallel(law, compose_node(kids[i]));
1138 break;
1139 }
1140 case SPNodeType::OR: {
1141 const std::vector<std::size_t> kids = node.kids;
1142 std::vector<PhLaw<T>> laws;
1143 for (std::size_t c : kids) laws.push_back(compose_node(c));
1144 law = compose_mixture(laws, sp_tree_.nodes[k].probs);
1145 break;
1146 }
1147 case SPNodeType::LOOP: {
1148 const std::size_t child = node.kids[0];
1149 law = compose_loop_geometric(compose_node(child), sp_tree_.nodes[k].count);
1150 break;
1151 }
1152 }
1153
1154 sp_tree_.nodes[k].law = law;
1155 sp_tree_.nodes[k].valid = true;
1156 return law;
1157 }
1158
1159 static void invalidate_branch(SPTree<T>& tree, std::size_t k) {
1160 while (k != npos) {
1161 tree.nodes[k].valid = false;
1162 k = tree.nodes[k].parent;
1163 }
1164 }
1165
1166 /**
1167 * Expected executions of each node per workflow run.
1168 *
1169 * Serial and parallel children inherit the count of their parent, an OR
1170 * branch is weighted by its probability, and a loop body by the loop count.
1171 */
1172 static std::vector<T> sp_execution_counts(const SPTree<T>& tree) {
1173 std::vector<T> execs(tree.nodes.size(), num_traits<T>::from_int(0));
1174 if (tree.root == npos) return execs;
1175 execs[tree.root] = num_traits<T>::from_int(1);
1176 std::vector<std::size_t> stack(1, tree.root);
1177 while (!stack.empty()) {
1178 const std::size_t k = stack.back();
1179 stack.pop_back();
1180 const SPNode<T>& node = tree.nodes[k];
1181 for (std::size_t i = 0; i < node.kids.size(); ++i) {
1182 const std::size_t c = node.kids[i];
1183 if (node.type == SPNodeType::OR) {
1184 execs[c] = T(execs[k] * node.probs[i]);
1185 } else if (node.type == SPNodeType::LOOP) {
1186 execs[c] = T(execs[k] * node.count);
1187 } else {
1188 execs[c] = execs[k];
1189 }
1190 stack.push_back(c);
1191 }
1192 }
1193 return execs;
1194 }
1195
1196 // -----------------------------------------------------------------
1197 // Block composition, the fallback for a graph that is not series-parallel
1198 // -----------------------------------------------------------------
1199
1200 struct ForkInfo {
1201 bool is_and = true;
1202 std::size_t pre_act = npos;
1203 std::vector<std::size_t> post_acts;
1204 std::vector<T> probs;
1205 };
1206
1207 struct JoinInfo {
1208 bool is_and = true;
1209 std::vector<std::size_t> pre_acts;
1210 std::size_t post_act = npos;
1211 };
1212
1213 struct LoopInfo {
1214 std::size_t pre_act = npos;
1215 std::vector<std::size_t> body_acts;
1216 std::size_t end_act = npos;
1217 T count = num_traits<T>::from_int(1);
1218 };
1219
1220 struct Structure {
1221 std::vector<std::vector<std::size_t>> adj;
1222 std::vector<std::size_t> in_deg, out_deg;
1223 std::vector<ForkInfo> forks;
1224 std::vector<JoinInfo> joins;
1225 std::vector<LoopInfo> loops;
1226 };
1227
1228 Structure analyze_structure() const {
1229 const std::size_t n = activities_.size();
1230 Structure st;
1231 st.adj.assign(n, std::vector<std::size_t>());
1232 st.in_deg.assign(n, 0);
1233 st.out_deg.assign(n, 0);
1234
1235 for (const Precedence<T>& prec : precedences_) {
1236 const std::vector<std::size_t> pre = sp_indices_of(prec.pre_acts);
1237 const std::vector<std::size_t> post = sp_indices_of(prec.post_acts);
1238 for (std::size_t i : pre)
1239 for (std::size_t j : post) {
1240 st.adj[i].push_back(j);
1241 ++st.out_deg[i];
1242 ++st.in_deg[j];
1243 }
1244
1245 if (prec.post_type == PrecedenceType::POST_AND) {
1246 ForkInfo f;
1247 f.is_and = true;
1248 f.pre_act = pre[0];
1249 f.post_acts = post;
1250 st.forks.push_back(f);
1251 } else if (prec.post_type == PrecedenceType::POST_OR) {
1252 ForkInfo f;
1253 f.is_and = false;
1254 f.pre_act = pre[0];
1255 f.post_acts = post;
1256 f.probs = prec.post_params;
1257 st.forks.push_back(f);
1258 } else if (prec.post_type == PrecedenceType::POST_LOOP) {
1259 LoopInfo l;
1260 l.pre_act = pre[0];
1261 if (post.size() > 1) {
1262 l.body_acts.assign(post.begin(), post.end() - 1);
1263 l.end_act = post.back();
1264 } else {
1265 l.body_acts = post;
1266 }
1267 l.count = prec.post_params.empty() ? num_traits<T>::from_int(1)
1268 : prec.post_params[0];
1269 st.loops.push_back(l);
1270 }
1271
1272 if (prec.pre_type == PrecedenceType::PRE_AND ||
1273 prec.pre_type == PrecedenceType::PRE_OR) {
1274 JoinInfo j;
1275 j.is_and = prec.pre_type == PrecedenceType::PRE_AND;
1276 j.pre_acts = pre;
1277 j.post_act = post[0];
1278 st.joins.push_back(j);
1279 }
1280 }
1281 return st;
1282 }
1283
1284 std::vector<std::size_t> topological_sort(
1285 const std::vector<std::vector<std::size_t>>& adj) const {
1286 const std::size_t n = activities_.size();
1287 std::vector<std::size_t> in_deg(n, 0);
1288 for (const std::vector<std::size_t>& nbrs : adj)
1289 for (std::size_t j : nbrs) ++in_deg[j];
1290
1291 std::vector<std::size_t> queue, order;
1292 for (std::size_t i = 0; i < n; ++i)
1293 if (in_deg[i] == 0) queue.push_back(i);
1294 std::size_t head = 0;
1295 while (head < queue.size()) {
1296 const std::size_t cur = queue[head++];
1297 order.push_back(cur);
1298 for (std::size_t nx : adj[cur])
1299 if (--in_deg[nx] == 0) queue.push_back(nx);
1300 }
1301 std::vector<bool> seen(n, false);
1302 for (std::size_t i : order) seen[i] = true;
1303 for (std::size_t i = 0; i < n; ++i)
1304 if (!seen[i]) order.push_back(i);
1305 return order;
1306 }
1307
1308 /**
1309 * The block composition.
1310 *
1311 * A HEURISTIC, and the reason the series-parallel reduction exists: it
1312 * folds each fork/join and loop block independently and then chains what is
1313 * left in topological order, so a block nested inside another is not
1314 * reduced exactly.
1315 */
1316 PhLaw<T> build_ctmc() {
1317 const std::size_t n = activities_.size();
1318 if (n == 1) return activities_[0].ph_representation();
1319
1320 const Structure st = analyze_structure();
1321
1322 std::vector<PhLaw<T>> block(n);
1323 std::vector<bool> absorbed(n, false);
1324 for (std::size_t i = 0; i < n; ++i) block[i] = activities_[i].ph_representation();
1325
1326 for (const LoopInfo& loop : st.loops) {
1327 PhLaw<T> body = activities_[loop.body_acts[0]].ph_representation();
1328 for (std::size_t j = 1; j < loop.body_acts.size(); ++j)
1329 body = compose_serial(body, activities_[loop.body_acts[j]].ph_representation());
1330
1331 PhLaw<T> res = compose_serial(block[loop.pre_act],
1332 compose_loop_geometric(body, loop.count));
1333 if (loop.end_act != npos) {
1334 res = compose_serial(res, activities_[loop.end_act].ph_representation());
1335 absorbed[loop.end_act] = true;
1336 }
1337 block[loop.pre_act] = res;
1338 for (std::size_t idx : loop.body_acts) absorbed[idx] = true;
1339 }
1340
1341 for (const ForkInfo& fork : st.forks) {
1342 const JoinInfo* join = find_matching_join(fork.post_acts, st.joins, fork.is_and);
1343 if (fork.is_and && join == nullptr) continue;
1344
1345 PhLaw<T> inner;
1346 if (fork.is_and) {
1347 inner = block[fork.post_acts[0]];
1348 for (std::size_t i = 1; i < fork.post_acts.size(); ++i)
1349 inner = compose_parallel(inner, block[fork.post_acts[i]]);
1350 } else {
1351 std::vector<PhLaw<T>> laws;
1352 for (std::size_t idx : fork.post_acts) laws.push_back(block[idx]);
1353 inner = compose_mixture(laws, fork.probs);
1354 }
1355
1356 PhLaw<T> res = compose_serial(block[fork.pre_act], inner);
1357 if (join != nullptr && !absorbed[join->post_act]) {
1358 res = compose_serial(res, block[join->post_act]);
1359 absorbed[join->post_act] = true;
1360 }
1361 block[fork.pre_act] = res;
1362 for (std::size_t idx : fork.post_acts) absorbed[idx] = true;
1363 }
1364
1365 const std::vector<std::size_t> order = topological_sort(st.adj);
1366 bool started = false;
1367 PhLaw<T> out;
1368 for (std::size_t idx : order) {
1369 if (absorbed[idx]) continue;
1370 if (!started) {
1371 out = block[idx];
1372 started = true;
1373 } else {
1374 out = compose_serial(out, block[idx]);
1375 }
1376 }
1377 if (!started) out = activities_[0].ph_representation();
1378 return out;
1379 }
1380
1381 static const JoinInfo* find_matching_join(const std::vector<std::size_t>& post_acts,
1382 const std::vector<JoinInfo>& joins, bool is_and) {
1383 std::vector<std::size_t> want = post_acts;
1384 std::sort(want.begin(), want.end());
1385 for (const JoinInfo& j : joins) {
1386 if (j.is_and != is_and) continue;
1387 std::vector<std::size_t> have = j.pre_acts;
1388 std::sort(have.begin(), have.end());
1389 if (have == want) return &j;
1390 }
1391 return nullptr;
1392 }
1393
1394 std::string name_;
1395 std::vector<WorkflowActivity<T>> activities_;
1396 std::map<std::string, std::size_t> activity_map_;
1397 std::vector<Precedence<T>> precedences_;
1398
1399 Distrib<T> cached_ph_;
1400 bool cached_valid_ = false;
1401 SPTree<T> sp_tree_;
1402 bool sp_built_ = false;
1403 bool sp_failed_ = false;
1404};
1405
1406} // namespace workflow
1407} // namespace line
1408
1409#endif // LINE_LANG_WORKFLOW_WORKFLOW_H
InputError(const std::string &what)
Definition error.h:105
std::size_t rows() const
Definition matrix.h:89
UnsupportedError(const std::string &what)
Definition error.h:119
Workflow(const std::string &name)
Definition workflow.h:250
A computational activity.
Definition workflow.h:102
void set_metadata(const std::map< std::string, std::string > &m)
Definition workflow.h:171
WorkflowActivity(const std::string &name, const Distrib< T > &host_demand)
Definition workflow.h:108
void set_host_demand(const Distrib< T > &d)
Definition workflow.h:114
const std::string & name() const
Definition workflow.h:111
static constexpr std::size_t kDetPhases
Order of the Erlang surrogate of a deterministic host demand (sn_nonmarkov_toph's default nonmkvorder...
Definition workflow.h:105
std::size_t num_phases() const
Definition workflow.h:160
const std::map< std::string, std::string > & metadata() const
Optional external metadata, MATLAB's act.metadata and the JAR's getMetadata().
Definition workflow.h:170
PhLaw< T > ph_representation() const
The (alpha, T) pair of this activity.
Definition workflow.h:127
const Distrib< T > & host_demand() const
Definition workflow.h:113
static bool is_acyclic_generator(const Matrix< T > &S)
True when the phase graph of S has no cycle.
Definition workflow.h:699
static Precedence< T > Loop(const std::string &pre, const std::vector< std::string > &posts, const T &count)
A loop: PRE runs once, then POSTS[0..n-2] repeat a geometric number of times of mean COUNT and POSTS[...
Definition workflow.h:795
static Precedence< T > AndJoin(const std::vector< std::string > &pres, const std::string &post, const std::vector< T > &quorum=std::vector< T >())
An empty QUORUM means a full join; a partial one is refused by validate.
Definition workflow.h:758
const SPTree< T > * sp_tree()
The cached series-parallel decomposition, or null when the precedence graph is not series-parallel.
Definition workflow.h:488
std::vector< T > sample(std::size_t n, pfqn::McRng &rng)
Draw n workflow execution times from the composed law.
Definition workflow.h:389
void invalidate_topology()
Discard the cached law and the decomposition.
Definition workflow.h:438
void set_activity_demand(const std::string &name, const Distrib< T > &host_demand)
Change the host demand of one activity.
Definition workflow.h:403
static PhLaw< T > compose_repeat(const PhLaw< T > &body, long count)
COUNT-fold convolution of a phase-type law.
Definition workflow.h:680
std::size_t add_activity(const std::string &name, const Distrib< T > &host_demand)
Add an activity; the name must be unique.
Definition workflow.h:255
static PhLaw< T > compose_loop_geometric(const PhLaw< T > &body, const T &count)
Geometric repetition of a phase-type law, the POST_LOOP semantics.
Definition workflow.h:627
void add_precedence(const Precedence< T > &prec)
Definition workflow.h:270
const std::string & name() const
Definition workflow.h:252
std::size_t add_activity(const std::string &name, const T &mean)
Add an activity with an exponential host demand of the given mean.
Definition workflow.h:266
const std::vector< WorkflowActivity< T > > & activities() const
Definition workflow.h:276
static std::vector< Precedence< T > > SerialSequence(const std::vector< std::string > &acts)
Definition workflow.h:740
static constexpr std::size_t npos
Definition workflow.h:248
void invalidate_activity(std::size_t act_idx)
Mark one activity law dirty, keeping every other cached block.
Definition workflow.h:449
static Precedence< T > AndFork(const std::string &pre, const std::vector< std::string > &posts)
Definition workflow.h:747
static Precedence< T > OrFork(const std::string &pre, const std::vector< std::string > &posts, const std::vector< T > &probs)
Definition workflow.h:770
void set_activity_demand_mean(const std::string &name, const T &mean_value)
Change only the mean of one activity, preserving its shape.
Definition workflow.h:416
Distrib< T > refresh_ph()
Recompose the law after a demand change.
Definition workflow.h:376
std::size_t num_activities() const
Definition workflow.h:275
void validate() const
Validate the workflow, throwing on the first defect.
Definition workflow.h:301
void rescale_activity_leaf(std::size_t act_idx, const T &factor)
Time-scale a cached leaf in place: S -> S*FACTOR with alpha fixed.
Definition workflow.h:466
std::size_t activity_index(const std::string &name) const
Definition workflow.h:279
static PhLaw< T > compose_parallel(const PhLaw< T > &a, const PhLaw< T > &b)
Parallel (AND-fork/join) composition: the time until BOTH complete.
Definition workflow.h:538
static PhLaw< T > compose_serial(const PhLaw< T > &a, const PhLaw< T > &b)
Serial composition: the second law starts when the first absorbs.
Definition workflow.h:505
static Precedence< T > OrJoin(const std::vector< std::string > &pres, const std::string &post)
Definition workflow.h:781
const std::vector< Precedence< T > > & precedences() const
Definition workflow.h:277
Distrib< T > to_ph()
The composed law of the workflow.
Definition workflow.h:354
Workflow(const std::string &name)
Definition workflow.h:250
static Precedence< T > Serial(const std::string &pre, const std::string &post)
Definition workflow.h:731
static PhLaw< T > compose_mixture(const std::vector< PhLaw< T > > &laws, const std::vector< T > &probs)
Probabilistic mixture: a block-diagonal generator whose initial vector picks branch i with probabilit...
Definition workflow.h:590
WorkflowActivity< T > & activity(const std::string &name)
Definition workflow.h:284
const WorkflowActivity< T > & activity_at(std::size_t i) const
Activity by index, the form a series-parallel LEAF node names it in.
Definition workflow.h:291
The moment fitters the reference distributions carry as STATIC FACTORIES: Erlang.fitMeanAndOrder,...
Rate-scaled copy of a distribution, preserving its shape.
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
Sample the inter-arrival times of a MAP, a RAP or a matrix exponential.
Dense matrix and non-owning view.
const Element * child(const Element *e, const std::string &tag)
The first direct child with the given tag, or null.
Definition jmva_reader.h:89
Distrib< T > erlang_fit_mean_order(const T &mean, std::size_t k)
Erlang.fitMeanAndOrder(MEAN, k): k phases, each of rate k / MEAN.
PrecedenceType
Activity precedence kinds, with the values of MATLAB ActivityPrecedenceType.
Definition lang_types.h:516
Distrib< T > aph_fit_mean_scv(const T &mean, const T &scv)
APH.fitMeanAndSCV(MEAN, SCV), through mam::aph_fit_mean_scv.
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:529
Distrib< T > dist_scale_rate(const Distrib< T > &d, const T &factor)
The law of X / factor, in the same family as d.
std::string join(const std::vector< std::string > &v, const std::string &sep)
std::vector< const Element * > kids(const Element *el)
Model children of el: results and output requests are skipped.
std::vector< T > map_sample(const Map< T > &m, std::size_t n, pfqn::McRng &rng, const std::vector< T > &pie0=std::vector< T >(), SampleTrace *trace=0)
Sample the inter-arrival times of a MAP, a RAP or a matrix exponential.
Definition map_sample.h:98
std::mt19937_64 McRng
The generator type every Monte Carlo entry point in this tree accepts.
std::vector< Frame > & stack()
SPNodeType
A node of the series-parallel tree.
Definition workflow.h:212
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:926
std::vector< T > params
Constructor arguments, in MATLAB getParam order.
Definition lang_types.h:899
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
static Distrib phase_type(const std::vector< T > &alpha, const Matrix< T > &A, bool acyclic)
PH / APH given by (alpha, A): D0 = A and D1 = (-A e) alpha.
static Distrib exp_mean(const T &m)
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:834
static constexpr double FineTol
Definition lang_types.h:828
static constexpr double ArcTol
Below this an off-diagonal entry is NO ARC of the phase / state graph.
Definition lang_types.h:832
A phase-type law as the composition rules pass it around.
Definition workflow.h:90
std::vector< T > alpha
Definition workflow.h:91
One precedence of the activity graph.
Definition workflow.h:79
std::vector< T > pre_params
Definition workflow.h:84
PrecedenceType pre_type
Definition workflow.h:82
PrecedenceType post_type
Definition workflow.h:83
std::vector< T > post_params
Definition workflow.h:85
std::vector< std::string > post_acts
Definition workflow.h:81
std::vector< std::string > pre_acts
Definition workflow.h:80
T count
Loop count for a LOOP node.
Definition workflow.h:224
std::vector< T > probs
Branch probabilities for an OR node.
Definition workflow.h:222
std::vector< std::size_t > kids
Definition workflow.h:219
std::size_t act
Activity index for a LEAF, npos otherwise.
Definition workflow.h:218
The flat series-parallel tree.
Definition workflow.h:237
std::vector< SPNode< T > > nodes
Definition workflow.h:238
std::vector< T > execs
Definition workflow.h:242
std::vector< std::size_t > leaf_of
Node index of each activity's leaf, npos when the activity has none.
Definition workflow.h:241