hydr_structures/structures/control/
batch.rs1use super::{
4 ControlCommandOutput, ControlDecisionSchedule, ControlEvent, ControlInitialState,
5 ControlSample, ControlState, ControlStepDiagnostics, OperatingControlDefinition,
6 OperatingControlTrial, SampledControlTiming,
7};
8use crate::structures::tensor::control::{
9 TensorControlContext, TensorControlState, TensorControlStep, TensorControlTimer,
10};
11use crate::structures::{
12 StructureBatch, StructureElement, StructureError, StructureInputErrorKind,
13};
14use numr::dtype::DType;
15use numr::runtime::Runtime;
16use std::sync::Arc;
17
18#[derive(Clone, Debug)]
20pub struct OperatingControlBatch<R: Runtime<DType = DType>> {
21 pub(crate) context: Arc<TensorControlContext<R>>,
22 pub(crate) state: TensorControlState<R>,
23 pub(crate) time: f64,
24 pub(crate) next_decision: usize,
25 pub(crate) steps: usize,
26 pub(crate) last: Option<Arc<TensorControlStep<R>>>,
27}
28impl<R: Runtime<DType = DType>> StructureBatch<R> {
29 pub fn with_operating_controls(
31 &self,
32 definitions: Vec<OperatingControlDefinition>,
33 initial_states: Vec<ControlInitialState>,
34 schedule: ControlDecisionSchedule,
35 timing: SampledControlTiming,
36 ) -> Result<OperatingControlBatch<R>, StructureError>
37 where
38 R::Client: numr::ops::BinaryOps<R>
39 + numr::ops::CompareOps<R>
40 + numr::ops::ConditionalOps<R>
41 + numr::ops::ReduceOps<R>
42 + numr::ops::ScalarOps<R>
43 + numr::ops::TwoSumOps<R>
44 + numr::ops::TypeConversionOps<R>
45 + numr::ops::UnaryOps<R>,
46 {
47 let context = Arc::new(TensorControlContext::new(
48 Arc::clone(&self.context),
49 definitions,
50 initial_states,
51 schedule,
52 timing,
53 )?);
54 let state = TensorControlState::initial(&context)?;
55 Ok(OperatingControlBatch {
56 time: context.schedule.initial_time_s,
57 context,
58 state,
59 next_decision: 0,
60 steps: 0,
61 last: None,
62 })
63 }
64}
65impl<R: Runtime<DType = DType>> OperatingControlBatch<R> {
66 pub fn elements(&self) -> &[StructureElement] {
68 &self.context.structures.elements
69 }
70 pub fn definitions(&self) -> &[OperatingControlDefinition] {
72 &self.context.definitions
73 }
74 pub fn initial_states(&self) -> &[ControlInitialState] {
76 &self.context.initial_states
77 }
78 pub fn schedule(&self) -> &ControlDecisionSchedule {
80 &self.context.schedule
81 }
82 pub fn timing(&self) -> &SampledControlTiming {
84 &self.context.timing
85 }
86 pub fn time(&self) -> f64 {
88 self.time
89 }
90 pub fn accepted_steps(&self) -> usize {
92 self.steps
93 }
94 pub fn next_event(&self) -> Option<ControlEvent> {
96 if self.time == self.schedule().end_s {
97 return None;
98 }
99 match self.schedule().decision_times_s.get(self.next_decision) {
100 Some(&time_s) => Some(ControlEvent {
101 time_s,
102 decision_index: Some(self.next_decision),
103 terminal: time_s == self.schedule().end_s,
104 }),
105 None => Some(ControlEvent {
106 time_s: self.schedule().end_s,
107 decision_index: None,
108 terminal: true,
109 }),
110 }
111 }
112 pub fn commands(&self) -> Result<Vec<ControlCommandOutput>, StructureError> {
114 super::projection::commands(&self.context, &self.state, self.time)
115 }
116 pub fn states(&self) -> Result<Vec<ControlState>, StructureError> {
118 super::projection::states(&self.context, &self.state)
119 }
120 pub fn last_step(&self) -> Result<Option<ControlStepDiagnostics>, StructureError> {
122 self.last
123 .as_ref()
124 .map(|step| super::projection::step(&self.context, step))
125 .transpose()
126 }
127 pub fn trial_to(
129 &self,
130 end_s: f64,
131 decision_samples: &[ControlSample],
132 ) -> Result<OperatingControlTrial<R>, StructureError>
133 where
134 R::Client: numr::ops::BinaryOps<R>
135 + numr::ops::CompareOps<R>
136 + numr::ops::ConditionalOps<R>
137 + numr::ops::ReduceOps<R>
138 + numr::ops::ScalarOps<R>
139 + numr::ops::TwoSumOps<R>
140 + numr::ops::TypeConversionOps<R>
141 + numr::ops::UnaryOps<R>,
142 {
143 self.complete(self.prepare_to(end_s)?, decision_samples)
144 }
145 pub(crate) fn prepare_to(
147 &self,
148 end_s: f64,
149 ) -> Result<OperatingControlPreparedInterval<R>, StructureError> {
150 let duration = end_s - self.time;
151 if !end_s.is_finite() || !duration.is_finite() || duration <= 0.0 {
152 return Err(StructureError::input(
153 StructureInputErrorKind::Definition,
154 format!(
155 "control interval=[{},{}],duration={duration}: supply a finite positive original duration",
156 self.time, end_s
157 ),
158 ));
159 }
160 let event = self.next_event().ok_or_else(|| {
161 StructureError::input(
162 StructureInputErrorKind::UnsupportedRegime,
163 "control trial exceeds terminal support",
164 )
165 })?;
166 if end_s > event.time_s {
167 return Err(StructureError::input(
168 StructureInputErrorKind::UnsupportedRegime,
169 "control interval crosses the next original event: split at the event",
170 ));
171 }
172 Ok(OperatingControlPreparedInterval {
173 base: self.clone(),
174 end_s,
175 event: (end_s == event.time_s).then_some(event),
176 })
177 }
178 pub(crate) fn complete(
180 &self,
181 prepared: OperatingControlPreparedInterval<R>,
182 decision_samples: &[ControlSample],
183 ) -> Result<OperatingControlTrial<R>, StructureError>
184 where
185 R::Client: numr::ops::BinaryOps<R>
186 + numr::ops::CompareOps<R>
187 + numr::ops::ConditionalOps<R>
188 + numr::ops::ReduceOps<R>
189 + numr::ops::ScalarOps<R>
190 + numr::ops::TwoSumOps<R>
191 + numr::ops::TypeConversionOps<R>
192 + numr::ops::UnaryOps<R>,
193 {
194 if !self.same_accepted(&prepared.base) {
195 return Err(StructureError::input(
196 StructureInputErrorKind::Identity,
197 "prepared control interval belongs to another accepted state: prepare it from this batch",
198 ));
199 }
200 let end_s = prepared.end_s;
201 let decision = prepared.decision_index();
202 let step = match decision {
203 Some(index) => {
204 let input = crate::structures::tensor::control::input::decision_samples(
205 &self.context,
206 decision_samples,
207 end_s,
208 )?;
209 crate::structures::numerics::control::decide(
210 &self.context,
211 &self.state,
212 self.time,
213 end_s,
214 index,
215 decision_samples,
216 input,
217 )?
218 }
219 None => {
220 if !decision_samples.is_empty() {
221 return Err(StructureError::input(
222 StructureInputErrorKind::OperatingPoint,
223 "non-decision control interval requires an empty sample slice",
224 ));
225 }
226 TensorControlStep {
227 start: self.time,
228 end: end_s,
229 decision_index: None,
230 before: self.state.clone(),
231 after: self.state.clone(),
232 samples: Vec::new(),
233 qualifies: self.context.zero.clone(),
234 timer: TensorControlTimer::zero(&self.context),
235 transitioned: self.context.zero.clone(),
236 }
237 }
238 };
239 let steps = self.steps.checked_add(1).ok_or_else(|| {
240 StructureError::numerical("control accepted interval counter overflows")
241 })?;
242 let next_decision = if decision.is_some() {
243 self.next_decision
244 .checked_add(1)
245 .ok_or_else(|| StructureError::numerical("control decision counter overflows"))?
246 } else {
247 self.next_decision
248 };
249 let next = Self {
250 context: Arc::clone(&self.context),
251 state: step.after.clone(),
252 time: end_s,
253 next_decision,
254 steps,
255 last: Some(Arc::new(step)),
256 };
257 Ok(OperatingControlTrial { next })
258 }
259 pub(crate) fn same_accepted(&self, other: &Self) -> bool {
261 Arc::ptr_eq(&self.context, &other.context)
262 && self.time.to_bits() == other.time.to_bits()
263 && self.steps == other.steps
264 && self.next_decision == other.next_decision
265 && self.state.high.shares_storage_with(&other.state.high)
266 && self.state.pending.shares_storage_with(&other.state.pending)
267 && self.state.since.shares_storage_with(&other.state.since)
268 && self.state.count.shares_storage_with(&other.state.count)
269 }
270}
271
272#[derive(Clone, Debug)]
274pub(crate) struct OperatingControlPreparedInterval<R: Runtime<DType = DType>> {
275 pub base: OperatingControlBatch<R>,
276 pub end_s: f64,
277 pub event: Option<ControlEvent>,
278}
279impl<R: Runtime<DType = DType>> OperatingControlPreparedInterval<R> {
280 pub fn decision_index(&self) -> Option<usize> {
282 self.event.and_then(|event| event.decision_index)
283 }
284 pub fn left(&self) -> OperatingControlBatch<R> {
286 OperatingControlBatch {
287 time: self.end_s,
288 ..self.base.clone()
289 }
290 }
291}