LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ldes_station.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_SOLVERS_LDES_LDES_STATION_H
6#define LINE_SOLVERS_LDES_LDES_STATION_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The scheduling disciplines of the native LDES engine.
12 *
13 * TWO FAMILIES, and they are structurally different simulators sharing one
14 * station:
15 *
16 * - THE BUFFERED disciplines (FCFS, LCFS, SIRO, the priority variants, SJF,
17 * LJF, SEPT, LEPT) hold waiting jobs in an ORDER and hand the head to a
18 * free server. The discipline IS the order, so it lives entirely in
19 * `WaitCmp` below; everything downstream is the same code.
20 * - THE SHARING disciplines (PS, DPS, GPS, their priority variants and LPS)
21 * have no order at all. Every job in service advances at its own share of
22 * the server, so the station has no head and no service-start event: the
23 * residual work of EVERY job must be integrated forward and EVERY departure
24 * rescheduled whenever the population changes. `PsStation` does that.
25 *
26 * THE SERVICE TIME IS SAMPLED AT ARRIVAL, not at service start. This is the
27 * reference's choice (`customer.serviceTime = generateServiceTime(...)` in the
28 * arrival handlers) and it is forced: SJF, LJF and the size-based orders
29 * compare service times of jobs that have not started, so the sample must
30 * exist before the job is ordered. It is invisible under FCFS, where arrival
31 * and service order coincide, and visible under LCFS with a MAP service
32 * process, whose phase then advances in ARRIVAL order.
33 *
34 * PRIORITY ORDERS ASCENDING: a lower value is more urgent, 0 highest. That is
35 * LINE's convention throughout (`SaveHandlers` inverts it when exporting to
36 * JMT, which orders the other way), and every comparator here follows it.
37 */
38
39#include <algorithm>
40#include <cmath>
41#include <cstddef>
42#include <cstdint>
43#include <limits>
44#include <set>
45#include <vector>
46
48
49namespace line {
50namespace ldes {
51namespace engine {
52
53/**
54 * A job held by a station.
55 *
56 * `service`, `remaining` and `elapsed` are the three quantities the size-based
57 * orders need and are NOT redundant. `service` is the ORIGINAL requirement
58 * PSJF orders by; `remaining` is the residual SRPT and LRPT order by, equal to
59 * `service` until the job is first preempted; `elapsed` is the attained
60 * service FB and SETF order by. The reference keeps them in a side table
61 * (`preemptedJobHistory`, keyed by the arrival instants) because its wait
62 * queue holds a plain `Customer`; carrying them on the job is the same
63 * information without the lookup, and without the key collision two jobs
64 * arriving at the same instant would produce.
65 */
66struct Job {
67 std::size_t cls = 0;
68 int priority = 0;
69 double t_arr = 0.0; ///< arrival instant at this station
70 /**
71 * Time spent parked outside a WAITQ region before entering this station. It is part of the
72 * visit's response time (JMT and Solver_ssj keep the original arrival instant) but not of
73 * `t_arr`, which orders the buffer by the RELEASE instant, as the Java engine's orderTime does.
74 */
75 double region_wait = 0.0;
76 double t_sys = 0.0; ///< instant the current passage started
77 /**
78 * The class the current passage STARTED in (the class the Source emitted),
79 * -1 when unset. A system completion is credited to it, not to the class the
80 * job leaves in: MATLAB defines a class's XN as its rate through its
81 * reference station, which for an open class is the Source, so a chain that
82 * switches A -> B credits A. It is copied wherever `t_sys` is.
83 */
84 int sys_cls = -1;
85 double service = 0.0; ///< the sampled requirement, drawn at arrival
86 double remaining = 0.0; ///< residual work; equals `service` before any preemption
87 double elapsed = 0.0; ///< attained service across all its service intervals
88 double rank = 0.0; ///< SIRO's random key, drawn at arrival
89 double deadline = std::numeric_limits<double>::infinity(); ///< EDD/EDF key
90 double vft = 0.0; ///< FSP's virtual finish time, recomputed on demand
91 /**
92 * Identity of this job while it waits, so a reneging timer can find it.
93 *
94 * A timer names the job it was armed for, and the job may by then have
95 * entered service, been preempted back into the queue, or already left. An
96 * identity is the only thing that survives all three; the arrival instant
97 * cannot serve as one, because two jobs admitted at the same instant --
98 * routine on a closed model placed at t=0 -- would share it.
99 */
100 std::uint64_t id = 0;
101 /**
102 * The fork synchronization this job is a sibling of, 0 when it is not one.
103 *
104 * It rides on the JOB and not on the station because siblings of different
105 * parents interleave freely at every station between the Fork and the Join.
106 */
107 std::uint64_t parent = 0;
108 /**
109 * How many times this job has already retried from an orbit.
110 *
111 * It rides on the job because `maxAttempts` bounds the retries of ONE job,
112 * not of the station: a per-station counter would cap the orbit's total
113 * traffic instead and would let a job retry forever as long as others gave
114 * up.
115 */
116 int attempts = 0;
117 /**
118 * The SYNCHRONOUS CALL this job belongs to, 0 when it belongs to none.
119 *
120 * It rides on the job because the call is answered by a REPLY that comes
121 * back from somewhere else entirely: this identity is the only link between
122 * that reply and the server still held for it, and `id` cannot serve as one,
123 * being reassigned at every admission.
124 */
125 std::uint64_t call = 0;
126 /**
127 * The generation its currently scheduled completion was pushed under.
128 *
129 * Only an INFINITE SERVER needs it: a buffered station keeps the generation
130 * on the slot (`server_tag`) and a sharing one on its `PsJob`, but a Delay
131 * holds neither, so a think time re-timed by a global dependence has no
132 * other way to invalidate the departure already in the event list.
133 */
134 std::uint64_t tag = 0;
135 /**
136 * `options.init_jobs`: the caller's tag for this job, -1 when untagged. It
137 * does not survive a hop, because the next station receives a new `Job`, so
138 * `jobDepartures` records the departure from the station it was placed at.
139 */
140 std::int64_t ext = -1;
141 /** An init_jobs residual: `service` is the work still owed, not a fresh draw. */
142 bool preset = false;
143 /** A Delay job's completion instant, read by the track_jobs export. */
144 double due = 0.0;
145 /**
146 * Round robin: the instant a job whose quantum expired rejoined the waiting
147 * room, which is its buffer order key from then on (the TAIL of the queue);
148 * negative until then, when the key is `t_arr`. It is NOT `t_arr` itself,
149 * which the response time is measured from, as `Solver_ssj` keeps the
150 * arrival instant and moves only `orderTime`.
151 */
152 double order_time = -1.0;
153};
154
155/** True for the disciplines that interrupt a job already in service. */
157 switch (s) {
173 // EDF is the PREEMPTIVE deadline order (EDD is its non-preemptive twin): an arrival with an earlier absolute
174 // deadline displaces the in-service job with the latest one, preemptive resume, as `Solver_ssj` does.
176 return true;
177 default:
178 return false;
179 }
180}
181
182/**
183 * PREEMPTIVE RESUME, as against preemptive restart.
184 *
185 * A resumed job continues from its residual work; a restarted one draws a
186 * FRESH requirement and discards what it had done. That distinction is the
187 * whole of the PR/PI split and it is not cosmetic: under exponential service
188 * the two agree in distribution (memorylessness) and under any other law they
189 * do not, so a model that uses PI to represent lost work is silently served
190 * as PR on a Coxian. Every size-based policy is RESUME -- restarting a job
191 * would make its own scheduling key meaningless.
192 */
194 switch (s) {
199 return false;
200 default:
201 return is_preemptive(s);
202 }
203}
204
205/** True for the orders whose key is the job's size, residual or attained work. */
207 switch (s) {
215 return true;
216 default:
217 return false;
218 }
219}
220
221/** True for the disciplines that share the server instead of ordering a queue. */
223 switch (s) {
231 return true;
232 default:
233 return false;
234 }
235}
236
237/**
238 * The waiting-room order of a buffered discipline.
239 *
240 * Used as a `std::priority_queue` comparator, which pops the GREATEST element,
241 * so every rule below is inverted relative to the reference's `Comparator`
242 * (which orders ascending and polls the least). Getting that backwards turns
243 * FCFS into LCFS silently -- both run, both conserve jobs, and only the
244 * response-time variance tells them apart.
245 */
246struct WaitCmp {
248 const std::vector<double>* class_mean = 0; ///< mean service per class, for SEPT/LEPT
249
250 bool operator()(const Job& a, const Job& b) const {
251 switch (sched) {
255 return a.t_arr < b.t_arr; // latest first
257 return a.rank > b.rank;
261 // Plain FCFSPR/FCFSPI are DELIBERATELY absent: a policy that did
262 // not declare itself priority-aware must not read `priority`, so
263 // they fall to the default arm and queue in arrival order.
264 if (a.priority != b.priority) return a.priority > b.priority;
265 return a.t_arr > b.t_arr;
269 if (a.priority != b.priority) return a.priority > b.priority;
270 return a.t_arr < b.t_arr;
272 if (a.service != b.service) return a.service > b.service;
273 return a.t_arr > b.t_arr;
275 if (a.service != b.service) return a.service < b.service;
276 return a.t_arr > b.t_arr;
278 const double ma = mean_of(a), mb = mean_of(b);
279 if (ma != mb) return ma > mb; // shortest expected first
280 return a.t_arr > b.t_arr;
281 }
283 const double ma = mean_of(a), mb = mean_of(b);
284 if (ma != mb) return ma < mb;
285 return a.t_arr > b.t_arr;
286 }
289 if (a.deadline != b.deadline) return a.deadline > b.deadline;
290 return a.t_arr > b.t_arr;
292 if (a.remaining != b.remaining) return a.remaining > b.remaining;
293 return a.t_arr > b.t_arr;
295 if (a.priority != b.priority) return a.priority > b.priority;
296 if (a.remaining != b.remaining) return a.remaining > b.remaining;
297 return a.t_arr > b.t_arr;
299 if (a.remaining != b.remaining) return a.remaining < b.remaining;
300 return a.service < b.service;
302 // The ORIGINAL requirement, not the residual: a job that has
303 // already been served keeps the rank its full size gave it.
304 if (a.service != b.service) return a.service > b.service;
305 return a.t_arr > b.t_arr;
308 // Least attained service first. FB and SETF share this order;
309 // they differ in WHEN the running job is interrupted, not in
310 // how the waiting ones are ranked.
311 if (a.elapsed != b.elapsed) return a.elapsed > b.elapsed;
312 return a.t_arr > b.t_arr;
314 if (a.vft != b.vft) return a.vft > b.vft;
315 return a.t_arr > b.t_arr;
317 // FCFS on the instant the job last joined the waiting room: a
318 // job preempted by its quantum goes to the tail.
319 const double ka = a.order_time >= 0.0 ? a.order_time : a.t_arr;
320 const double kb = b.order_time >= 0.0 ? b.order_time : b.t_arr;
321 if (ka != kb) return ka > kb;
322 return a.t_arr > b.t_arr;
323 }
324 default: // FCFS and anything ordered like it
325 return a.t_arr > b.t_arr;
326 }
327 }
328
329private:
330 double mean_of(const Job& j) const {
331 if (class_mean == 0 || j.cls >= class_mean->size()) return 0.0;
332 return (*class_mean)[j.cls];
333 }
334};
335
336/**
337 * THE WAITING ROOM IS A java.util.PriorityQueue, ALGORITHM FOR ALGORITHM.
338 *
339 * The reference's comparators carry NO tie-break (FCFS compares `orderTime`
340 * alone), so jobs with equal keys -- a closed population all admitted at t = 0,
341 * simultaneous arrivals under deterministic times -- leave in whatever order
342 * the binary heap's sift rules produce. libstdc++'s `pop_heap` moves the hole
343 * to a leaf and sifts back up, which settles ties differently, so the native
344 * engine served the same jobs in a different order and the job ids of a sample
345 * path parted company at the first tied start (closed 2026-11-14). These four
346 * functions are `offer`, `poll`, `removeAt` and `heapify` of OpenJDK's
347 * PriorityQueue (identical in 8 and 17), with `cmp` the inverted comparator of
348 * `WaitCmp`: `compare(x, y) > 0` there is `cmp(x, y)` here, and
349 * `compare(x, y) >= 0` is `!cmp(y, x)`.
350 */
351template <typename T, typename Cmp>
352inline std::size_t jpq_sift_down(std::vector<T>& es, std::size_t k, T x, std::size_t n, const Cmp& cmp) {
353 const std::size_t half = n >> 1;
354 while (k < half) {
355 std::size_t child = 2 * k + 1;
356 const std::size_t right = child + 1;
357 if (right < n && cmp(es[child], es[right])) child = right;
358 if (!cmp(x, es[child])) break;
359 es[k] = es[child];
360 k = child;
361 }
362 es[k] = x;
363 return k;
364}
365
366template <typename T, typename Cmp>
367inline void jpq_sift_up(std::vector<T>& es, std::size_t k, T x, const Cmp& cmp) {
368 while (k > 0) {
369 const std::size_t parent = (k - 1) >> 1;
370 if (!cmp(es[parent], x)) break;
371 es[k] = es[parent];
372 k = parent;
373 }
374 es[k] = x;
375}
376
377/** PriorityQueue.offer: append, then sift the new element up. */
378template <typename T, typename Cmp>
379inline void jpq_offer(std::vector<T>& es, const T& x, const Cmp& cmp) {
380 es.push_back(x);
381 jpq_sift_up(es, es.size() - 1, x, cmp);
382}
383
384/** PriorityQueue.poll: take the root, sift the LAST element down from it. */
385template <typename T, typename Cmp>
386inline T jpq_poll(std::vector<T>& es, const Cmp& cmp) {
387 T result = es.front();
388 T x = es.back();
389 es.pop_back();
390 if (!es.empty()) jpq_sift_down(es, 0, x, es.size(), cmp);
391 return result;
392}
393
394/** PriorityQueue.removeAt: the last element fills the hole, down then up. */
395template <typename T, typename Cmp>
396inline void jpq_remove_at(std::vector<T>& es, std::size_t i, const Cmp& cmp) {
397 const std::size_t s = es.size() - 1;
398 if (s == i) {
399 es.pop_back();
400 return;
401 }
402 T moved = es[s];
403 es.pop_back();
404 if (jpq_sift_down(es, i, moved, s, cmp) == i) jpq_sift_up(es, i, moved, cmp);
405}
406
407/** PriorityQueue.heapify, for a buffer whose keys were rewritten in place. */
408template <typename T, typename Cmp>
409inline void jpq_heapify(std::vector<T>& es, const Cmp& cmp) {
410 const std::size_t n = es.size();
411 for (std::size_t i = n >> 1; i-- > 0;) jpq_sift_down(es, i, es[i], n, cmp);
412}
413
414/** A job being served by a sharing discipline, with the work it still owes. */
415struct PsJob {
416 std::size_t cls = 0;
417 int priority = 0;
418 double t_arr = 0.0;
419 double region_wait = 0.0; ///< Job::region_wait, carried across the sharing station
420 double t_sys = 0.0;
421 int sys_cls = -1; ///< Job::sys_cls
422 double total = 0.0; ///< the sampled requirement
423 double remaining = 0.0; ///< residual work, in service-time units
424 std::uint64_t tag = 0; ///< identifies the departure event scheduled for it
425 /**
426 * The fork the job belongs to, carried across the sharing station.
427 *
428 * A buffered station keeps the whole `Job` in its server slot and hands it
429 * back at the completion, so the identity survives; a sharing station holds
430 * this reduced record instead and would hand back a DEFAULT-CONSTRUCTED one.
431 * A sibling leaving with parent 0 matches no fork at the Join and is
432 * discarded there, which drains a closed fork-join model after one pass.
433 */
434 std::uint64_t parent = 0;
435 std::int64_t ext = -1; ///< Job::ext, carried across the sharing station
436 std::uint64_t id = 0; ///< Job::id, the identity the sample-path export follows
437};
438
439/**
440 * The per-job shares of a sharing discipline, in units of one server.
441 *
442 * `c` is the station's effective server count: with n <= c every job runs at
443 * rate 1 and the station is an infinite server; above that the capacity is
444 * split. Each rule is capped at 1 because ONE job cannot consume more than ONE
445 * server however the weights fall -- dropping that cap is what makes a
446 * two-class DPS station report a utilization above one.
447 *
448 * Transcribed from `calculatePSRates` and the five rules under it.
449 */
450inline std::vector<double> ps_shares(lang::SchedStrategy sched, const std::vector<PsJob>& jobs,
451 double c, const std::vector<double>& weight,
452 std::size_t nclasses) {
453 const std::size_t n = jobs.size();
454 std::vector<double> rates(n, 0.0);
455 if (n == 0) return rates;
456
457 const bool prio = (sched == lang::SchedStrategy::PSPRIO ||
460 const bool weighted_by_job = (sched == lang::SchedStrategy::DPS ||
462 const bool weighted_by_class = (sched == lang::SchedStrategy::GPS ||
464
465 if (!prio) {
466 if (weighted_by_job) {
467 double tot = 0.0;
468 for (const PsJob& j : jobs) tot += weight[j.cls];
469 if (tot > 0.0) {
470 for (std::size_t i = 0; i < n; ++i)
471 rates[i] = std::min(1.0, weight[jobs[i].cls] * c / tot);
472 return rates;
473 }
474 } else if (weighted_by_class) {
475 std::vector<int> per_class(nclasses, 0);
476 for (const PsJob& j : jobs) ++per_class[j.cls];
477 double tot = 0.0;
478 for (std::size_t k = 0; k < nclasses; ++k)
479 if (per_class[k] > 0) tot += weight[k];
480 if (tot > 0.0) {
481 for (std::size_t i = 0; i < n; ++i) {
482 const std::size_t k = jobs[i].cls;
483 rates[i] = std::min(1.0, (weight[k] / tot / per_class[k]) * c);
484 }
485 return rates;
486 }
487 }
488 // PS, LPS, and the degenerate all-zero-weight case: equal shares.
489 const double share = std::min(1.0, c / static_cast<double>(n));
490 for (std::size_t i = 0; i < n; ++i) rates[i] = share;
491 return rates;
492 }
493
494 // The priority variants give the whole station to the most urgent class
495 // present, and only what is left over to the next -- so an uncongested
496 // station (n <= c) has nothing to arbitrate and every job runs at 1.
497 if (static_cast<double>(n) <= c) {
498 for (std::size_t i = 0; i < n; ++i) rates[i] = 1.0;
499 return rates;
500 }
501 std::set<int> prios;
502 for (const PsJob& j : jobs) prios.insert(j.priority);
503 double remaining = c;
504 for (std::set<int>::const_iterator it = prios.begin(); it != prios.end(); ++it) {
505 if (remaining <= 0.0) break;
506 const int p = *it;
507 int count = 0;
508 double tot_job_weight = 0.0;
509 std::vector<int> per_class(nclasses, 0);
510 for (const PsJob& j : jobs)
511 if (j.priority == p) {
512 ++count;
513 tot_job_weight += weight[j.cls];
514 ++per_class[j.cls];
515 }
516 const double allocated = std::min(remaining, static_cast<double>(count));
517 double tot_class_weight = 0.0;
518 for (std::size_t k = 0; k < nclasses; ++k)
519 if (per_class[k] > 0) tot_class_weight += weight[k];
520
521 for (std::size_t i = 0; i < n; ++i) {
522 if (jobs[i].priority != p) continue;
523 const std::size_t k = jobs[i].cls;
524 if (sched == lang::SchedStrategy::DPSPRIO && tot_job_weight > 0.0)
525 rates[i] = std::min(1.0, weight[k] * allocated / tot_job_weight);
526 else if (sched == lang::SchedStrategy::GPSPRIO && tot_class_weight > 0.0)
527 rates[i] = std::min(1.0, (weight[k] / tot_class_weight / per_class[k]) * allocated);
528 else
529 rates[i] = allocated / count;
530 }
531 remaining -= allocated;
532 }
533 return rates;
534}
535
536/**
537 * FSP's virtual finish time: when `target` would finish if the station ran
538 * processor sharing from now on.
539 *
540 * Sort every residual work at the station, then walk it: while n jobs remain
541 * each advances at min(1, c/n), so the wall time to clear the k-th smallest
542 * residual is the sum of (w_k - w_{k-1}) / rate over the ranks below it. FSP
543 * then serves in that order, which is what makes it dominate PS job by job.
544 * Transcribes `computeFSPVirtualFinishTime`.
545 */
546inline double fsp_virtual_finish(const std::vector<double>& residuals, double target_work,
547 double c, double now) {
548 std::vector<double> works = residuals;
549 std::sort(works.begin(), works.end());
550 const std::size_t n = works.size();
551 double cumulative = 0.0, prev = 0.0;
552 for (std::size_t rank = 0; rank < n; ++rank) {
553 const double w = works[rank];
554 const double rate = std::min(1.0, c / static_cast<double>(n - rank));
555 if (rate > 0.0) cumulative += (w - prev) / rate;
556 if (w >= target_work) return now + cumulative;
557 prev = w;
558 }
559 return now + cumulative;
560}
561
562/**
563 * Which job in service `arriving` displaces, or `in_service.size()` for none.
564 *
565 * ONE RULE PER FAMILY, transcribed from `shouldPreemptForLCFS`,
566 * `shouldPreemptForFCFS` and `shouldPreemptForSizeBasedPolicy` together with
567 * their `findJobToPreempt*` counterparts. The two halves are fused here because
568 * they ask the same question twice in the reference -- once to decide and once
569 * to choose -- and answering it once cannot disagree with itself.
570 *
571 * THE PRIORITY VARIANTS PREEMPT ONLY STRICTLY LOWER PRIORITY, AND ONLY THEY DO.
572 * There are FOUR distinct tests here, not one:
573 * - `LCFSPR`/`LCFSPI` preempt UNCONDITIONALLY. Last-come-first-served keeps the
574 * NEWEST job in service, so the newcomer takes the head with no class ordering.
575 * - `LCFSPRPRIO`/`LCFSPIPRIO` preempt a job whose priority value is AT LEAST the
576 * arrival's, a strictly lower one first. `started[j]` is when `in_service[j]`
577 * last took its server, the tie-break among equals.
578 * - `FCFSPRPRIO`/`FCFSPIPRIO` preempt only one STRICTLY GREATER.
579 * - `FCFSPR`/`FCFSPI` preempt NOTHING AT ALL. Preemption under the FCFS families
580 * is a PRIORITY act, so it belongs to the PRIO names alone and only ACROSS
581 * priority groups: the base rule serves in ARRIVAL ORDER, and a plain variant
582 * is absent from the model's priority-aware set (the user is warned that
583 * "Priorities will be ignored"), so every class sits in ONE group and the
584 * arrival can only WAIT. Reading `priority` here anyway -- which this function
585 * did until 2026-09-12, sharing an arm with the PRIO pair -- infers a policy
586 * the model never declared; it is invisible for flat priorities and silently
587 * turns a declared-FCFS station into a preemptive-priority one otherwise.
588 * Collapsing those four tests into fewer turns a priority station into a
589 * thrashing one, or into a non-preemptive one, depending which way it falls.
590 */
591inline std::size_t preemption_victim(lang::SchedStrategy sched, const std::vector<Job>& in_service,
592 const std::vector<double>& started, const Job& arriving,
593 double c, double now) {
594 const std::size_t none = in_service.size();
595 if (in_service.empty()) return none;
596
597 switch (sched) {
600 // Displace the OLDEST job in service: the newcomer takes the head
601 // of a last-come-first-served station unconditionally.
602 std::size_t best = none;
603 double oldest = std::numeric_limits<double>::infinity();
604 for (std::size_t j = 0; j < in_service.size(); ++j)
605 if (in_service[j].t_arr < oldest) {
606 oldest = in_service[j].t_arr;
607 best = j;
608 }
609 return best;
610 }
613 // Two tiers, as findJobToPreempt: the least urgent STRICTLY lower job (earliest arrival
614 // among ties), else the equal one that STARTED earliest. A single oldest-eligible pass
615 // displaces a more urgent job while a less urgent one keeps its server whenever c > 1.
616 std::size_t best = none;
617 for (std::size_t j = 0; j < in_service.size(); ++j) {
618 if (in_service[j].priority <= arriving.priority) continue;
619 if (best == none || in_service[j].priority > in_service[best].priority ||
620 (in_service[j].priority == in_service[best].priority &&
621 in_service[j].t_arr < in_service[best].t_arr))
622 best = j;
623 }
624 if (best != none) return best;
625 for (std::size_t j = 0; j < in_service.size(); ++j)
626 if (in_service[j].priority == arriving.priority &&
627 (best == none || started[j] < started[best]))
628 best = j;
629 return best;
630 }
633 // NOTHING. An FCFS-PR/PI arrival never preempts: the base rule serves
634 // in ARRIVAL ORDER and the plain variants declare no priorities, so
635 // every class is in one group and the arrival can only wait.
636 return none;
639 // The least urgent job in service, tie-broken by the LATEST service
640 // start: among equals, the one that has invested least is displaced.
641 std::size_t best = none;
642 for (std::size_t j = 0; j < in_service.size(); ++j) {
643 if (in_service[j].priority <= arriving.priority) continue;
644 if (best == none || in_service[j].priority > in_service[best].priority ||
645 (in_service[j].priority == in_service[best].priority &&
646 in_service[j].t_arr > in_service[best].t_arr))
647 best = j;
648 }
649 return best;
650 }
653 // The job ranked LAST: under SRPTPRIO the lowest priority (largest
654 // value) first, then the most remaining work, as in WaitCmp. A
655 // higher-priority arrival displaces a lower-priority job whatever
656 // their sizes; picking the largest residual alone let a high-priority
657 // job wait behind a low-priority one with less work left.
658 const bool prio = (sched == lang::SchedStrategy::SRPTPRIO);
659 std::size_t worst = 0;
660 for (std::size_t j = 1; j < in_service.size(); ++j) {
661 if (prio && in_service[j].priority != in_service[worst].priority) {
662 if (in_service[j].priority > in_service[worst].priority) worst = j;
663 } else if (in_service[j].remaining > in_service[worst].remaining) {
664 worst = j;
665 }
666 }
667 if (prio && arriving.priority != in_service[worst].priority)
668 return (arriving.priority < in_service[worst].priority) ? worst : none;
669 return (arriving.remaining < in_service[worst].remaining) ? worst : none;
670 }
672 std::size_t largest = 0;
673 for (std::size_t j = 1; j < in_service.size(); ++j)
674 if (in_service[j].service > in_service[largest].service) largest = j;
675 return (arriving.service < in_service[largest].service) ? largest : none;
676 }
679 // A fresh arrival has attained nothing, so it displaces whichever
680 // job has attained the most -- provided that is more than nothing.
681 std::size_t most = 0;
682 for (std::size_t j = 1; j < in_service.size(); ++j)
683 if (in_service[j].elapsed > in_service[most].elapsed) most = j;
684 return (in_service[most].elapsed > arriving.elapsed) ? most : none;
685 }
687 std::size_t least = 0;
688 for (std::size_t j = 1; j < in_service.size(); ++j)
689 if (in_service[j].remaining < in_service[least].remaining) least = j;
690 return (arriving.remaining > in_service[least].remaining) ? least : none;
691 }
693 std::vector<double> works;
694 for (const Job& j : in_service) works.push_back(j.remaining);
695 works.push_back(arriving.remaining);
696 const double arrival_vft = fsp_virtual_finish(works, arriving.remaining, c, now);
697 std::size_t worst = 0;
698 double worst_vft = -std::numeric_limits<double>::infinity();
699 for (std::size_t j = 0; j < in_service.size(); ++j) {
700 const double v = fsp_virtual_finish(works, in_service[j].remaining, c, now);
701 if (v > worst_vft) {
702 worst_vft = v;
703 worst = j;
704 }
705 }
706 return (arrival_vft < worst_vft) ? worst : none;
707 }
709 // The in-service job with the LATEST absolute deadline (first among ties), displaced only by an arrival
710 // whose deadline is strictly earlier, as `Solver_ssj.shouldPreempt`.
711 std::size_t latest = 0;
712 for (std::size_t j = 1; j < in_service.size(); ++j)
713 if (in_service[j].deadline > in_service[latest].deadline) latest = j;
714 return (arriving.deadline < in_service[latest].deadline) ? latest : none;
715 }
716 default:
717 return none;
718 }
719}
720
721} // namespace engine
722} // namespace ldes
723} // namespace line
724
725#endif // LINE_SOLVERS_LDES_LDES_STATION_H
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
std::size_t preemption_victim(lang::SchedStrategy sched, const std::vector< Job > &in_service, const std::vector< double > &started, const Job &arriving, double c, double now)
Which job in service arriving displaces, or in_service.size() for none.
void jpq_heapify(std::vector< T > &es, const Cmp &cmp)
PriorityQueue.heapify, for a buffer whose keys were rewritten in place.
void jpq_sift_up(std::vector< T > &es, std::size_t k, T x, const Cmp &cmp)
std::size_t jpq_sift_down(std::vector< T > &es, std::size_t k, T x, std::size_t n, const Cmp &cmp)
THE WAITING ROOM IS A java.util.PriorityQueue, ALGORITHM FOR ALGORITHM.
void jpq_offer(std::vector< T > &es, const T &x, const Cmp &cmp)
PriorityQueue.offer: append, then sift the new element up.
bool is_preemptive(lang::SchedStrategy s)
True for the disciplines that interrupt a job already in service.
double fsp_virtual_finish(const std::vector< double > &residuals, double target_work, double c, double now)
FSP's virtual finish time: when target would finish if the station ran processor sharing from now on.
std::vector< double > ps_shares(lang::SchedStrategy sched, const std::vector< PsJob > &jobs, double c, const std::vector< double > &weight, std::size_t nclasses)
The per-job shares of a sharing discipline, in units of one server.
bool is_preemptive_resume(lang::SchedStrategy s)
PREEMPTIVE RESUME, as against preemptive restart.
bool is_ps_family(lang::SchedStrategy s)
True for the disciplines that share the server instead of ordering a queue.
bool is_size_based(lang::SchedStrategy s)
True for the orders whose key is the job's size, residual or attained work.
void jpq_remove_at(std::vector< T > &es, std::size_t i, const Cmp &cmp)
PriorityQueue.removeAt: the last element fills the hole, down then up.
T jpq_poll(std::vector< T > &es, const Cmp &cmp)
PriorityQueue.poll: take the root, sift the LAST element down from it.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A job held by a station.
double due
A Delay job's completion instant, read by the track_jobs export.
double deadline
EDD/EDF key.
int sys_cls
The class the current passage STARTED in (the class the Source emitted), -1 when unset.
double region_wait
Time spent parked outside a WAITQ region before entering this station.
double t_arr
arrival instant at this station
std::uint64_t call
The SYNCHRONOUS CALL this job belongs to, 0 when it belongs to none.
double rank
SIRO's random key, drawn at arrival.
double vft
FSP's virtual finish time, recomputed on demand.
bool preset
An init_jobs residual: service is the work still owed, not a fresh draw.
int attempts
How many times this job has already retried from an orbit.
double order_time
Round robin: the instant a job whose quantum expired rejoined the waiting room, which is its buffer o...
double t_sys
instant the current passage started
std::uint64_t tag
The generation its currently scheduled completion was pushed under.
double elapsed
attained service across all its service intervals
double service
the sampled requirement, drawn at arrival
std::int64_t ext
options.init_jobs: the caller's tag for this job, -1 when untagged.
double remaining
residual work; equals service before any preemption
std::uint64_t parent
The fork synchronization this job is a sibling of, 0 when it is not one.
A job being served by a sharing discipline, with the work it still owes.
double total
the sampled requirement
std::uint64_t tag
identifies the departure event scheduled for it
double region_wait
Job::region_wait, carried across the sharing station.
double remaining
residual work, in service-time units
int sys_cls
Job::sys_cls.
std::uint64_t parent
The fork the job belongs to, carried across the sharing station.
std::int64_t ext
Job::ext, carried across the sharing station.
The waiting-room order of a buffered discipline.
lang::SchedStrategy sched
bool operator()(const Job &a, const Job &b) const
const std::vector< double > * class_mean
mean service per class, for SEPT/LEPT