Skip to main content

task_allocation/ccbba/
constraints.rs

1//! Coupled assignment constraints between tasks, grouped into activities.
2
3use alloc::vec;
4use alloc::vec::Vec;
5use core::fmt;
6
7use crate::assignment::Assignment;
8use crate::id::TaskId;
9
10/// Assignment constraints between tasks: which tasks need others, and which exclude each
11/// other.
12///
13/// Tasks are grouped into *activities*. Within an activity, a dependency matrix `D` says how
14/// each pair of tasks relates, as in Table I of Whitten, Choi, Johnson and How (2011). Entry
15/// `D[q][u]`, with `q` and `u` positions in the activity's task list, is:
16///
17/// - `1`: task `u` depends on task `q`; `u` may only be assigned if `q` is;
18/// - `0`: no constraint;
19/// - `-1`: `q` and `u` are mutually exclusive; at most one of them may be assigned.
20///
21/// Two tasks that depend on each other must be assigned together or not at all. The diagonal
22/// is zero. Tasks outside every activity are unconstrained. The paper's codes above one
23/// ("either of these tasks") are not supported.
24///
25/// # Examples
26///
27/// ```
28/// use task_allocation::TaskId;
29/// use task_allocation::ccbba::Constraints;
30///
31/// // A strike (task 0) needs a sensor (task 1), and the sensor is useless without it.
32/// // Task 2 excludes both.
33/// let mut constraints = Constraints::new(3);
34/// constraints
35///     .add_activity(
36///         &[TaskId(0), TaskId(1), TaskId(2)],
37///         &[&[0, 1, -1], &[1, 0, -1], &[-1, -1, 0]],
38///     )
39///     .unwrap();
40///
41/// assert_eq!(constraints.requirements(TaskId(0)).collect::<Vec<_>>(), [TaskId(1)]);
42/// assert!(constraints.excludes(TaskId(2), TaskId(0)));
43/// ```
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct Constraints {
46    /// For each task, its activity and its position in it; `None` for unconstrained tasks.
47    membership: Vec<Option<(usize, usize)>>,
48
49    /// The activities: their tasks, in matrix order, and their dependency matrices.
50    activities: Vec<Activity>,
51
52    /// For each task, the opening of its time window: the earliest it may start, in the
53    /// time unit of the agents' routes. Zero unless set.
54    openings: Vec<u64>,
55}
56
57/// A group of coupled tasks with its dependency matrix.
58#[derive(Clone, Debug, PartialEq, Eq)]
59struct Activity {
60    /// The tasks, in the order of the matrix's rows and columns.
61    tasks: Vec<TaskId>,
62
63    /// `dependency[q][u]`: how the tasks at positions `q` and `u` relate; see [`Constraints`].
64    dependency: Vec<Vec<i8>>,
65
66    /// `timing[q][u]`: the most task `q` may start after task `u` starts; `None` for no
67    /// limit. Finite only between dependent tasks.
68    timing: Vec<Vec<Option<i64>>>,
69}
70
71/// Why an activity was rejected.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73#[non_exhaustive]
74pub enum ConstraintError {
75    /// A task identifier is not below the task count.
76    UnknownTask(TaskId),
77
78    /// A task appears twice in one activity, or already belongs to another activity.
79    DuplicateTask(TaskId),
80
81    /// The matrix is not square with one row per task.
82    Shape,
83
84    /// A diagonal entry is not zero.
85    Diagonal,
86
87    /// An entry is not `-1`, `0` or `1`.
88    UnsupportedCode(i8),
89
90    /// The timing matrix is not square with one row per task.
91    TimingShape,
92
93    /// A diagonal entry of the timing matrix is not zero or unbounded.
94    TimingDiagonal,
95
96    /// The timing matrix limits two tasks that do not depend on each other in either
97    /// direction; the paper defines no windows or release rules for those.
98    TimingWithoutDependency,
99}
100
101impl fmt::Display for ConstraintError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::UnknownTask(task) => write!(f, "{task} is not part of the task set"),
105            Self::DuplicateTask(task) => write!(f, "{task} is already part of an activity"),
106            Self::Shape => f.write_str("the dependency matrix needs one row and column per task"),
107            Self::Diagonal => f.write_str("the dependency matrix needs a zero diagonal"),
108            Self::UnsupportedCode(code) => {
109                write!(f, "dependency code {code} is not supported; use -1, 0 or 1")
110            }
111            Self::TimingShape => f.write_str("the timing matrix needs one row and column per task"),
112            Self::TimingDiagonal => {
113                f.write_str("the timing matrix needs a zero or unbounded diagonal")
114            }
115            Self::TimingWithoutDependency => {
116                f.write_str("timing limits apply only between dependent tasks")
117            }
118        }
119    }
120}
121
122impl core::error::Error for ConstraintError {}
123
124impl Constraints {
125    /// No constraints between tasks `0..tasks`.
126    #[must_use]
127    pub fn new(tasks: usize) -> Self {
128        Self {
129            membership: vec![None; tasks],
130            activities: Vec::new(),
131            openings: vec![0; tasks],
132        }
133    }
134
135    /// Adds an activity: `tasks`, related by `dependency` as described on [`Constraints`],
136    /// without timing limits.
137    ///
138    /// # Errors
139    ///
140    /// Returns a [`ConstraintError`] when a task is unknown or already in an activity, when
141    /// the matrix is not square with one row per task, when its diagonal is not zero, or when
142    /// an entry is not `-1`, `0` or `1`. Nothing is added then.
143    pub fn add_activity(
144        &mut self,
145        tasks: &[TaskId],
146        dependency: &[&[i8]],
147    ) -> Result<(), ConstraintError> {
148        let unbounded = vec![None; tasks.len()];
149        let rows: Vec<&[Option<i64>]> = tasks.iter().map(|_| unbounded.as_slice()).collect();
150
151        self.add_timed_activity(tasks, dependency, &rows)
152    }
153
154    /// Adds an activity whose dependent tasks must also start within limits of each other.
155    ///
156    /// `timing[q][u]` is the most task `q` may start after task `u` starts, in the time unit
157    /// of the agents' routes; negative values make `q` start before `u`; `None` sets no
158    /// limit. Together, `u` imposes on `q` the window `start(u) - timing[u][q]` to
159    /// `start(u) + timing[q][u]`. This is the matrix `T` of Whitten, Choi, Johnson and How.
160    ///
161    /// # Errors
162    ///
163    /// As [`add_activity`](Constraints::add_activity), plus when the timing matrix is not
164    /// square with one row per task, has a diagonal other than zero or `None`, or limits two
165    /// tasks that do not depend on each other.
166    ///
167    /// # Examples
168    ///
169    /// The paper's strike activity: the strike (task 0) and the sensing (task 1) start within
170    /// 20 seconds of each other, and the damage assessment (task 2) starts at least 180
171    /// seconds after the strike and the sensing. Task 3, gathering intelligence instead,
172    /// excludes all three.
173    ///
174    /// ```
175    /// use task_allocation::TaskId;
176    /// use task_allocation::ccbba::Constraints;
177    ///
178    /// let mut constraints = Constraints::new(4);
179    /// constraints
180    ///     .add_timed_activity(
181    ///         &[TaskId(0), TaskId(1), TaskId(2), TaskId(3)],
182    ///         &[&[0, 1, 1, -1], &[1, 0, 1, -1], &[0, 0, 0, -1], &[-1, -1, -1, 0]],
183    ///         &[
184    ///             &[Some(0), Some(20), Some(-180), None],
185    ///             &[Some(20), Some(0), Some(-180), None],
186    ///             &[None, None, Some(0), None],
187    ///             &[None, None, None, Some(0)],
188    ///         ],
189    ///     )
190    ///     .unwrap();
191    ///
192    /// // A strike starting at 100 lets the sensing start from 80 to 120, and the damage
193    /// // assessment from 280 on.
194    /// assert_eq!(constraints.window(TaskId(1), TaskId(0), 100), (Some(80), Some(120)));
195    /// assert_eq!(constraints.window(TaskId(2), TaskId(0), 100), (Some(280), None));
196    /// ```
197    pub fn add_timed_activity(
198        &mut self,
199        tasks: &[TaskId],
200        dependency: &[&[i8]],
201        timing: &[&[Option<i64>]],
202    ) -> Result<(), ConstraintError> {
203        self.check_tasks(tasks)?;
204        check_matrix(tasks.len(), dependency)?;
205        check_timing(dependency, timing)?;
206
207        let activity = self.activities.len();
208        for (position, task) in tasks.iter().enumerate() {
209            self.membership[task.index()] = Some((activity, position));
210        }
211
212        self.activities.push(Activity {
213            tasks: tasks.to_vec(),
214            dependency: dependency.iter().map(|row| row.to_vec()).collect(),
215            timing: timing.iter().map(|row| row.to_vec()).collect(),
216        });
217
218        Ok(())
219    }
220
221    /// Sets the opening of `task`'s time window, the earliest it may start. A
222    /// [`TimedAgent`](super::TimedAgent) never starts the task earlier. Agents that conflict
223    /// over two mutually dependent tasks compare how far into their windows they start, and
224    /// the earlier one gives way.
225    ///
226    /// # Panics
227    ///
228    /// Panics when `task` is not part of the task set.
229    pub fn set_opening(&mut self, task: TaskId, opening: u64) {
230        self.openings[task.index()] = opening;
231    }
232
233    /// The opening of `task`'s time window; zero unless set.
234    ///
235    /// # Panics
236    ///
237    /// Panics when `task` is not part of the task set.
238    #[must_use]
239    pub fn opening(&self, task: TaskId) -> u64 {
240        self.openings[task.index()]
241    }
242
243    /// The window `other`, starting at `start`, imposes on `task`: the earliest and the
244    /// latest start, each `None` when unbounded. Only a task that depends on `other` gets a
245    /// window; otherwise both are `None`. Bounds are not clamped at zero.
246    #[must_use]
247    pub fn window(&self, task: TaskId, other: TaskId, start: u64) -> (Option<i128>, Option<i128>) {
248        let Some((after, before, depends)) = self.timing_between(task, other) else {
249            return (None, None);
250        };
251
252        if !depends {
253            return (None, None);
254        }
255
256        let start = i128::from(start);
257
258        (
259            before.map(|lead| start - i128::from(lead)),
260            after.map(|lag| start + i128::from(lag)),
261        )
262    }
263
264    /// Whether starts at `start` for `task` and `other_start` for `other` respect the
265    /// timing limits between them, in both directions.
266    #[must_use]
267    pub fn starts_agree(&self, task: TaskId, start: u64, other: TaskId, other_start: u64) -> bool {
268        let Some((after, before, _)) = self.timing_between(task, other) else {
269            return true;
270        };
271
272        let (start, other_start) = (i128::from(start), i128::from(other_start));
273        let late_enough = after.is_none_or(|lag| start <= other_start + i128::from(lag));
274        let early_enough = before.is_none_or(|lead| other_start <= start + i128::from(lead));
275
276        late_enough && early_enough
277    }
278
279    /// The other tasks in `task`'s activity; none for an unconstrained task.
280    pub(crate) fn activity_tasks(&self, task: TaskId) -> impl Iterator<Item = TaskId> + '_ {
281        self.related(task).map(|(other, _, _)| other)
282    }
283
284    /// Whether `task` depends on `other`.
285    #[must_use]
286    pub fn depends_on(&self, task: TaskId, other: TaskId) -> bool {
287        self.requirements(task).any(|required| required == other)
288    }
289
290    /// `timing[task][other]`, `timing[other][task]`, and whether `task` depends on `other`;
291    /// `None` when the two are not in the same activity.
292    fn timing_between(
293        &self,
294        task: TaskId,
295        other: TaskId,
296    ) -> Option<(Option<i64>, Option<i64>, bool)> {
297        let (activity, q) = self.membership.get(task.index()).copied().flatten()?;
298        let (other_activity, u) = self.membership.get(other.index()).copied().flatten()?;
299        if activity != other_activity || q == u {
300            return None;
301        }
302
303        let activity = &self.activities[activity];
304
305        Some((
306            activity.timing[q][u],
307            activity.timing[u][q],
308            activity.dependency[u][q] == 1,
309        ))
310    }
311
312    /// Checks that every task is known, and in no activity yet, nor twice in `tasks`.
313    fn check_tasks(&self, tasks: &[TaskId]) -> Result<(), ConstraintError> {
314        for (index, &task) in tasks.iter().enumerate() {
315            let Some(membership) = self.membership.get(task.index()) else {
316                return Err(ConstraintError::UnknownTask(task));
317            };
318
319            if membership.is_some() || tasks[..index].contains(&task) {
320                return Err(ConstraintError::DuplicateTask(task));
321            }
322        }
323
324        Ok(())
325    }
326
327    /// The number of tasks the constraints cover.
328    #[must_use]
329    pub fn tasks(&self) -> usize {
330        self.membership.len()
331    }
332
333    /// The tasks `task` depends on: it may only be assigned if all of them are.
334    pub fn requirements(&self, task: TaskId) -> impl Iterator<Item = TaskId> + '_ {
335        self.related(task)
336            .filter(|&(_, toward, _)| toward == 1)
337            .map(|(other, _, _)| other)
338    }
339
340    /// Whether `a` and `b` are mutually exclusive.
341    #[must_use]
342    pub fn excludes(&self, a: TaskId, b: TaskId) -> bool {
343        self.related(a)
344            .any(|(other, toward, away)| other == b && (toward == -1 || away == -1))
345    }
346
347    /// The tasks mutually exclusive with `task`.
348    pub fn exclusions(&self, task: TaskId) -> impl Iterator<Item = TaskId> + '_ {
349        self.related(task)
350            .filter(|&(_, toward, away)| toward == -1 || away == -1)
351            .map(|(other, _, _)| other)
352    }
353
354    /// Whether `task` depends on a task that also depends on it. Agents may bid on such a task
355    /// optimistically, before its partners have winners.
356    #[must_use]
357    pub fn is_mutual(&self, task: TaskId) -> bool {
358        self.related(task)
359            .any(|(_, toward, away)| toward == 1 && away == 1)
360    }
361
362    /// Every other task in `task`'s activity, with the matrix entries `D[other][task]` and
363    /// `D[task][other]`.
364    fn related(&self, task: TaskId) -> impl Iterator<Item = (TaskId, i8, i8)> + '_ {
365        let membership = self.membership.get(task.index()).copied().flatten();
366
367        membership
368            .into_iter()
369            .flat_map(move |(activity, position)| {
370                let activity = &self.activities[activity];
371                activity
372                    .tasks
373                    .iter()
374                    .enumerate()
375                    .filter(move |&(other, _)| other != position)
376                    .map(move |(other, &other_task)| {
377                        (
378                            other_task,
379                            activity.dependency[other][position],
380                            activity.dependency[position][other],
381                        )
382                    })
383            })
384    }
385
386    /// Whether `assignment` meets every constraint: each assigned task's requirements are
387    /// assigned too, and no two mutually exclusive tasks are both assigned.
388    #[must_use]
389    pub fn is_satisfied_by(&self, assignment: &Assignment) -> bool {
390        let assigned = |task: TaskId| assignment.holder(task).is_some();
391
392        (0..self.tasks())
393            .map(TaskId)
394            .filter(|&task| assigned(task))
395            .all(|task| {
396                self.requirements(task).all(assigned) && !self.exclusions(task).any(assigned)
397            })
398    }
399}
400
401/// Checks that `timing` is a square matrix of the same side as `dependency`, with a zero or
402/// unbounded diagonal, and finite only between tasks that depend on each other in some
403/// direction.
404fn check_timing(dependency: &[&[i8]], timing: &[&[Option<i64>]]) -> Result<(), ConstraintError> {
405    let size = dependency.len();
406    if timing.len() != size || timing.iter().any(|row| row.len() != size) {
407        return Err(ConstraintError::TimingShape);
408    }
409
410    for (q, row) in timing.iter().enumerate() {
411        for (u, &limit) in row.iter().enumerate() {
412            if q == u {
413                if limit.is_some_and(|limit| limit != 0) {
414                    return Err(ConstraintError::TimingDiagonal);
415                }
416
417                continue;
418            }
419
420            let dependent = dependency[q][u] == 1 || dependency[u][q] == 1;
421            if limit.is_some() && !dependent {
422                return Err(ConstraintError::TimingWithoutDependency);
423            }
424        }
425    }
426
427    Ok(())
428}
429
430/// Checks that `dependency` is a square matrix of side `size` with a zero diagonal and
431/// entries `-1`, `0` or `1`.
432fn check_matrix(size: usize, dependency: &[&[i8]]) -> Result<(), ConstraintError> {
433    if dependency.len() != size || dependency.iter().any(|row| row.len() != size) {
434        return Err(ConstraintError::Shape);
435    }
436
437    for (q, row) in dependency.iter().enumerate() {
438        for (u, &code) in row.iter().enumerate() {
439            if !(-1..=1).contains(&code) {
440                return Err(ConstraintError::UnsupportedCode(code));
441            }
442
443            if q == u && code != 0 {
444                return Err(ConstraintError::Diagonal);
445            }
446        }
447    }
448
449    Ok(())
450}