5#ifndef LINE_SOLVERS_SSA_SOLVER_SSA_NRM_SPN_H
6#define LINE_SOLVERS_SSA_SOLVER_SSA_NRM_SPN_H
110 std::size_t node = 0;
111 std::size_t mode = 0;
113 std::vector<double> S;
114 std::vector<std::size_t> en_slot;
115 std::vector<double> en_w;
116 std::vector<std::size_t> inh_slot;
117 std::vector<double> inh_thr;
118 double base_rate = 0.0;
119 double nservers = 1.0;
122 std::vector<std::size_t> dep_slots;
124 std::vector<std::size_t> flow_q;
125 std::vector<double> flow_rate;
126 std::vector<std::size_t> guard_q;
127 std::vector<int> guard_sgn;
128 std::vector<double> guard_thr;
129 std::vector<std::size_t> imp_q;
130 std::vector<double> imp_d;
131 std::vector<std::size_t> fdep_q;
132 std::vector<std::function<double(
double)>> fdep_fun;
134 std::vector<std::function<double(
const std::vector<double>&)>> flow_fun;
135 std::vector<std::vector<std::size_t>> flow_read;
137 std::function<double(
const std::vector<double>&)> gdep;
138 std::vector<std::size_t> gdep_read;
147inline double spn_en_degree(
const std::vector<double>& n,
const SpnReaction& rx) {
148 for (std::size_t i = 0; i < rx.inh_slot.size(); ++i)
149 if (n[rx.inh_slot[i]] >= rx.inh_thr[i])
return 0.0;
150 if (rx.en_slot.empty())
return 1.0;
151 double d = std::numeric_limits<double>::infinity();
152 for (std::size_t i = 0; i < rx.en_slot.size(); ++i)
153 d = std::min(d, std::floor(n[rx.en_slot[i]] / rx.en_w[i]));
163inline double spn_propensity(
const std::vector<double>& n,
const SpnReaction& rx) {
164 const double eff = std::min(spn_en_degree(n, rx), rx.nservers);
165 return eff <= 0.0 ? 0.0 : rx.base_rate * eff;
189bool ssa_check_firingdep(
const qn::NetworkStruct<T>& sn,
bool raise =
true) {
190 if (sn.has_fluid_places())
return true;
191 for (
typename std::map<std::size_t, qn::TransitionParam<T>>::const_iterator it =
192 sn.transparam.begin();
193 it != sn.transparam.end(); ++it) {
194 const qn::TransitionParam<T>& tp = it->second;
195 for (std::size_t m = 0; m < tp.nmodes && m < tp.firingdep.size(); ++m) {
196 if (!tp.firingdep[m])
continue;
197 if (!raise)
return false;
198 const std::size_t ind = it->first;
200 "SolverSSA: transition '" +
201 (ind >= 1 && ind <= sn.nodes.size() ? sn.nodes[ind - 1].name : std::string(
"?")) +
202 "' mode " + std::to_string(m + 1) +
203 " uses a marking-dependent firing rate (setFiringRateDependence), which the "
204 "NRM does not support: it builds one constant-propensity reaction per timed "
205 "mode and never evaluates the handle. Ask for method='serial', which applies "
206 "it, or use SolverCTMC or SolverLDES");
222bool spn_nrm_supported(
const qn::NetworkStruct<T>& sn,
bool raise =
true) {
223 const std::size_t I = sn.nodes.size();
224 const std::size_t K = sn.nclasses;
225 bool any_transition =
false;
226 for (std::size_t i = 0; i < I; ++i)
227 if (sn.nodes[i].nodetype == qn::NodeType::Transition) any_transition =
true;
228 if (!any_transition)
return true;
229 if (!ssa_check_firingdep(sn, raise))
return false;
231 for (std::size_t i = 0; i < I; ++i) {
232 if (sn.nodes[i].nodetype == qn::NodeType::Transition) {
233 const typename std::map<std::size_t, qn::TransitionParam<T>>::const_iterator it =
234 sn.transparam.find(i + 1);
235 if (it == sn.transparam.end())
continue;
236 const qn::TransitionParam<T>& tp = it->second;
237 for (std::size_t m = 0; m < tp.nmodes; ++m) {
240 const bool one_phase = m < tp.firingphases.size() && tp.firingphases[m] == 1;
241 const bool has_proc = m < tp.firingproc.size() && tp.firingproc[m].D1.rows() > 0;
242 if (one_phase && has_proc)
continue;
243 if (!raise)
return false;
245 "SolverSSA(method='nrm'): transition '" + sn.nodes[i].name +
"' mode " +
246 std::to_string(m + 1) +
247 " has a non-exponential timed firing. The reaction network carries one "
248 "constant-rate reaction per mode and no per-mode phase, so an in-flight "
249 "firing has nowhere to keep its phase; use method='serial'");
251 }
else if (sn.nodes[i].nodetype == qn::NodeType::Source) {
252 const std::size_t ist = sn.nodes[i].station;
253 if (ist == 0)
continue;
254 for (std::size_t r = 0; r < K; ++r) {
255 const double lambda = num_traits<T>::to_double(sn.rates(ist - 1, r));
256 if (std::isnan(lambda) || lambda <= 0.0)
continue;
258 if (!raise)
return false;
260 "SolverSSA(method='nrm'): source '" + sn.nodes[i].name +
"' class '" +
262 "' has a non-exponential arrival. An arrival into a Place is one "
263 "constant-propensity reaction here, which only a Poisson stream is; "
264 "use method='serial'");
267 for (std::size_t j = 0; j < I && !feeds; ++j) {
268 if (sn.nodes[j].nodetype != qn::NodeType::Place)
continue;
269 for (std::size_t s = 0; s < K && !feeds; ++s)
270 if (num_traits<T>::to_double(sn.rtnodes(i * K + r, j * K + s)) > 0.0)
274 if (!raise)
return false;
276 "SolverSSA(method='nrm'): source '" + sn.nodes[i].name +
"' class '" +
278 "' routes to no Place. The SPN path deposits an arrival into a Place "
279 "slot and has nowhere else to put one; use method='serial'");
282 }
else if (sn.nodes[i].nodetype == qn::NodeType::Place) {
283 const typename std::map<std::size_t, std::vector<T>>::const_iterator im =
284 sn.initmarking.find(i + 1);
285 if (im == sn.initmarking.end())
continue;
286 for (std::size_t r = 0; r < im->second.size(); ++r) {
287 if (std::isfinite(num_traits<T>::to_double(im->second[r])))
continue;
288 if (!raise)
return false;
289 throw UnsupportedError(ErrorKind{
"Place"},
"SolverSSA(method='nrm'): place '" + sn.nodes[i].name +
290 "' declares an infinite initial marking, which the "
291 "reaction network cannot count; use method='serial'");
312api::SnFluidVerdict ssa_fluid_refusal(
const qn::NetworkStruct<T>& sn,
const std::string& method) {
313 api::SnFluidVerdict v;
314 if (!sn.has_fluid_places())
return v;
317 v.reason =
"SolverSSA: " + v.reason;
320 if (method ==
"serial" || method ==
"ssa") {
322 v.reason =
"SolverSSA: the model is a fluid stochastic Petri net (Place.setFluid), whose levels only the "
323 "NRM Petri runner moves. Use options.method='nrm' or 'default'.";
326 for (
const qn::NodeDef& nd : sn.nodes)
327 if (nd.nodetype != qn::NodeType::Place && nd.nodetype != qn::NodeType::Transition &&
328 nd.nodetype != qn::NodeType::Source && nd.nodetype != qn::NodeType::Sink) {
330 v.reason =
"SolverSSA: a fluid stochastic Petri net may hold only Place, Transition, Source and Sink "
331 "nodes; the NRM Petri runner has no hand-off between a level and a queueing station.";
334 if (!spn_nrm_supported(sn,
false)) {
336 v.reason =
"SolverSSA: the fluid net has a non-exponential firing or Source arrival, or an infinite "
337 "marking, which the NRM Petri runner (the only engine that moves fluid levels) has no form for.";
346inline bool spn_fluid_guard_holds(
const SpnReaction& rec,
const std::vector<double>& f,
347 const std::vector<double>& v) {
348 for (std::size_t g = 0; g < rec.guard_q.size(); ++g) {
349 const std::size_t q = rec.guard_q[g];
350 const double sg =
static_cast<double>(rec.guard_sgn[g]);
351 const double thr = rec.guard_thr[g];
352 const double tolf = 1e-12 * std::max(1.0, std::fabs(thr));
353 const double d = sg * (f[q] - thr);
354 if (d > tolf)
continue;
355 if (d >= -tolf && sg * v[q] >= 0.0)
continue;
362inline double spn_fluid_dep(
const SpnReaction& rec,
const std::vector<double>& f,
const std::vector<double>& v,
365 for (std::size_t i = 0; i < rec.fdep_q.size(); ++i) {
366 const std::size_t q = rec.fdep_q[i];
367 h *= rec.fdep_fun[i](std::max(0.0, f[q] + v[q] * t));
373inline bool spn_fluid_varying(
const SpnReaction& rec,
const std::vector<double>& v) {
374 for (std::size_t i = 0; i < rec.fdep_q.size(); ++i)
375 if (v[rec.fdep_q[i]] != 0.0)
return true;
381double spn_simpson_panel(
const F& h,
double a,
double b,
double fa,
double fm,
double fb,
double whole,
382 double tol,
int depth) {
383 const double m = 0.5 * (a + b);
384 const double lm = 0.5 * (a + m), rm = 0.5 * (m + b);
385 const double flm = h(lm), frm = h(rm);
386 const double left = (m - a) / 6.0 * (fa + 4.0 * flm + fm);
387 const double right = (b - m) / 6.0 * (fm + 4.0 * frm + fb);
388 const double err = left + right - whole;
389 if (depth <= 0 || std::fabs(err) <= 15.0 * tol)
return left + right +
err / 15.0;
390 return spn_simpson_panel(h, a, m, fa, flm, fm, left, 0.5 * tol, depth - 1) +
391 spn_simpson_panel(h, m, b, fm, frm, fb, right, 0.5 * tol, depth - 1);
399inline double spn_fluid_hazard(
const SpnReaction& rec,
double a0,
const std::vector<double>& f,
400 const std::vector<double>& v,
double dt) {
401 if (dt <= 0.0)
return 0.0;
402 if (!spn_fluid_varying(rec, v))
return a0 * spn_fluid_dep(rec, f, v, 0.0) * dt;
403 const auto h = [&](
double t) {
return spn_fluid_dep(rec, f, v, t); };
404 const double fa = h(0.0), fm = h(0.5 * dt), fb = h(dt);
405 const double whole = dt / 6.0 * (fa + 4.0 * fm + fb);
406 const double tol = std::max(1e-12, 1e-10 * std::fabs(whole));
407 return a0 * spn_simpson_panel(h, 0.0, dt, fa, fm, fb, whole, tol, 50);
415inline double spn_fluid_fire_time(
const SpnReaction& rec,
double a0,
const std::vector<double>& f,
416 const std::vector<double>& v,
double need,
double horizon) {
417 const double inf = std::numeric_limits<double>::infinity();
418 if (!spn_fluid_varying(rec, v)) {
419 const double a = a0 * spn_fluid_dep(rec, f, v, 0.0);
420 return a <= 0.0 ? inf : need / a;
422 if (need <= 0.0)
return 0.0;
424 if (std::isfinite(horizon)) {
426 if (spn_fluid_hazard(rec, a0, f, v, hi) < need)
return inf;
428 const double a = std::max(a0 * spn_fluid_dep(rec, f, v, 0.0), std::numeric_limits<double>::min());
431 while (spn_fluid_hazard(rec, a0, f, v, hi) < need) {
433 if (++grow > 200)
return inf;
436 const auto g = [&](
double t) {
return spn_fluid_hazard(rec, a0, f, v, t) - need; };
454 : sn_(
sn), opt_(
opt), rng_(
opt.seed) {
467 using Rx = detail::SpnReaction;
473 std::size_t I_ = 0, K_ = 0, M_ = 0, NS_ = 0;
476 std::vector<Rx> imm_;
478 std::vector<std::vector<std::vector<std::size_t>>> consumers_;
480 std::vector<std::vector<std::vector<std::size_t>>> producers_;
482 std::vector<double> nvec0_;
483 std::vector<double> pcap_slot_;
485 std::vector<std::pair<double, std::vector<std::size_t>>> place_total_caps_;
486 bool has_caps_ =
false;
489 std::vector<long> fq_;
490 std::vector<std::size_t> fl_node_;
491 std::vector<std::size_t> fl_ist_;
492 std::vector<double> fl_cap_;
493 std::vector<double> fl_f0_;
495 std::vector<std::vector<double>> fm_;
498 static const std::size_t kMaxImmSteps = 100000;
500 std::size_t slot(std::size_t node0, std::size_t cls)
const {
return node0 * K_ + cls; }
503 Rx build_mode(std::size_t ind0, std::size_t m)
const;
504 void apply_caps(std::vector<double>& n,
const std::vector<std::size_t>& deposited)
const;
505 void collapse(std::vector<double>& n);
508 SsaSolution run_fluid();
509 std::size_t fluid_index(std::size_t node1)
const;
510 void fluid_mark_mul(
const std::vector<double>& n, std::vector<double>& gk);
511 void fluid_resolve(
const std::vector<double>& n,
const std::vector<double>& f, std::vector<double>& eff,
512 std::vector<double>& v, std::vector<double>& vin, std::vector<double>& vout)
const;
513 void fluid_slope(
const std::vector<double>& f,
const std::vector<double>& eff, std::vector<double>& v,
514 std::vector<double>& vin, std::vector<double>& vout)
const;
515 void fluid_next_det(
const std::vector<double>& f,
const std::vector<double>& v,
double& tdet,
516 std::size_t& qdet,
double& fdet)
const;
517 void fluid_impulse(std::vector<double>& f,
const Rx& rec, std::vector<double>& OF)
const;
518 void collapse_fluid(std::vector<double>& n, std::vector<double>& f,
const std::vector<double>& v,
519 std::vector<double>& OF);
531void NrmSpnEngine<T>::build() {
532 I_ = sn_.nodes.size();
536 consumers_.assign(I_, std::vector<std::vector<std::size_t>>(K_));
537 producers_.assign(I_, std::vector<std::vector<std::size_t>>(K_));
543 detail::ssa_check_firingdep(sn_,
true);
548 if (sn_.has_fluid_places()) {
550 if (!fv.ok)
throw UnsupportedError(ErrorKind{
"Structure"},
"solver_ssa_nrm_spn: " + fv.reason);
551 for (std::size_t ind = 0; ind < I_; ++ind) {
552 if (sn_.nodes[ind].nodetype != qn::NodeType::Place || !sn_.is_fluid_node(ind + 1))
continue;
553 const std::size_t ist = sn_.nodes[ind].station;
554 const qn::Station<T>& st = sn_.stations[ist - 1];
555 fq_[ind] =
static_cast<long>(fl_node_.size());
556 fl_node_.push_back(ind);
557 fl_ist_.push_back(ist - 1);
558 fl_cap_.push_back(st.fluidcap);
559 fl_f0_.push_back(st.fluidinit);
563 for (std::size_t ind = 0; ind < I_; ++ind) {
564 if (sn_.nodes[ind].nodetype != qn::NodeType::Transition)
continue;
565 const typename std::map<std::size_t, qn::TransitionParam<T>>::const_iterator it =
566 sn_.transparam.find(ind + 1);
567 if (it == sn_.transparam.end())
continue;
568 const qn::TransitionParam<T>& tp = it->second;
569 for (std::size_t m = 0; m < tp.nmodes; ++m) {
570 const Rx rec = build_mode(ind, m);
576 const std::size_t ridx = rx_.size() - 1;
577 for (std::size_t a = 0; a < rec.en_slot.size(); ++a)
578 consumers_[rec.en_slot[a] / K_][rec.en_slot[a] % K_].push_back(ridx);
587 for (std::size_t ind = 0; ind < I_; ++ind) {
588 if (sn_.nodes[ind].nodetype != qn::NodeType::Source)
continue;
589 const std::size_t ist = sn_.nodes[ind].station;
590 if (ist == 0)
continue;
591 for (std::size_t r = 0; r < K_; ++r) {
592 const double lambda = num_traits<T>::to_double(sn_.rates(ist - 1, r));
593 if (std::isnan(lambda) || lambda <= 0.0)
continue;
596 "solver_ssa_nrm_spn: source '" + sn_.nodes[ind].name +
"' class '" +
597 sn_.classes[r].name +
598 "' has a non-exponential arrival, which the SPN reaction network cannot "
599 "express; use method='serial' or SolverJMT");
600 bool found_place =
false;
601 for (std::size_t jnd = 0; jnd < I_; ++jnd) {
602 if (sn_.nodes[jnd].nodetype != qn::NodeType::Place)
continue;
603 for (std::size_t s = 0; s < K_; ++s) {
605 num_traits<T>::to_double(sn_.rtnodes(ind * K_ + r, jnd * K_ + s));
606 if (p <= 0.0)
continue;
611 rec.S.assign(NS_, 0.0);
612 rec.S[slot(jnd, s)] += 1.0;
613 rec.base_rate = lambda * p;
615 rec.dep_slots.push_back(slot(jnd, s));
617 producers_[ind][r].push_back(rx_.size() - 1);
621 throw UnsupportedError(ErrorKind{
"Topology"},
"solver_ssa_nrm_spn: source '" + sn_.nodes[ind].name +
622 "' class '" + sn_.classes[r].name +
623 "' does not route to any Place; the SPN path needs a "
624 "Source->Place arc");
630 "solver_ssa_nrm_spn: the stochastic Petri net has no timed reaction; there is "
631 "nothing to simulate");
647 nvec0_.assign(NS_, 0.0);
648 for (std::size_t r = 0; r < K_; ++r) {
649 const double pop = sn_.classes[r].population;
650 if (!std::isfinite(pop) || pop <= 0.0)
continue;
651 const std::size_t rs = sn_.classes[r].refstat;
652 if (rs < 1 || rs > M_)
continue;
653 const std::size_t ind = sn_.station_to_node[rs - 1] - 1;
654 if (sn_.nodes[ind].nodetype != qn::NodeType::Place)
continue;
655 nvec0_[slot(ind, r)] = pop;
657 for (std::size_t ind = 0; ind < I_; ++ind) {
658 if (sn_.nodes[ind].nodetype != qn::NodeType::Place)
continue;
659 const typename std::map<std::size_t, std::vector<T>>::const_iterator im =
660 sn_.initmarking.find(ind + 1);
661 if (im == sn_.initmarking.end())
continue;
662 for (std::size_t r = 0; r < K_; ++r) {
664 r < im->second.size() ? num_traits<T>::to_double(im->second[r]) : 0.0;
665 if (!std::isfinite(v))
666 throw UnsupportedError(ErrorKind{
"Place"},
"solver_ssa_nrm_spn: place '" + sn_.nodes[ind].name +
667 "' declares an infinite initial marking, which the "
668 "reaction network cannot count");
669 nvec0_[slot(ind, r)] = v > 0.0 ? v : 0.0;
678 const double inf = std::numeric_limits<double>::infinity();
679 pcap_slot_.assign(NS_, inf);
680 for (std::size_t ind = 0; ind < I_; ++ind) {
681 if (sn_.nodes[ind].nodetype != qn::NodeType::Place)
continue;
682 const std::size_t ist = sn_.nodes[ind].station;
683 if (ist == 0)
continue;
684 std::vector<std::size_t> slots_here;
685 for (std::size_t r = 0; r < K_; ++r) {
686 slots_here.push_back(slot(ind, r));
687 if (ist - 1 < sn_.classcap.size() && r < sn_.classcap[ist - 1].size()) {
688 const double cc = sn_.classcap[ist - 1][r];
689 if (std::isfinite(cc)) pcap_slot_[slot(ind, r)] = cc;
692 if (ist - 1 < sn_.cap.size() && std::isfinite(sn_.cap[ist - 1]))
693 place_total_caps_.push_back(std::make_pair(sn_.cap[ist - 1], slots_here));
695 has_caps_ = !place_total_caps_.empty();
696 for (std::size_t j = 0; j < NS_ && !has_caps_; ++j)
697 if (std::isfinite(pcap_slot_[j])) has_caps_ =
true;
710typename NrmSpnEngine<T>::Rx NrmSpnEngine<T>::build_mode(std::size_t ind0, std::size_t m)
const {
711 const qn::TransitionParam<T>& tp = sn_.transparam.at(ind0 + 1);
715 rec.S.assign(NS_, 0.0);
717 if (m < tp.enabling.size()) {
718 const Matrix<T>& en = tp.enabling[m];
719 for (std::size_t p = 0; p < en.rows() && p < I_; ++p)
720 for (std::size_t c = 0; c < en.cols() && c < K_; ++c) {
721 const double w = num_traits<T>::to_double(en(p, c));
722 if (w == 0.0)
continue;
723 rec.en_slot.push_back(slot(p, c));
724 rec.en_w.push_back(w);
725 rec.S[slot(p, c)] -= w;
728 if (m < tp.firing.size()) {
729 const Matrix<T>& fir = tp.firing[m];
730 for (std::size_t p = 0; p < fir.rows() && p < I_; ++p)
731 for (std::size_t c = 0; c < fir.cols() && c < K_; ++c) {
732 const double w = num_traits<T>::to_double(fir(p, c));
733 if (w == 0.0)
continue;
734 rec.S[slot(p, c)] += w;
737 if (m < tp.inhibiting.size()) {
738 const Matrix<T>& inh = tp.inhibiting[m];
739 for (std::size_t p = 0; p < inh.rows() && p < I_; ++p)
740 for (std::size_t c = 0; c < inh.cols() && c < K_; ++c) {
741 const double thr = num_traits<T>::to_double(inh(p, c));
742 if (!std::isfinite(thr))
continue;
743 rec.inh_slot.push_back(slot(p, c));
744 rec.inh_thr.push_back(thr);
747 for (std::size_t j = 0; j < NS_; ++j)
748 if (rec.S[j] > 0.0) rec.dep_slots.push_back(j);
754 const bool one_phase = m < tp.firingphases.size() && tp.firingphases[m] == 1;
755 if (!one_phase || m >= tp.firingproc.size() || tp.firingproc[m].D1.rows() == 0)
756 throw UnsupportedError(ErrorKind{
"NonExponential"},
"solver_ssa_nrm_spn: transition '" + sn_.nodes[ind0].name +
757 "' mode " + std::to_string(m + 1) +
758 " has a non-exponential firing, which the SPN reaction "
759 "network cannot express; use method='serial'");
760 const Matrix<T>& d1 = tp.firingproc[m].D1;
762 for (std::size_t a = 0; a < d1.rows(); ++a)
763 for (std::size_t b = 0; b < d1.cols(); ++b) s += num_traits<T>::to_double(d1(a, b));
766 rec.nservers = m < tp.nmodeservers.size() ? tp.nmodeservers[m] : 1.0;
768 rec.weight = m < tp.fireweight.size() ? num_traits<T>::to_double(tp.fireweight[m]) : 1.0;
769 rec.prio = m < tp.firingprio.size() ? tp.firingprio[m] : 1.0;
771 for (
const auto& a : tp.fluid_rates(m)) {
772 rec.flow_q.push_back(fluid_index(a.node));
773 rec.flow_rate.push_back(a.value);
775 for (
const auto& g : tp.fluid_guards(m)) {
776 rec.guard_q.push_back(fluid_index(g.node));
777 rec.guard_sgn.push_back(g.sgn);
778 rec.guard_thr.push_back(g.thr);
780 for (
const auto& a : tp.fluid_impulses(m)) {
781 rec.imp_q.push_back(fluid_index(a.node));
782 rec.imp_d.push_back(a.value);
784 for (
const auto& d : tp.fluid_deps(m)) {
785 rec.fdep_q.push_back(fluid_index(d.node));
786 rec.fdep_fun.push_back(d.fun);
789 const std::vector<typename qn::TransitionParam<T>::FluidArc>& fr = tp.fluid_rates(m);
790 rec.flow_fun.assign(fr.size(), std::function<
double(
const std::vector<double>&)>());
791 rec.flow_read.assign(fr.size(), std::vector<std::size_t>());
792 for (
const auto& fd : tp.fluid_flow_deps(m))
793 for (std::size_t t = 0; t < fr.size(); ++t) {
794 if (fr[t].node != fd.node)
continue;
795 rec.flow_fun[t] = fd.fun;
796 for (std::size_t q : fd.read) rec.flow_read[t].push_back(q - 1);
802 if (timed && m < tp.firingdep.size() && tp.firingdep[m]) {
803 const std::function<T(
const std::vector<T>&)> g = tp.firingdep[m];
804 rec.gdep = [g](
const std::vector<double>& mk) ->
double {
805 std::vector<T> mt(mk.size());
806 for (std::size_t i = 0; i < mk.size(); ++i) mt[i] = num_traits<T>::from_double(mk[i]);
807 return num_traits<T>::to_double(g(mt));
809 if (m < tp.enabling.size()) {
810 const Matrix<T>& en = tp.enabling[m];
811 for (std::size_t p = 0; p < en.rows() && p < I_; ++p)
812 for (std::size_t c = 0; c < en.cols(); ++c)
813 if (num_traits<T>::to_double(en(p, c)) > 0.0) {
814 rec.gdep_read.push_back(p);
829void NrmSpnEngine<T>::fluid_mark_mul(
const std::vector<double>& n, std::vector<double>& gk) {
830 const std::size_t nrx = rx_.size();
832 fm_.assign(nrx, std::vector<double>());
833 for (std::size_t k = 0; k < nrx; ++k) {
834 const Rx& rec = rx_[k];
836 std::vector<double> mk(NS_, 0.0);
837 for (std::size_t p : rec.gdep_read)
838 for (std::size_t c = 0; c < K_; ++c) mk[slot(p, c)] = n[slot(p, c)];
839 gk[k] = rec.gdep(mk);
841 for (std::size_t t = 0; t < rec.flow_fun.size(); ++t) {
842 if (!rec.flow_fun[t])
continue;
843 if (fm_[k].empty()) fm_[k].assign(rec.flow_q.size(), 1.0);
844 std::vector<double> mk(NS_, 0.0);
845 for (std::size_t p : rec.flow_read[t])
846 for (std::size_t c = 0; c < K_; ++c) mk[slot(p, c)] = n[slot(p, c)];
847 fm_[k][t] = rec.flow_fun[t](mk);
854std::size_t NrmSpnEngine<T>::fluid_index(std::size_t node1)
const {
855 if (node1 == 0 || node1 > I_ || fq_[node1 - 1] < 0)
857 "solver_ssa_nrm_spn: a fluid arc names node " + std::to_string(node1) +
", which is not a fluid place");
858 return static_cast<std::size_t
>(fq_[node1 - 1]);
869void NrmSpnEngine<T>::apply_caps(std::vector<double>& n,
870 const std::vector<std::size_t>& deposited)
const {
871 for (std::size_t a = 0; a < deposited.size(); ++a) {
872 const std::size_t j = deposited[a];
873 if (n[j] > pcap_slot_[j]) n[j] = pcap_slot_[j];
875 for (std::size_t p = 0; p < place_total_caps_.size(); ++p) {
876 const double tcap = place_total_caps_[p].first;
877 const std::vector<std::size_t>& slots = place_total_caps_[p].second;
879 for (std::size_t a = 0; a < slots.size(); ++a) total += n[slots[a]];
880 double excess = total - tcap;
881 for (std::size_t a = 0; a < deposited.size() && excess > 0.0; ++a) {
882 const std::size_t j = deposited[a];
883 if (std::find(slots.begin(), slots.end(), j) == slots.end())
continue;
884 if (n[j] <= 0.0)
continue;
885 const double d = std::min(excess, n[j]);
901void NrmSpnEngine<T>::collapse(std::vector<double>& n) {
902 if (imm_.empty())
return;
903 std::size_t steps = 0;
905 std::vector<std::size_t> enabled;
906 for (std::size_t m = 0; m < imm_.size(); ++m)
907 if (detail::spn_en_degree(n, imm_[m]) >= 1.0) enabled.push_back(m);
908 if (enabled.empty())
return;
909 double top_prio = -std::numeric_limits<double>::infinity();
910 for (std::size_t i = 0; i < enabled.size(); ++i)
911 top_prio = std::max(top_prio, imm_[enabled[i]].prio);
912 std::vector<std::size_t> top;
913 std::vector<double> w;
914 for (std::size_t i = 0; i < enabled.size(); ++i)
915 if (imm_[enabled[i]].prio == top_prio) {
916 top.push_back(enabled[i]);
917 w.push_back(imm_[enabled[i]].weight);
919 const std::size_t pick = top.size() == 1 ? top[0] : top[rng_.draw(w)];
920 for (std::size_t j = 0; j < NS_; ++j) n[j] += imm_[pick].S[j];
921 if (++steps > kMaxImmSteps)
923 "solver_ssa_nrm_spn: immediate-transition livelock -- the vanishing-marking "
924 "collapse did not reach a tangible marking");
943 if (!fl_node_.empty())
return run_fluid();
944 const std::size_t nrx = rx_.size();
950 out.
CN.assign(K_, 0.0);
951 out.
XN.assign(K_, 0.0);
956 std::vector<double> nvec = nvec0_;
959 std::vector<std::size_t> all(NS_);
960 for (std::size_t j = 0; j < NS_; ++j) all[j] = j;
961 apply_caps(nvec, all);
964 std::vector<double> Ak(nrx, 0.0), Pk(nrx, 0.0), Tk(nrx, 0.0), tau(nrx, 0.0);
965 const double inf = std::numeric_limits<double>::infinity();
966 for (std::size_t k = 0; k < nrx; ++k) {
967 Ak[k] = detail::spn_propensity(nvec, rx_[k]);
968 Pk[k] = -std::log(rng_.uniform());
969 tau[k] = Ak[k] > 0.0 ? (Pk[k] - Tk[k]) / Ak[k] : inf;
972 double total_time = 0.0;
975 static_cast<std::size_t
>(opt_.samples));
976 const std::size_t console_every = std::max<std::size_t>(1, opt_.samples / 20);
979 bool time_stopped =
false;
980 for (; n < opt_.samples; ++n) {
987 if (n == n_warm && n_warm > 0) {
993 if ((n + 1) % console_every == 0)
995 static_cast<long>((n + 1) / console_every),
996 "simulated %zu of %zu samples (%.0f%%), simulated time %.4g", n + 1,
997 static_cast<std::size_t
>(opt_.samples),
998 100.0 *
static_cast<double>(n + 1) /
static_cast<double>(opt_.samples),
1000 std::size_t kfire = 0;
1002 for (std::size_t k = 0; k < nrx; ++k)
1009 "solver_ssa_nrm_spn: deadlock -- no transition is enabled, so the sample path "
1013 for (std::size_t ist = 0; ist < M_; ++ist) {
1014 const std::size_t ind = sn_.station_to_node[ist] - 1;
1015 for (std::size_t c = 0; c < K_; ++c) {
1016 const double tokens = nvec[slot(ind, c)];
1017 out.
QN(ist, c) += tokens * dt;
1018 out.
UN(ist, c) += tokens * dt;
1020 const std::vector<std::size_t>& cons = consumers_[ind][c];
1021 for (std::size_t a = 0; a < cons.size(); ++a) depr += Ak[cons[a]];
1025 const std::vector<std::size_t>& prod = producers_[ind][c];
1026 for (std::size_t a = 0; a < prod.size(); ++a) depr += Ak[prod[a]];
1027 out.
TN(ist, c) += depr * dt;
1034 for (std::size_t j = 0; j < NS_; ++j) nvec[j] += rx_[kfire].S[j];
1035 if (has_caps_) apply_caps(nvec, rx_[kfire].dep_slots);
1040 for (std::size_t k = 0; k < nrx; ++k) Tk[k] += Ak[k] * dt;
1041 for (std::size_t k = 0; k < nrx; ++k) Ak[k] = detail::spn_propensity(nvec, rx_[k]);
1042 Pk[kfire] -= std::log(rng_.uniform());
1043 for (std::size_t k = 0; k < nrx; ++k)
1044 tau[k] = Ak[k] > 0.0 ? (Pk[k] - Tk[k]) / Ak[k] : inf;
1048 if (time_stopped && n_warm > 0 && n <= n_warm)
1050 "solver_ssa_nrm_spn: the wall-clock time budget (options.timeout) ran "
1051 "out inside the warmup, before any sample was collected");
1053 if (total_time > 0.0)
1054 for (std::size_t ist = 0; ist < M_; ++ist)
1055 for (std::size_t c = 0; c < K_; ++c) {
1056 out.
QN(ist, c) /= total_time;
1057 out.
UN(ist, c) /= total_time;
1058 out.
TN(ist, c) /= total_time;
1060 for (std::size_t c = 0; c < K_; ++c) {
1061 out.
XN[c] = out.
TN(sn_.classes[c].refstat - 1, c);
1062 for (std::size_t ist = 0; ist < M_; ++ist)
1063 out.
RN(ist, c) = out.
TN(ist, c) > 0.0 ? out.
QN(ist, c) / out.
TN(ist, c) : 0.0;
1064 if (out.
XN[c] > 0.0) out.
CN[c] = sn_.classes[c].population / out.
XN[c];
1083 const std::size_t nrx = rx_.size();
1084 const std::size_t nf = fl_node_.size();
1090 out.
CN.assign(K_, 0.0);
1091 out.
XN.assign(K_, 0.0);
1095 std::vector<bool> fluid_st(M_,
false);
1096 for (std::size_t q = 0; q < nf; ++q) fluid_st[fl_ist_[q]] =
true;
1098 std::vector<double> f = fl_f0_;
1099 std::vector<double> nvec = nvec0_;
1100 std::vector<double> QF(nf, 0.0), OF(nf, 0.0);
1103 std::vector<double> of0(nf, 0.0);
1104 collapse_fluid(nvec, f, std::vector<double>(nf, 0.0), of0);
1107 std::vector<std::size_t> all(NS_);
1108 for (std::size_t j = 0; j < NS_; ++j) all[j] = j;
1109 apply_caps(nvec, all);
1111 std::vector<double> Pk(nrx, 0.0), Tk(nrx, 0.0), a0(nrx, 0.0), Ik(nrx, 0.0), tau(nrx, 0.0);
1112 for (std::size_t k = 0; k < nrx; ++k) Pk[k] = -std::log(rng_.uniform());
1114 const double inf = std::numeric_limits<double>::infinity();
1115 double total_time = 0.0;
1116 std::size_t n = 0, zero_run = 0, ndet = 0;
1118 bool warm_pending = n_warm > 0;
1119 std::vector<double> eff, v, vin, vout;
1120 std::vector<double> gk(nrx, 1.0);
1121 fm_.assign(nrx, std::vector<double>());
1122 bool has_mark_dep =
false;
1123 for (std::size_t k = 0; k < nrx; ++k) {
1124 has_mark_dep = has_mark_dep ||
static_cast<bool>(rx_[k].gdep);
1125 for (
const auto& ff : rx_[k].flow_fun) has_mark_dep = has_mark_dep ||
static_cast<bool>(ff);
1128 static_cast<std::size_t
>(opt_.samples));
1129 const std::size_t console_every = std::max<std::size_t>(1, opt_.samples / 20);
1130 bool time_stopped =
false;
1131 while (n < opt_.samples) {
1135 time_stopped =
true;
1138 if (warm_pending && n == n_warm) {
1139 out.
QN = Matrix<double>(M_, K_, 0.0);
1140 out.
UN = Matrix<double>(M_, K_, 0.0);
1141 out.
TN = Matrix<double>(M_, K_, 0.0);
1142 std::fill(QF.begin(), QF.end(), 0.0);
1143 std::fill(OF.begin(), OF.end(), 0.0);
1145 warm_pending =
false;
1149 if (has_mark_dep) fluid_mark_mul(nvec, gk);
1150 fluid_resolve(nvec, f, eff, v, vin, vout);
1151 for (std::size_t k = 0; k < nrx; ++k) a0[k] = rx_[k].base_rate * eff[k] * gk[k];
1154 double tdet = inf, fdet = 0.0;
1155 std::size_t qdet = 0;
1156 fluid_next_det(f, v, tdet, qdet, fdet);
1160 std::size_t kfire = 0;
1161 for (std::size_t k = 0; k < nrx; ++k) {
1162 tau[k] = a0[k] > 0.0 ? detail::spn_fluid_fire_time(rx_[k], a0[k], f, v, Pk[k] - Tk[k], tdet) : inf;
1163 if (tau[k] < dt_r) {
1168 const bool fire = dt_r <= tdet;
1169 const double dt = fire ? dt_r : tdet;
1172 "solver_ssa_nrm_spn: deadlock -- no transition is enabled and no fluid level is moving, so the "
1173 "sample path cannot advance");
1176 for (std::size_t k = 0; k < nrx; ++k)
1177 Ik[k] = a0[k] > 0.0 ? detail::spn_fluid_hazard(rx_[k], a0[k], f, v, dt) : 0.0;
1179 for (std::size_t ist = 0; ist < M_; ++ist) {
1180 if (fluid_st[ist])
continue;
1181 const std::size_t ind = sn_.station_to_node[ist] - 1;
1182 for (std::size_t c = 0; c < K_; ++c) {
1183 const double tokens = nvec[slot(ind, c)];
1184 out.
QN(ist, c) += tokens * dt;
1185 out.
UN(ist, c) += tokens * dt;
1187 for (std::size_t k : consumers_[ind][c]) fired += Ik[k];
1188 for (std::size_t k : producers_[ind][c]) fired += Ik[k];
1189 out.
TN(ist, c) += fired;
1192 for (std::size_t q = 0; q < nf; ++q) {
1193 QF[q] += f[q] * dt + 0.5 * v[q] * dt * dt;
1195 if (v[q] == 0.0 && vin[q] < vout[q] && f[q] <= 0.0)
1196 OF[q] += vin[q] * dt;
1198 OF[q] += vout[q] * dt;
1200 for (std::size_t k = 0; k < nrx; ++k) Tk[k] += Ik[k];
1201 for (std::size_t q = 0; q < nf; ++q) f[q] = std::min(std::max(f[q] + v[q] * dt, 0.0), fl_cap_[q]);
1207 if (++zero_run > 1000)
1209 "solver_ssa_nrm_spn: the fluid level of place " + sn_.nodes[fl_node_[qdet]].name +
1210 " keeps re-crossing a guard at the same instant: a guarded flow drives its own level back "
1211 "across its own guard (a sliding mode), which a sample path has no value for");
1215 collapse_fluid(nvec, f, v, OF);
1216 if (ndet > 1000 * std::max<std::size_t>(opt_.samples, 1))
1218 "solver_ssa_nrm_spn: more than 1000 guard or bound events per firing: the fluid levels "
1219 "chatter. Check the guards against the flows they gate");
1225 for (std::size_t j = 0; j < NS_; ++j) nvec[j] += rx_[kfire].S[j];
1226 if (has_caps_) apply_caps(nvec, rx_[kfire].dep_slots);
1227 fluid_impulse(f, rx_[kfire], OF);
1228 collapse_fluid(nvec, f, v, OF);
1229 Pk[kfire] -= std::log(rng_.uniform());
1232 if (n % console_every == 0)
1234 static_cast<long>(n / console_every),
1235 "simulated %zu of %zu samples (%.0f%%), simulated time %.4g", n,
1236 static_cast<std::size_t
>(opt_.samples),
1237 100.0 *
static_cast<double>(n) /
static_cast<double>(opt_.samples), total_time);
1241 if (time_stopped && n_warm > 0 && n <= n_warm)
1243 "solver_ssa_nrm_spn: the wall-clock time budget (options.timeout) ran "
1244 "out inside the warmup, before any sample was collected");
1246 if (total_time > 0.0) {
1247 for (std::size_t ist = 0; ist < M_; ++ist)
1248 for (std::size_t c = 0; c < K_; ++c) {
1249 out.
QN(ist, c) /= total_time;
1250 out.
UN(ist, c) /= total_time;
1251 out.
TN(ist, c) /= total_time;
1253 for (std::size_t q = 0; q < nf; ++q) {
1254 QF[q] /= total_time;
1255 OF[q] /= total_time;
1260 for (std::size_t q = 0; q < nf; ++q) {
1261 const std::size_t ist = fl_ist_[q];
1262 for (std::size_t c = 0; c < K_; ++c) out.
QN(ist, c) = out.
UN(ist, c) = out.
TN(ist, c) = 0.0;
1263 if (K_ == 0)
continue;
1264 out.
QN(ist, 0) = QF[q];
1265 out.
UN(ist, 0) = std::isfinite(fl_cap_[q]) ? QF[q] / fl_cap_[q] : QF[q];
1266 out.
TN(ist, 0) = OF[q];
1268 for (std::size_t c = 0; c < K_; ++c) {
1269 out.
XN[c] = out.
TN(sn_.classes[c].refstat - 1, c);
1270 for (std::size_t ist = 0; ist < M_; ++ist)
1271 out.
RN(ist, c) = out.
TN(ist, c) > 0.0 ? out.
QN(ist, c) / out.
TN(ist, c) : 0.0;
1272 if (out.
XN[c] > 0.0) out.
CN[c] = sn_.classes[c].population / out.
XN[c];
1286void NrmSpnEngine<T>::fluid_resolve(
const std::vector<double>& n,
const std::vector<double>& f,
1287 std::vector<double>& eff, std::vector<double>& v, std::vector<double>& vin,
1288 std::vector<double>& vout)
const {
1289 const std::size_t nrx = rx_.size();
1290 const std::vector<double> still(f.size(), 0.0);
1291 std::vector<double> deg(nrx, 0.0);
1292 std::vector<bool> gok(nrx,
true), gnew(nrx,
true);
1293 for (std::size_t k = 0; k < nrx; ++k) {
1294 deg[k] = std::min(detail::spn_en_degree(n, rx_[k]), rx_[k].nservers);
1295 gok[k] = detail::spn_fluid_guard_holds(rx_[k], f, still);
1297 eff.assign(nrx, 0.0);
1298 for (
int it = 0; it < 20; ++it) {
1299 for (std::size_t k = 0; k < nrx; ++k) eff[k] = gok[k] ? deg[k] : 0.0;
1300 fluid_slope(f, eff, v, vin, vout);
1301 for (std::size_t k = 0; k < nrx; ++k) gnew[k] = detail::spn_fluid_guard_holds(rx_[k], f, v);
1302 if (gnew == gok)
return;
1306 "solver_ssa_nrm_spn: a guarded fluid flow switches its own guard on and off at the threshold (a sliding "
1307 "mode), which a sample path has no value for");
1315void NrmSpnEngine<T>::fluid_slope(
const std::vector<double>& f,
const std::vector<double>& eff,
1316 std::vector<double>& v, std::vector<double>& vin,
1317 std::vector<double>& vout)
const {
1318 const std::size_t nf = fl_node_.size();
1319 vin.assign(nf, 0.0);
1320 vout.assign(nf, 0.0);
1321 for (std::size_t k = 0; k < rx_.size(); ++k) {
1322 if (eff[k] <= 0.0)
continue;
1323 for (std::size_t t = 0; t < rx_[k].flow_q.size(); ++t) {
1324 const std::size_t q = rx_[k].flow_q[t];
1325 double rt = rx_[k].flow_rate[t] * eff[k];
1326 if (k < fm_.size() && !fm_[k].empty()) rt *= fm_[k][t];
1334 for (std::size_t q = 0; q < nf; ++q) {
1335 v[q] = vin[q] - vout[q];
1336 if ((f[q] <= 0.0 && v[q] < 0.0) || (f[q] >= fl_cap_[q] && v[q] > 0.0)) v[q] = 0.0;
1342void NrmSpnEngine<T>::fluid_next_det(
const std::vector<double>& f,
const std::vector<double>& v,
double& tdet,
1343 std::size_t& qdet,
double& fdet)
const {
1344 tdet = std::numeric_limits<double>::infinity();
1347 for (std::size_t q = 0; q < fl_node_.size(); ++q) {
1348 if (v[q] > 0.0 && std::isfinite(fl_cap_[q])) {
1349 const double t = (fl_cap_[q] - f[q]) / v[q];
1355 }
else if (v[q] < 0.0) {
1356 const double t = f[q] / (-v[q]);
1364 const std::vector<Rx>* sets[2] = {&rx_, &imm_};
1365 for (
int s = 0; s < 2; ++s)
1366 for (
const Rx& rec : *sets[s])
1367 for (std::size_t g = 0; g < rec.guard_q.size(); ++g) {
1368 const std::size_t q = rec.guard_q[g];
1369 const double thr = rec.guard_thr[g];
1370 if (v[q] == 0.0 || std::fabs(f[q] - thr) <= 1e-12 * std::max(1.0, std::fabs(thr)))
continue;
1371 const double t = (thr - f[q]) / v[q];
1372 if (t > 0.0 && t < tdet) {
1378 tdet = std::max(tdet, 0.0);
1386void NrmSpnEngine<T>::fluid_impulse(std::vector<double>& f,
const Rx& rec, std::vector<double>& OF)
const {
1387 for (std::size_t t = 0; t < rec.imp_q.size(); ++t) {
1388 const std::size_t q = rec.imp_q[t];
1389 const double fnew = std::min(std::max(f[q] + rec.imp_d[t], 0.0), fl_cap_[q]);
1390 if (fnew < f[q]) OF[q] += f[q] - fnew;
1400void NrmSpnEngine<T>::collapse_fluid(std::vector<double>& n, std::vector<double>& f,
const std::vector<double>& v,
1401 std::vector<double>& OF) {
1402 if (imm_.empty())
return;
1403 std::size_t steps = 0;
1405 std::vector<std::size_t> enabled;
1406 for (std::size_t m = 0; m < imm_.size(); ++m)
1407 if (detail::spn_en_degree(n, imm_[m]) >= 1.0 && detail::spn_fluid_guard_holds(imm_[m], f, v))
1408 enabled.push_back(m);
1409 if (enabled.empty())
return;
1410 double top_prio = -std::numeric_limits<double>::infinity();
1411 for (std::size_t i = 0; i < enabled.size(); ++i) top_prio = std::max(top_prio, imm_[enabled[i]].prio);
1412 std::vector<std::size_t> top;
1413 std::vector<double> w;
1414 for (std::size_t i = 0; i < enabled.size(); ++i)
1415 if (imm_[enabled[i]].prio == top_prio) {
1416 top.push_back(enabled[i]);
1417 w.push_back(imm_[enabled[i]].weight);
1419 const std::size_t pick = top.size() == 1 ? top[0] : top[rng_.draw(w)];
1420 for (std::size_t j = 0; j < NS_; ++j) n[j] += imm_[pick].S[j];
1421 fluid_impulse(f, imm_[pick], OF);
1422 if (++steps > kMaxImmSteps)
1424 "solver_ssa_nrm_spn: immediate-transition livelock -- the vanishing-marking collapse did not reach "
1425 "a tangible marking");
NumericError(const std::string &what)
UnsupportedError(const std::string &what)
A network plus its refreshed NetworkStruct.
NrmSpnEngine(const qn::NetworkStruct< T > &sn, const SsaOptions &opt)
SsaSolution run()
Run opt.samples firings and return the time-averaged metrics.
std::size_t nimmediate() const
The immediate-mode count, likewise.
std::size_t nreactions() const
The reaction count, for the tests that assert the builder.
The uniform source, MATLAB's rand.
static void loop(const char *fmt,...)
Announce an iteration loop and reset its reporting budget.
static void iter(long k, const char *fmt,...)
Report iteration k of the current loop.
The exception types the port throws.
Running progress log of a LINE solver run (the "solver console").
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
Dense matrix and non-owning view.
SnFluidVerdict sn_fluid_refusal(const qn::NetworkStruct< T > &sn)
Whether the net breaks a structural rule of an FSPN.
@ IMMEDIATE
fires with zero delay, resolved by weight and priority
InputError err(const std::string &msg, int line=-1)
std::size_t ssa_warmup_firings(double warmupfrac, std::size_t samples)
Firings whose tallies an engine discards: floor(warmupfrac * samples), with an unset (negative) fract...
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
Conservation laws of a layered queueing network, enumerated from its structure.
RootResult< T > root_brent(F f, const T &a0, const T &b0, const T &tol, unsigned maxiter=200)
Brent's method on a bracket with a sign change.
A queueing network and its refreshed NetworkStruct.
Deterministic scalar root finding.
Port of matlab/src/api/sn/sn_fluid_refusal.m.
Controls, results and the random source of SolverSSA.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
static constexpr double MaxInt
Stand-in for an unbounded COUNT, MATLAB GlobalConstants.MaxInt.
Controls, defaulting to SolverOptions('SSA') in the reference.
What the analyzer returns, in the same shape as the MVA and fluid results.
Matrix< double > StartN
The DERIVED rates, (nstations x nclasses): how often per unit time a class-r service STARTS at statio...
double simulated_time
Simulated time the metrics are averaged over; the reference's totalTime.
std::size_t samples
Reaction firings actually performed.
std::string method
The concrete algorithm, as the reference's method.
Matrix< double > PreemptN