Skip to main content

resource_timeline/
lib.rs

1//! # Resource timeline
2//!
3//! Resource timelines for onboard scheduling: energy, memory, thermal and communication budgets.
4//!
5//! A [`Timeline`] tracks the level of one numeric resource over integer time ticks. Activities
6//! add [`Impact`]s to it:
7//!
8//! - a consumable resource (battery energy, data volume) changes by permanent
9//!   [`Impact::Step`]s and by linear [`Impact::Rate`]s (charging, discharging, thermal drift);
10//! - a reusable resource (an instrument, a transmitter, a power channel) is borrowed by an
11//!   [`Impact::Claim`] for a half-open interval and returned afterwards.
12//!
13//! [`Timeline::first_violation`] reports the first tick at which the level leaves its
14//! `[min, max]` [`Bounds`] or misses an end-state [`Target`], with the activities responsible.
15//! A [`StateTimeline`] does the same for discrete states such as instrument modes and comm
16//! visibility windows. [`Timeline::breakpoints`], [`Timeline::samples`] and
17//! [`Timeline::export`] extract the level line for display and telemetry.
18//!
19//! On top of single timelines:
20//!
21//! - a [`Plan`] holds one timeline per resource, places activities given as [`Demand`]s
22//!   atomically and finds the [earliest start](Plan::earliest_start) at which an activity fits,
23//!   in closed form per linear piece when rates are involved;
24//! - [`greedy::schedule`] places activities in priority order at their earliest feasible start;
25//! - [`envelope::Envelope`] bounds the level over every schedule that start [`Window`]s admit,
26//!   including uncertain durations and precedences, so a flexible schedule can be checked once
27//!   instead of per dispatch decision; [`envelope::StateEnvelope`] does the same for states.
28//!
29//! Every timeline and plan is generic over its [`storage`]: heap-allocated by default, or
30//! fixed-capacity and allocation-free ([`FixedTimeline`], [`storage::FixedPlan`]) for onboard
31//! use, with the same algorithms and typed [`Error::CapacityExceeded`] errors.
32//!
33//! This crate is the companion of `temporal-control` but does not depend on it: temporal
34//! controllability does not imply resource safety, so both checks must run independently. Both
35//! crates share the time representation only by convention: a [`Tick`] is a plain `i64`, and
36//! start windows come from the STN (see [`envelope`] for the bridge).
37//!
38//! ```mermaid
39//! graph LR
40//!     demands["Demands of an activity"] --> plan["Plan: numeric and state timelines"]
41//!     plan --> search["earliest_start, greedy::schedule"]
42//!     plan --> check["first_violation with contributors"]
43//!     windows["Start windows from an STN"] --> envelope["Envelope: Safe, Possible, Certain"]
44//!     plan --> envelope
45//! ```
46//!
47//! ## Example
48//!
49//! ```
50//! use resource_timeline::{ActivityId, Bound, Bounds, Impact, Timeline};
51//!
52//! // Battery with 100 units, a reserve of 20 and a capacity of 120.
53//! let mut battery = Timeline::depletable(0, 100, Bounds::new(20, 120)?, 16)?;
54//! let warm_up = ActivityId(1);
55//! let analyze = ActivityId(2);
56//! battery.add(warm_up, Impact::Step { at: 5, delta: -40 })?;
57//! battery.add(analyze, Impact::Step { at: 20, delta: -50 })?;
58//!
59//! let violation = battery.first_violation()?.expect("the reserve is broken");
60//! assert_eq!(violation.at, 20);
61//! assert_eq!(violation.level, 10);
62//! assert_eq!(violation.bound, Bound::BelowMin(20));
63//! assert_eq!(violation.contributors, [warm_up, analyze]);
64//! # Ok::<(), resource_timeline::Error>(())
65//! ```
66//!
67//! ## Features
68//!
69//! - `alloc` (default): heap storage ([`storage::Heap`], the default storage of every type),
70//!   [`envelope`] and [`greedy`]. Without it the crate needs no allocator: timelines, state
71//!   timelines and plans use [`storage::Fixed`] and [`storage::FixedPlan`].
72//!
73//! Repository: <https://github.com/sunsided/resource-timeline>
74//!
75#![cfg_attr(
76    feature = "alloc",
77    doc = "[`greedy::schedule`]: crate::greedy::schedule"
78)]
79#![cfg_attr(not(feature = "alloc"), doc = "[`greedy::schedule`]: crate#features")]
80#![cfg_attr(
81    feature = "alloc",
82    doc = "[`envelope::Envelope`]: crate::envelope::Envelope"
83)]
84#![cfg_attr(not(feature = "alloc"), doc = "[`envelope::Envelope`]: crate#features")]
85#![cfg_attr(
86    feature = "alloc",
87    doc = "[`envelope::StateEnvelope`]: crate::envelope::StateEnvelope"
88)]
89#![cfg_attr(
90    not(feature = "alloc"),
91    doc = "[`envelope::StateEnvelope`]: crate#features"
92)]
93#![cfg_attr(feature = "alloc", doc = "[`envelope`]: crate::envelope")]
94#![cfg_attr(not(feature = "alloc"), doc = "[`envelope`]: crate#features")]
95#![cfg_attr(feature = "alloc", doc = "[`greedy`]: crate::greedy")]
96#![cfg_attr(not(feature = "alloc"), doc = "[`greedy`]: crate#features")]
97#![no_std]
98#![forbid(unsafe_code)]
99
100#[cfg(feature = "alloc")]
101extern crate alloc;
102
103mod activity;
104pub mod codec;
105#[cfg(feature = "alloc")]
106pub mod envelope;
107mod error;
108#[cfg(feature = "alloc")]
109pub mod greedy;
110mod impact;
111mod plan;
112#[cfg(feature = "serde")]
113mod serde_impls;
114mod state;
115pub mod storage;
116mod target;
117mod timeline;
118mod violation;
119mod window;
120
121pub use activity::ActivityId;
122pub use error::{Container, Error};
123pub use impact::Impact;
124pub use plan::{Demand, Plan, PlanViolation, SearchScratch, StateId, TimelineId};
125pub use state::{StateImpact, StateTimeline, StateValue, StateViolation};
126pub use target::Target;
127pub use timeline::extract::{Breakpoint, Breakpoints, LevelProfile, Samples};
128pub use timeline::{Bounds, Kind, Timeline};
129pub use violation::{Bound, Violation};
130pub use window::Window;
131
132/// Doctests for the code examples in README.md (not part of the API).
133#[cfg(doctest)]
134#[doc = include_str!("../README.md")]
135mod readme_doctests {}
136
137/// A point in time, as a count of integer ticks.
138///
139/// The unit (seconds, milliseconds, spacecraft clock subticks) and the epoch are chosen by the
140/// mission; the crate never converts. `temporal-control` uses the same convention in its
141/// `Ticks(pub i64)` newtype, so integration code converts by wrapping or unwrapping `.0`.
142pub type Tick = i64;
143
144/// A resource level in a mission-chosen integer unit, for example mWh, KiB or instrument units.
145pub type Level = i64;
146
147/// A numeric timeline with room for `N` impacts that never allocates.
148pub type FixedTimeline<const N: usize> = Timeline<storage::Fixed<N>>;
149
150/// A state timeline with room for `N` impacts that never allocates.
151pub type FixedStateTimeline<const N: usize> = StateTimeline<storage::Fixed<N>>;