Skip to main content

hydr_structures/structures/gate/trajectory/
binding.rs

1//! Original gate-subsequence assignments and immutable context ownership.
2use numr::{dtype::DType, runtime::Runtime};
3
4use super::{GateOpeningTrajectory, GateTrajectoryEvent, GateTrajectorySupport};
5use crate::structures::blockage::effective::gate_opening_limit;
6use crate::structures::tensor::{
7    TensorStructureContext, gate::trajectory::TensorTrajectoryContext,
8};
9use crate::structures::{StructureError, StructureInputErrorKind, StructureLaw};
10use std::collections::BTreeMap;
11use std::sync::Arc;
12
13/// One exact original gate identity and its complete prescribed definition.
14#[derive(Clone, Debug, PartialEq)]
15pub struct GateTrajectoryAssignment {
16    /// Identity in the original gate subsequence.
17    pub structure_id: String,
18    /// Complete immutable operating trajectory.
19    pub trajectory: GateOpeningTrajectory,
20}
21#[derive(Debug)]
22pub(crate) struct GateTrajectoryData<R: Runtime<DType = DType>> {
23    pub context: Arc<TensorStructureContext<R>>,
24    pub assignments: Vec<GateTrajectoryAssignment>,
25    pub slots: Vec<usize>,
26    pub support: GateTrajectorySupport,
27    pub events: Vec<GateTrajectoryEvent>,
28    pub tensors: TensorTrajectoryContext<R>,
29}
30impl<R: Runtime<DType = DType>> GateTrajectoryData<R> {
31    pub(super) fn new(
32        context: Arc<TensorStructureContext<R>>,
33        assignments: Vec<GateTrajectoryAssignment>,
34    ) -> Result<Self, StructureError>
35    where
36        R::Client: numr::ops::BinaryOps<R>
37            + numr::ops::CompareOps<R>
38            + numr::ops::ConditionalOps<R>
39            + numr::ops::ReduceOps<R>
40            + numr::ops::ScalarOps<R>
41            + numr::ops::TwoSumOps<R>
42            + numr::ops::TypeConversionOps<R>
43            + numr::ops::UnaryOps<R>,
44    {
45        let slots: Vec<_> = context
46            .elements
47            .iter()
48            .enumerate()
49            .filter_map(|(i, e)| {
50                matches!(e.law, StructureLaw::HydrostaticRectangularGate(_)).then_some(i)
51            })
52            .collect();
53        if slots.is_empty() {
54            return Err(StructureError::input(
55                StructureInputErrorKind::Definition,
56                "gate trajectory batch has no gates: supply an actual gate law",
57            ));
58        }
59        if assignments.len() != slots.len() {
60            return Err(StructureError::input(
61                StructureInputErrorKind::Identity,
62                format!(
63                    "gate assignments={},expected={}: supply every gate in original subsequence order",
64                    assignments.len(),
65                    slots.len()
66                ),
67            ));
68        }
69        for (assignment, &slot) in assignments.iter().zip(&slots) {
70            let element = &context.elements[slot];
71            if assignment.structure_id != element.id {
72                return Err(StructureError::input(
73                    StructureInputErrorKind::Identity,
74                    format!(
75                        "gate assignment={:?},expected={:?}: match original gate subsequence",
76                        assignment.structure_id, element.id
77                    ),
78                )
79                .at(slot));
80            }
81            check_range(&context, assignment, slot)?;
82        }
83        Self::build(context, assignments, slots, false)
84    }
85    pub(super) fn subset(
86        context: Arc<TensorStructureContext<R>>,
87        assignments: Vec<GateTrajectoryAssignment>,
88    ) -> Result<Self, StructureError>
89    where
90        R::Client: numr::ops::BinaryOps<R>
91            + numr::ops::CompareOps<R>
92            + numr::ops::ConditionalOps<R>
93            + numr::ops::ReduceOps<R>
94            + numr::ops::ScalarOps<R>
95            + numr::ops::TwoSumOps<R>
96            + numr::ops::TypeConversionOps<R>
97            + numr::ops::UnaryOps<R>,
98    {
99        if assignments.is_empty() {
100            return Err(StructureError::input(
101                StructureInputErrorKind::Identity,
102                "gate trajectory subset is empty: supply an explicit nonempty ordered gate subset",
103            ));
104        }
105        let index: BTreeMap<_, _> = context
106            .elements
107            .iter()
108            .enumerate()
109            .map(|(slot, element)| (element.id.as_str(), slot))
110            .collect();
111        let mut slots = Vec::with_capacity(assignments.len());
112        for assignment in &assignments {
113            let slot = index.get(assignment.structure_id.as_str()).copied().ok_or_else(|| {
114                StructureError::input(
115                    StructureInputErrorKind::Identity,
116                    format!(
117                        "gate assignment={:?}: supply an identity from the complete original structure context",
118                        assignment.structure_id
119                    ),
120                )
121            })?;
122            if !matches!(
123                context.elements[slot].law,
124                StructureLaw::HydrostaticRectangularGate(_)
125            ) {
126                return Err(StructureError::input(
127                    StructureInputErrorKind::Identity,
128                    "gate trajectory assignment requires an actual hydrostatic gate",
129                )
130                .at(slot));
131            }
132            if slots.last().is_some_and(|previous| *previous >= slot) {
133                return Err(StructureError::input(
134                    StructureInputErrorKind::Identity,
135                    "gate trajectory subset must be unique and follow original structure order",
136                )
137                .at(slot));
138            }
139            check_range(&context, assignment, slot)?;
140            slots.push(slot);
141        }
142        Self::build(context, assignments, slots, true)
143    }
144    fn build(
145        context: Arc<TensorStructureContext<R>>,
146        assignments: Vec<GateTrajectoryAssignment>,
147        slots: Vec<usize>,
148        allow_point: bool,
149    ) -> Result<Self, StructureError>
150    where
151        R::Client: numr::ops::BinaryOps<R>
152            + numr::ops::CompareOps<R>
153            + numr::ops::ConditionalOps<R>
154            + numr::ops::ReduceOps<R>
155            + numr::ops::ScalarOps<R>
156            + numr::ops::TwoSumOps<R>
157            + numr::ops::TypeConversionOps<R>
158            + numr::ops::UnaryOps<R>,
159    {
160        let (support, events) = super::events::build(&assignments, allow_point)?;
161        let tensors = TensorTrajectoryContext::new(&context, &assignments, &slots)?;
162        Ok(Self {
163            context,
164            assignments,
165            slots,
166            support,
167            events,
168            tensors,
169        })
170    }
171}
172
173fn check_range<R: Runtime<DType = DType>>(
174    context: &TensorStructureContext<R>,
175    assignment: &GateTrajectoryAssignment,
176    slot: usize,
177) -> Result<(), StructureError> {
178    if let Some(maximum) = gate_opening_limit(&context.elements[slot]) {
179        for (knot_index, knot) in assignment.trajectory.knots().iter().enumerate() {
180            if knot.opening_m > maximum {
181                return Err(StructureError::input(StructureInputErrorKind::Definition,format!("gate knot={knot_index},opening_m={},maximum={maximum}: supply opening within actual gate range. A blocked gate admits openings up to its blocked limit",knot.opening_m)).at(slot));
182            }
183        }
184    }
185    Ok(())
186}