resource_timeline/greedy.rs
1//! A greedy scheduler: place activities by priority at their earliest feasible start.
2//!
3//! This is deliberately simple. It never moves an activity once placed and never backtracks,
4//! so it can fail to place an activity that a smarter order would fit. It serves as an example
5//! of the [`Plan`] API and as a test vehicle; an onboard scheduler would typically run it to
6//! repair a plan after a change, with a ground-planned order as the priorities.
7
8use alloc::vec::Vec;
9
10use crate::storage::PlanStorage;
11use crate::{ActivityId, Demand, Error, Plan, Tick, Window};
12
13/// An activity the greedy scheduler should place.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub struct Request<'a> {
16 /// The id the placed impacts are tagged with.
17 pub activity: ActivityId,
18 /// Higher values are placed first. Ties go to the smaller activity id, then to the
19 /// earlier request.
20 pub priority: u32,
21 /// The allowed starts.
22 pub window: Window,
23 /// The effects of the activity, relative to its start.
24 pub demands: &'a [Demand],
25}
26
27/// Places every request at the earliest start in its window at which it fits, in priority
28/// order, and returns the chosen start per request (in the order of `requests`), or `None` for
29/// requests that did not fit anywhere.
30///
31/// Each request's search may check at most `max_checks` candidate starts, see
32/// [`Plan::earliest_start`]. Requests already placed stay in `plan`; a request that does not
33/// fit leaves it unchanged.
34///
35/// # Errors
36///
37/// The errors of [`Plan::earliest_start`] and [`Plan::place`], and [`Error::OutOfMemory`] if
38/// the order or the result cannot be allocated. On error, requests placed before the failing
39/// one remain in `plan`.
40///
41/// # Examples
42///
43/// ```
44/// use resource_timeline::greedy::{Request, schedule};
45/// use resource_timeline::{ActivityId, Demand, Impact, Plan, Timeline, Window};
46///
47/// let mut plan = Plan::new();
48/// let antenna = plan.add_timeline(Timeline::claimable(0, 1, 16)?)?;
49/// let downlink = [Demand::Level {
50/// timeline: antenna,
51/// impact: Impact::Claim { start: 0, end: 10, amount: 1 },
52/// }];
53/// let window = Window::new(0, 15)?;
54/// let requests = [
55/// Request { activity: ActivityId(1), priority: 1, window, demands: &downlink },
56/// Request { activity: ActivityId(2), priority: 5, window, demands: &downlink },
57/// Request { activity: ActivityId(3), priority: 3, window, demands: &downlink },
58/// ];
59///
60/// // Priority 5 goes first, priority 3 next; priority 1 no longer fits by tick 15.
61/// assert_eq!(schedule(&mut plan, &requests, 1_000)?, [None, Some(0), Some(10)]);
62/// # Ok::<(), resource_timeline::Error>(())
63/// ```
64pub fn schedule<P: PlanStorage>(
65 plan: &mut Plan<P>,
66 requests: &[Request<'_>],
67 max_checks: usize,
68) -> Result<Vec<Option<Tick>>, Error> {
69 let order = priority_order(requests)?;
70 let mut starts = Vec::new();
71 starts
72 .try_reserve_exact(requests.len())
73 .map_err(|_| Error::OutOfMemory)?;
74 starts.resize(requests.len(), None);
75
76 for index in order {
77 let request = &requests[index];
78 starts[index] = place_earliest(plan, request, max_checks)?;
79 }
80
81 Ok(starts)
82}
83
84/// The indices of `requests`, highest priority first, ties by activity id and then by index.
85fn priority_order(requests: &[Request<'_>]) -> Result<Vec<usize>, Error> {
86 let mut order = Vec::new();
87 order
88 .try_reserve_exact(requests.len())
89 .map_err(|_| Error::OutOfMemory)?;
90 order.extend(0..requests.len());
91 order.sort_by_key(|&index| {
92 let request = &requests[index];
93 (core::cmp::Reverse(request.priority), request.activity)
94 });
95 Ok(order)
96}
97
98/// Places `request` at its earliest feasible start and returns that start, if any.
99fn place_earliest<P: PlanStorage>(
100 plan: &mut Plan<P>,
101 request: &Request<'_>,
102 max_checks: usize,
103) -> Result<Option<Tick>, Error> {
104 let start = plan.earliest_start(request.demands, request.window, max_checks)?;
105 if let Some(start) = start {
106 plan.place(request.activity, start, request.demands)?;
107 }
108
109 Ok(start)
110}