Skip to main content

resource_timeline/envelope/
precedence.rs

1//! Precedence constraints between envelope activities: propagation and coupled extremes.
2//!
3//! A [`Precedence`] requires `time(after, to) - time(before, from) >= gap` between the starts
4//! or ends of two activities. With the start windows and the duration ranges of contingent
5//! activities (`end - start` in `[shortest, longest]`) this is a simple temporal network over
6//! the starts and ends. The envelope uses it twice:
7//!
8//! 1. **Propagation.** All-pairs shortest paths (Floyd-Warshall) give the tightest window of
9//!    each start, the tightest duration range of each contingent activity, and the tightest
10//!    separation of each pair of time points. Every admitted schedule stays inside them, so
11//!    separate extremes over them are still sound, and tighter.
12//! 2. **Coupled extremes** of the activities that take part in a precedence:
13//!    - all stepwise (steps and claims at fixed offsets): Muscettola's construction. Every
14//!      impact tick is forced at or before `t`, forced after it, or pending; the extreme is the
15//!      forced part plus a maximum-weight closure of the pending events under "never later
16//!      than", found by a minimum cut. Exact, and independent of the window lengths.
17//!    - with rates or uncertain durations: every impact is a separable function of its time
18//!      points (a step an indicator, a claim a difference of two indicators, a rate a difference
19//!      of two clamped ramps), so the extreme is the maximum of a separable function under
20//!      difference constraints, which the discretised minimum cut of the `cut` module solves
21//!      exactly. Its graph has a node per domain value, so it is used only while the domains
22//!      fit a node budget ([`Envelope::with_cut_budget`](super::Envelope::with_cut_budget)).
23//!    - above the budget: closure for the stepwise activities, separate extremes over the
24//!      tightened windows and durations for the others. Sound, but a possible violation may be
25//!      a false alarm.
26//!
27//! ```mermaid
28//! graph LR
29//!     windows["windows and precedences"] --> fw["Floyd-Warshall: tightened windows, separations"]
30//!     fw --> events["stepwise: events forced or pending"]
31//!     events --> closure["max-weight closure by min cut"]
32//!     fw --> layered["rates, durations: layered graph per time point"]
33//!     layered --> cut["min cut, within the node budget"]
34//!     closure --> level["coupled extreme level"]
35//!     cut --> level
36//! ```
37
38use alloc::vec;
39use alloc::vec::Vec;
40
41use super::closure::max_weight_closure;
42use super::contingent::{Anchor, Uncertain};
43use super::cut::{Variable, max_separable, nodes_for};
44use super::member::{Extreme, Member, Shape};
45use crate::{ActivityId, Error, Tick, Window};
46
47/// Which time point of an activity a [`Precedence`] refers to.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
50pub enum Endpoint {
51    /// The start.
52    Start,
53    /// The end: for a [`Contingent`](super::Contingent) activity the start plus its uncertain
54    /// duration, for a [`Flexible`](super::Flexible) activity the start plus the last tick of
55    /// its impacts (the start itself without impacts).
56    End,
57}
58
59/// A required order between time points of two envelope activities:
60/// `time(after, to) - time(before, from) >= gap`.
61///
62/// The four combinations of [`Endpoint`]s give start-start, start-end, end-start and end-end
63/// constraints. `gap` may be negative. "`after` starts once `before` has ended" is
64/// [`Precedence::after_end`]; for a contingent `before` that waits for its actual end.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
67pub struct Precedence {
68    /// The earlier activity. Every envelope activity with this id is constrained.
69    pub before: ActivityId,
70    /// The time point of `before` the gap is measured from.
71    pub from: Endpoint,
72    /// The later activity. Every envelope activity with this id is constrained.
73    pub after: ActivityId,
74    /// The time point of `after` the gap is measured to.
75    pub to: Endpoint,
76    /// The smallest allowed distance between the two time points, in ticks.
77    pub gap: Tick,
78}
79
80impl Precedence {
81    /// `start(after) - start(before) >= gap`.
82    #[must_use]
83    pub const fn starts(before: ActivityId, after: ActivityId, gap: Tick) -> Self {
84        Self {
85            before,
86            from: Endpoint::Start,
87            after,
88            to: Endpoint::Start,
89            gap,
90        }
91    }
92
93    /// `start(after) - end(before) >= gap`: `after` starts `gap` ticks after `before` ended.
94    #[must_use]
95    pub const fn after_end(before: ActivityId, after: ActivityId, gap: Tick) -> Self {
96        Self {
97            before,
98            from: Endpoint::End,
99            after,
100            to: Endpoint::Start,
101            gap,
102        }
103    }
104}
105
106/// How the coupled members are evaluated.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108enum Mode {
109    /// Every coupled member is stepwise: maximum-weight closure over pending events, exact.
110    Closure,
111    /// Some coupled member has rates or an uncertain duration, and the domains fit the cut
112    /// budget: the discretised minimum cut over all coupled time points, exact.
113    Cut,
114    /// The domains exceed the cut budget: closure over the stepwise members, separate
115    /// extremes over tightened windows and durations for the others, sound.
116    Partial,
117}
118
119/// The temporal network over the time points of the members.
120#[derive(Debug, Clone)]
121pub(crate) struct Network {
122    /// The number of nodes, the origin being node 0.
123    nodes: usize,
124    /// `distance[x * nodes + y]`: the largest possible `time(y) - time(x)`, `None` if
125    /// unbounded.
126    distance: Vec<Option<i128>>,
127    /// The start node of each member.
128    start: Vec<usize>,
129    /// The end node of each contingent member.
130    end: Vec<Option<usize>>,
131    /// Whether member `i` is evaluated jointly.
132    coupled: Vec<bool>,
133    /// How the jointly evaluated members are evaluated.
134    mode: Mode,
135}
136
137/// The windows and durations a propagation tightened.
138pub(crate) struct Tightened {
139    /// The start window of each member.
140    pub(crate) windows: Vec<Window>,
141    /// The duration range of each member (`[0, 0]` for fixed impacts).
142    pub(crate) durations: Vec<Window>,
143}
144
145impl Network {
146    /// Propagates `precedences` over the windows and durations of `members`.
147    ///
148    /// Coupled members are evaluated by closure if all are stepwise, by the discretised cut
149    /// if their time-point domains need at most `budget` graph nodes, and partly separately
150    /// otherwise.
151    ///
152    /// # Errors
153    ///
154    /// - [`Error::UnknownActivity`] if a precedence names an activity that is not a member.
155    /// - [`Error::InconsistentPrecedences`] if no schedule satisfies the windows, durations
156    ///   and precedences together.
157    /// - [`Error::OutOfMemory`] if the distance matrix cannot be allocated.
158    pub(crate) fn propagate(
159        members: &[Member<'_>],
160        precedences: &[Precedence],
161        budget: usize,
162    ) -> Result<(Tightened, Self), Error> {
163        let (start, end, nodes) = number_nodes(members);
164        let mut matrix = Matrix::new(nodes)?;
165        for (index, member) in members.iter().enumerate() {
166            matrix.tighten(0, start[index], i128::from(member.window.latest()));
167            matrix.tighten(start[index], 0, -i128::from(member.window.earliest()));
168            if let Some(end) = end[index] {
169                let duration = member.duration();
170                matrix.tighten(start[index], end, i128::from(duration.latest()));
171                matrix.tighten(end, start[index], -i128::from(duration.earliest()));
172            }
173        }
174
175        let point = |index: usize, endpoint: Endpoint| match (endpoint, end[index]) {
176            (Endpoint::Start, _) => (start[index], 0),
177            (Endpoint::End, Some(end)) => (end, 0),
178            (Endpoint::End, None) => (start[index], i128::from(members[index].span())),
179        };
180        let mut coupled = vec![false; members.len()];
181        for precedence in precedences {
182            let before = indices_of(members, precedence.before)?;
183            let after = indices_of(members, precedence.after)?;
184            for b in before.clone() {
185                for a in after.clone() {
186                    let (from, from_offset) = point(b, precedence.from);
187                    let (to, to_offset) = point(a, precedence.to);
188                    // to + to_offset - (from + from_offset) >= gap
189                    // <=> from - to <= to_offset - from_offset - gap.
190                    let bound = to_offset - from_offset - i128::from(precedence.gap);
191                    matrix.tighten(to, from, bound);
192                    coupled[a] = true;
193                    coupled[b] = true;
194                }
195            }
196        }
197
198        matrix.close()?;
199        let tightened = tighten(members, &matrix, &start, &end)?;
200        let mut network = Self {
201            nodes,
202            distance: matrix.cells,
203            start,
204            end,
205            coupled,
206            mode: Mode::Closure,
207        };
208        network.choose_mode(members, budget);
209        Ok((tightened, network))
210    }
211
212    /// Picks the evaluation mode of the coupled members and drops members that the partial
213    /// mode evaluates separately.
214    fn choose_mode(&mut self, members: &[Member<'_>], budget: usize) {
215        let coupled = || (0..members.len()).filter(|&index| self.coupled[index]);
216        if coupled().all(|index| members[index].is_stepwise()) {
217            self.mode = Mode::Closure;
218            return;
219        }
220
221        let domains = coupled()
222            .flat_map(|index| [Some(self.start[index]), self.end[index]])
223            .flatten()
224            .map(|node| {
225                let (lo, hi) = self.domain(node);
226                usize::try_from(hi - lo + 1).unwrap_or(usize::MAX)
227            });
228        if nodes_for(domains) <= budget {
229            self.mode = Mode::Cut;
230            return;
231        }
232
233        self.mode = Mode::Partial;
234        for (flag, member) in self.coupled.iter_mut().zip(members) {
235            *flag &= member.is_stepwise();
236        }
237    }
238
239    /// The largest possible `time(y) - time(x)`.
240    fn distance(&self, x: usize, y: usize) -> Option<i128> {
241        self.distance[x * self.nodes + y]
242    }
243
244    /// The tightened domain `[lo, hi]` of `node`.
245    fn domain(&self, node: usize) -> (i128, i128) {
246        let hi = self.distance(0, node).unwrap_or(i128::MAX);
247        let lo = self.distance(node, 0).map_or(i128::MIN, |bound| -bound);
248        (lo, hi)
249    }
250
251    /// Whether member `index` is part of the coupled extreme.
252    pub(crate) fn is_coupled(&self, index: usize) -> bool {
253        self.coupled[index]
254    }
255
256    /// For the cut mode with rates or uncertain durations: the tick ranges, relative to which
257    /// every tick may be an evaluation tick, as `(lo, hi)` of every coupled time point's domain
258    /// plus each offset of the member's anchors. Empty in the other modes.
259    pub(crate) fn dense_ranges<'m>(
260        &'m self,
261        members: &'m [Member<'m>],
262    ) -> impl Iterator<Item = (i128, i128)> + 'm {
263        let active = self.mode == Mode::Cut;
264        (0..members.len())
265            .filter(move |&index| active && self.coupled[index] && !members[index].is_stepwise())
266            .flat_map(move |index| {
267                members[index].anchored().flat_map(move |impact| {
268                    impact.anchors().into_iter().map(move |anchor| {
269                        let (node, offset) = self.anchor_point(index, anchor);
270                        let (lo, hi) = self.domain(node);
271                        (lo + offset, hi + offset)
272                    })
273                })
274            })
275    }
276
277    /// The node and offset of `anchor` of member `index`.
278    fn anchor_point(&self, index: usize, anchor: Anchor) -> (usize, i128) {
279        match (anchor, self.end[index]) {
280            (Anchor::End(offset), Some(end)) => (end, i128::from(offset)),
281            // Fixed impacts only carry start anchors; an end anchor without an end node is
282            // measured from the start like them.
283            (Anchor::Start(offset) | Anchor::End(offset), _) => {
284                (self.start[index], i128::from(offset))
285            }
286        }
287    }
288
289    /// The extreme summed contribution of the coupled members at tick `t`.
290    ///
291    /// # Errors
292    ///
293    /// [`Error::Overflow`] if a sum exceeds `i128`; [`Error::OutOfMemory`] if the graph
294    /// cannot be allocated.
295    pub(crate) fn coupled_extreme(
296        &self,
297        members: &[Member<'_>],
298        t: Tick,
299        extreme: Extreme,
300    ) -> Result<i128, Error> {
301        match self.mode {
302            Mode::Cut => self.cut_extreme(members, t, extreme),
303            Mode::Closure | Mode::Partial => self.closure_extreme(members, t, extreme),
304        }
305    }
306
307    /// The coupled extreme by the discretised minimum cut over every coupled time point.
308    fn cut_extreme(
309        &self,
310        members: &[Member<'_>],
311        t: Tick,
312        extreme: Extreme,
313    ) -> Result<i128, Error> {
314        let sign: i128 = match extreme {
315            Extreme::Upper => 1,
316            Extreme::Lower => -1,
317        };
318        let mut nodes: Vec<usize> = Vec::new();
319        let mut variables: Vec<Variable> = Vec::new();
320        for index in (0..members.len()).filter(|&index| self.coupled[index]) {
321            for node in [Some(self.start[index]), self.end[index]]
322                .into_iter()
323                .flatten()
324            {
325                let (lo, hi) = self.domain(node);
326                let size = usize::try_from(hi - lo + 1).map_err(|_| Error::Overflow)?;
327                let mut values = Vec::new();
328                values
329                    .try_reserve_exact(size)
330                    .map_err(|_| Error::OutOfMemory)?;
331                values.resize(size, 0);
332                nodes.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
333                variables.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
334                nodes.push(node);
335                variables.push(Variable { lo, values });
336            }
337
338            for impact in members[index].anchored() {
339                self.add_terms(index, impact, i128::from(t), sign, &nodes, &mut variables)?;
340            }
341        }
342
343        max_separable(&variables, |p, q| self.distance(nodes[p], nodes[q])).map(|best| sign * best)
344    }
345
346    /// Adds the contribution of `impact` of member `index` at tick `t`, times `sign`, to the
347    /// values of the variables of its time points.
348    fn add_terms(
349        &self,
350        index: usize,
351        impact: Uncertain,
352        t: i128,
353        sign: i128,
354        nodes: &[usize],
355        variables: &mut [Variable],
356    ) -> Result<(), Error> {
357        // Every impact is separable: a step is an indicator of its tick, a claim the difference
358        // of two indicators, a rate the difference of two clamped ramps.
359        let mut add = |anchor: Anchor, term: &dyn Fn(i128) -> i128| -> Result<(), Error> {
360            let (node, offset) = self.anchor_point(index, anchor);
361            let position = nodes
362                .iter()
363                .position(|&other| other == node)
364                .ok_or(Error::Overflow)?;
365            let variable = &mut variables[position];
366            for (k, value) in variable.values.iter_mut().enumerate() {
367                let x = variable.lo + i128::try_from(k).map_err(|_| Error::Overflow)?;
368                *value = value
369                    .checked_add(sign * term(x + offset))
370                    .ok_or(Error::Overflow)?;
371            }
372
373            Ok(())
374        };
375        let reached = |tick: i128| i128::from(tick <= t);
376        let ramp = |tick: i128| (t - tick).max(0);
377        match impact {
378            Uncertain::Step { at, delta } => add(at, &|tick| i128::from(delta) * reached(tick)),
379            Uncertain::Claim { start, end, amount } => {
380                let amount = i128::from(amount);
381                add(start, &|tick| -amount * reached(tick))?;
382                add(end, &|tick| amount * reached(tick))
383            }
384            Uncertain::Rate {
385                start,
386                end,
387                per_tick,
388            } => {
389                let rate = i128::from(per_tick);
390                add(start, &|tick| rate * ramp(tick))?;
391                add(end, &|tick| -rate * ramp(tick))
392            }
393        }
394    }
395
396    /// The coupled extreme of the stepwise coupled members by maximum-weight closure.
397    fn closure_extreme(
398        &self,
399        members: &[Member<'_>],
400        t: Tick,
401        extreme: Extreme,
402    ) -> Result<i128, Error> {
403        let sign = match extreme {
404            Extreme::Upper => 1,
405            Extreme::Lower => -1,
406        };
407        let mut forced: i128 = 0;
408        let mut pending: Vec<Event> = Vec::new();
409        for (index, member) in members.iter().enumerate() {
410            if !self.coupled[index] {
411                continue;
412            }
413
414            let Shape::Fixed(impacts) = member.shape else {
415                continue;
416            };
417            let (lo, hi) = self.domain(self.start[index]);
418            for (offset, jump) in jumps(impacts) {
419                let (earliest, latest) = (lo + i128::from(offset), hi + i128::from(offset));
420                let t = i128::from(t);
421                if latest <= t {
422                    forced = forced.checked_add(jump).ok_or(Error::Overflow)?;
423                } else if earliest <= t {
424                    pending.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
425                    pending.push(Event {
426                        node: self.start[index],
427                        offset,
428                        weight: sign * jump,
429                    });
430                }
431            }
432        }
433
434        let weights: Vec<i128> = pending.iter().map(|event| event.weight).collect();
435        let best = max_weight_closure(&weights, |x, y| self.not_later(&pending[y], &pending[x]))?;
436        forced.checked_add(sign * best).ok_or(Error::Overflow)
437    }
438
439    /// Whether event `x` is never later than event `y` in any admitted schedule, so that
440    /// `y` at or before a tick forces `x` there too.
441    fn not_later(&self, x: &Event, y: &Event) -> bool {
442        // time(y) - time(x) = node(y) - node(x) + offset(y) - offset(x), and the smallest
443        // node(y) - node(x) is the negated largest node(x) - node(y).
444        self.distance(y.node, x.node)
445            .is_some_and(|largest| -largest + i128::from(y.offset) - i128::from(x.offset) >= 0)
446    }
447}
448
449/// The start node of each member, the end node of each contingent member, and the node count.
450fn number_nodes(members: &[Member<'_>]) -> (Vec<usize>, Vec<Option<usize>>, usize) {
451    let mut next = 1;
452    let mut start = Vec::with_capacity(members.len());
453    let mut end = Vec::with_capacity(members.len());
454    for member in members {
455        start.push(next);
456        next += 1;
457        if matches!(member.shape, Shape::Uncertain { .. }) {
458            end.push(Some(next));
459            next += 1;
460        } else {
461            end.push(None);
462        }
463    }
464
465    (start, end, next)
466}
467
468/// The tightened start windows and durations from a closed matrix.
469fn tighten(
470    members: &[Member<'_>],
471    matrix: &Matrix,
472    start: &[usize],
473    end: &[Option<usize>],
474) -> Result<Tightened, Error> {
475    let mut windows = Vec::new();
476    let mut durations = Vec::new();
477    windows
478        .try_reserve_exact(members.len())
479        .map_err(|_| Error::OutOfMemory)?;
480    durations
481        .try_reserve_exact(members.len())
482        .map_err(|_| Error::OutOfMemory)?;
483    for (index, member) in members.iter().enumerate() {
484        windows.push(matrix.window(start[index])?);
485        let duration = match end[index] {
486            Some(end) => {
487                let longest = matrix.get(start[index], end).ok_or(Error::Overflow)?;
488                let shortest = -matrix.get(end, start[index]).ok_or(Error::Overflow)?;
489                let longest = Tick::try_from(longest).map_err(|_| Error::Overflow)?;
490                let shortest = Tick::try_from(shortest).map_err(|_| Error::Overflow)?;
491                Window::new(shortest, longest)?
492            }
493            None => member.duration(),
494        };
495        durations.push(duration);
496    }
497
498    Ok(Tightened { windows, durations })
499}
500
501/// A pending impact tick of a coupled member.
502#[derive(Debug, Clone, Copy)]
503struct Event {
504    /// The start node of the member.
505    node: usize,
506    /// The tick relative to the member's start.
507    offset: Tick,
508    /// The level jump at the tick, negated for the lower extreme.
509    weight: i128,
510}
511
512/// The net level jumps of stepwise `impacts` per relative tick, sorted by tick, without zero
513/// jumps.
514fn jumps(impacts: &[crate::Impact]) -> Vec<(Tick, i128)> {
515    let mut jumps: Vec<(Tick, i128)> = impacts
516        .iter()
517        .flat_map(crate::Impact::changes)
518        .flatten()
519        .map(|(at, step, _)| (at, step))
520        .collect();
521    jumps.sort_unstable_by_key(|&(at, _)| at);
522    jumps.dedup_by(|later, earlier| {
523        let same = later.0 == earlier.0;
524        if same {
525            earlier.1 += later.1;
526        }
527
528        same
529    });
530    jumps.retain(|&(_, jump)| jump != 0);
531    jumps
532}
533
534/// The indices of the members with id `activity`.
535///
536/// # Errors
537///
538/// [`Error::UnknownActivity`] if there is none.
539fn indices_of<'m>(
540    members: &'m [Member<'_>],
541    activity: ActivityId,
542) -> Result<impl Iterator<Item = usize> + Clone + 'm, Error> {
543    if !members.iter().any(|member| member.activity == activity) {
544        return Err(Error::UnknownActivity { activity });
545    }
546
547    Ok(members
548        .iter()
549        .enumerate()
550        .filter(move |(_, member)| member.activity == activity)
551        .map(|(index, _)| index))
552}
553
554/// A dense distance matrix of a simple temporal network, node 0 being the origin.
555struct Matrix {
556    /// The number of nodes.
557    nodes: usize,
558    /// `cells[x * nodes + y]`: the largest allowed `time(y) - time(x)`, `None` if unbounded.
559    cells: Vec<Option<i128>>,
560}
561
562impl Matrix {
563    /// A matrix with zero diagonal and no other constraint.
564    fn new(nodes: usize) -> Result<Self, Error> {
565        let mut cells = Vec::new();
566        cells
567            .try_reserve_exact(nodes * nodes)
568            .map_err(|_| Error::OutOfMemory)?;
569        cells.resize(nodes * nodes, None);
570        for node in 0..nodes {
571            cells[node * nodes + node] = Some(0);
572        }
573
574        Ok(Self { nodes, cells })
575    }
576
577    /// The largest allowed `time(y) - time(x)`.
578    fn get(&self, x: usize, y: usize) -> Option<i128> {
579        self.cells[x * self.nodes + y]
580    }
581
582    /// Requires `time(y) - time(x) <= bound`.
583    fn tighten(&mut self, x: usize, y: usize, bound: i128) {
584        let cell = &mut self.cells[x * self.nodes + y];
585        *cell = Some(cell.map_or(bound, |current| current.min(bound)));
586    }
587
588    /// Floyd-Warshall: replaces every cell by the shortest path.
589    ///
590    /// # Errors
591    ///
592    /// [`Error::InconsistentPrecedences`] on a negative cycle.
593    fn close(&mut self) -> Result<(), Error> {
594        let n = self.nodes;
595        for k in 0..n {
596            for x in 0..n {
597                let Some(via) = self.get(x, k) else {
598                    continue;
599                };
600
601                for y in 0..n {
602                    if let Some(rest) = self.get(k, y) {
603                        self.tighten(x, y, via + rest);
604                    }
605                }
606            }
607        }
608
609        if (0..n).any(|node| self.get(node, node).is_some_and(|loop_| loop_ < 0)) {
610            return Err(Error::InconsistentPrecedences);
611        }
612
613        Ok(())
614    }
615
616    /// The tightened window of `node` relative to the origin.
617    fn window(&self, node: usize) -> Result<Window, Error> {
618        let latest = self.get(0, node).ok_or(Error::Overflow)?;
619        let earliest = -self.get(node, 0).ok_or(Error::Overflow)?;
620        let latest = Tick::try_from(latest).map_err(|_| Error::Overflow)?;
621        let earliest = Tick::try_from(earliest).map_err(|_| Error::Overflow)?;
622        Window::new(earliest, latest)
623    }
624}