1use std::fmt::Debug;
8
9use crate::action::Action;
10use crate::condition::Condition;
11use crate::config::AriaConfig;
12use crate::error::AriaError;
13use crate::graph::Graph;
14use crate::invariants;
15use crate::invariants::InvariantReport;
16use crate::policy::{DiffPolicy, MatchPolicy};
17use crate::scheduler::Scheduler;
18use crate::state::State;
19use crate::trace::Trace;
20
21pub trait OpticalBackend: Debug + Send + Sync {
23 fn unitary_step(&self, t: u64, psi: &[num_complex::Complex64]) -> Vec<num_complex::Complex64>;
25 fn energy(&self, psi: &[num_complex::Complex64]) -> f64;
27}
28
29pub trait Predictor: Debug + Send + Sync {
31 fn embed(&self, psi: &[num_complex::Complex64]) -> Vec<f64>;
33 fn predict(&self, z: &[f64], a: Condition) -> Vec<f64>;
35 fn dist(&self, a: &[f64], b: &[f64]) -> f64;
37}
38
39pub trait GraphBackend: Debug + Send + Sync {
41 fn edit(
43 &self,
44 g: &Graph,
45 z: &[f64],
46 policy: MatchPolicy,
47 target: Option<&Graph>,
48 ) -> Graph;
49 fn ok(&self, g: &Graph) -> bool;
51}
52
53pub trait Diffuser: Debug + Send + Sync {
55 fn diffuse(&self, g: &Graph, z: &[f64], policy: DiffPolicy) -> Vec<f64>;
57}
58
59#[derive(Debug)]
61pub struct Engine<O, P, G, D>
62where
63 O: OpticalBackend,
64 P: Predictor,
65 G: GraphBackend,
66 D: Diffuser,
67{
68 config: AriaConfig,
69 optical: O,
70 predictor: P,
71 graph_backend: G,
72 diffuser: D,
73}
74
75impl<O, P, GB, D> Engine<O, P, GB, D>
76where
77 O: OpticalBackend,
78 P: Predictor,
79 GB: GraphBackend,
80 D: Diffuser,
81{
82 pub fn new(config: AriaConfig, optical: O, predictor: P, graph_backend: GB, diffuser: D) -> Self {
84 Engine {
85 config,
86 optical,
87 predictor,
88 graph_backend,
89 diffuser,
90 }
91 }
92
93 pub fn init(&self, psi0: Vec<num_complex::Complex64>, g0: Graph, a0: Condition) -> State {
98 let energy_0 = self.optical.energy(&psi0);
99 let z0 = self.predictor.embed(&psi0);
100 let p0 = self.predictor.predict(&z0, a0);
101 let prev_res = self.predictor.dist(&z0, &p0);
102
103 State {
104 psi: psi0,
105 z: z0,
106 g: g0,
107 t: 0,
108 prev_res,
109 energy_0,
110 }
111 }
112
113 pub fn apply(
118 &self,
119 mut state: State,
120 action: Action,
121 a: Condition,
122 ) -> Result<State, AriaError> {
123 match action {
124 Action::OpticalStep => {
125 let prev_psi = state.psi.clone();
127 state.psi = self.optical.unitary_step(state.t, &state.psi);
128
129 let residual = self.compute_residual(&state, a);
131 state.prev_res = residual;
132
133 let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
135 if self.config.strict && !report.all_ok() {
136 if let Some(v) = invariants::violation_from_report(
137 &report, action, state.energy(), state.energy_0,
138 residual, state.prev_res, self.config.eps,
139 ) {
140 state.psi = prev_psi; return Err(AriaError::InvariantViolation(v));
142 }
143 }
144 }
145
146 Action::Predict => {
147 let prev_z = state.z.clone();
149 state.z = self.predictor.predict(&self.predictor.embed(&state.psi), a);
150
151 let residual = self.compute_residual(&state, a);
152 state.prev_res = residual;
153
154 let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
155 if self.config.strict && !report.all_ok() {
156 if let Some(v) = invariants::violation_from_report(
157 &report, action, state.energy(), state.energy_0,
158 residual, state.prev_res, self.config.eps,
159 ) {
160 state.z = prev_z;
161 return Err(AriaError::InvariantViolation(v));
162 }
163 }
164 }
165
166 Action::Match => {
167 let prev_g = state.g.clone();
169 let mut g_with_z = state.g.clone();
170 g_with_z.add_node(
171 format!("z_{}", state.t),
172 state.z.clone(),
173 Some("latent".into()),
174 );
175
176 if g_with_z.size() > self.config.max_graph_size {
178 return Err(AriaError::Schedule(format!(
179 "graph size {} exceeds max {}",
180 g_with_z.size(),
181 self.config.max_graph_size
182 )));
183 }
184
185 state.g = self.graph_backend.edit(
186 &g_with_z,
187 &state.z,
188 self.config.match_policy,
189 None,
190 );
191
192 let residual = self.compute_residual(&state, a);
193 state.prev_res = residual;
194
195 let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
196 if self.config.strict && !report.all_ok() {
197 if let Some(v) = invariants::violation_from_report(
198 &report, action, state.energy(), state.energy_0,
199 residual, state.prev_res, self.config.eps,
200 ) {
201 state.g = prev_g;
202 return Err(AriaError::InvariantViolation(v));
203 }
204 }
205 }
206
207 Action::Diffuse => {
208 let prev_z = state.z.clone();
210 let prev_t = state.t;
211 state.z = self.diffuser.diffuse(&state.g, &state.z, self.config.diff_policy);
212 state.t += 1;
213
214 let residual = self.compute_residual(&state, a);
215 state.prev_res = residual;
216
217 let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
218 if self.config.strict && !report.all_ok() {
219 if let Some(v) = invariants::violation_from_report(
220 &report, action, state.energy(), state.energy_0,
221 residual, state.prev_res, self.config.eps,
222 ) {
223 state.z = prev_z;
224 state.t = prev_t;
225 return Err(AriaError::InvariantViolation(v));
226 }
227 }
228 }
229
230 Action::Stutter => {
231 let residual = self.compute_residual(&state, a);
235 let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
240 if self.config.strict && !report.all_ok() {
241 if let Some(v) = invariants::violation_from_report(
242 &report, action, state.energy(), state.energy_0,
243 residual, state.prev_res, self.config.eps,
244 ) {
245 return Err(AriaError::InvariantViolation(v));
246 }
247 }
248 }
249 }
250
251 Ok(state)
252 }
253
254 pub fn step_phi(&self, state: State, a: Condition) -> Result<State, AriaError> {
259 let s = state;
260 let s = self.apply(s, Action::OpticalStep, a)?;
261 let s = self.apply(s, Action::Predict, a)?;
262 let s = self.apply(s, Action::Match, a)?;
263 let s = self.apply(s, Action::Diffuse, a)?;
264 Ok(s)
265 }
266
267 pub fn run(
271 &self,
272 mut state: State,
273 scheduler: &mut Scheduler,
274 steps: u64,
275 a: Condition,
276 ) -> Result<(State, Trace), AriaError> {
277 let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
278
279 for _ in 0..steps {
280 let action = scheduler.next_action_budgeted();
281 let t_before = state.t;
282
283 state = self.apply(state, action, a)?;
284
285 let residual = self.compute_residual(&state, a);
286 let energy = state.energy();
287 trace.push(
288 t_before,
289 action,
290 residual,
291 energy,
292 state.g.size(),
293 &format!("{:?}", a).to_lowercase(),
294 );
295 }
296
297 Ok((state, trace))
298 }
299
300 pub fn check(&self, state: &State, a: Condition) -> InvariantReport {
302 let residual = self.compute_residual(state, a);
303 invariants::check_all(state, residual, self.config.eps, self.config.latent_dim)
304 }
305
306 fn compute_residual(&self, state: &State, a: Condition) -> f64 {
308 let embedded = self.predictor.embed(&state.psi);
309 let predicted = self.predictor.predict(&embedded, a);
310 self.predictor.dist(&state.z, &predicted)
311 }
312
313 pub fn config(&self) -> &AriaConfig {
315 &self.config
316 }
317}