1use std::fmt::Debug;
8
9use crate::action::Action;
10use crate::condition::Condition;
11use crate::config::AriaConfig;
12use crate::error::AriaError;
13use crate::gates::{GateMonitor, GateReport};
14use crate::graph::{Graph, GraphOp, UndoOp};
15use crate::invariants;
16use crate::invariants::InvariantReport;
17use crate::policy::{DiffPolicy, MatchPolicy};
18use crate::scheduler::Scheduler;
19use crate::state::State;
20use crate::trace::Trace;
21
22pub type MonitoredLatents = (State, Trace, GateReport, Vec<Vec<f64>>);
25
26pub trait OpticalBackend: Debug + Send + Sync {
28 fn unitary_step(&self, t: u64, psi: &[num_complex::Complex64]) -> Vec<num_complex::Complex64>;
30 fn energy(&self, psi: &[num_complex::Complex64]) -> f64 {
35 crate::state::field_energy(psi)
36 }
37}
38
39pub trait Predictor: Debug + Send + Sync {
41 fn embed(&self, psi: &[num_complex::Complex64]) -> Vec<f64>;
43 fn predict(&self, z: &[f64], a: Condition) -> Vec<f64>;
45 fn dist(&self, a: &[f64], b: &[f64]) -> f64;
47}
48
49pub trait GraphBackend: Debug + Send + Sync {
59 fn edit_ops(
65 &self,
66 g: &Graph,
67 z: &[f64],
68 policy: MatchPolicy,
69 target: Option<&Graph>,
70 t: u64,
71 ) -> Vec<GraphOp>;
72
73 fn ok(&self, g: &Graph) -> bool;
75
76 fn commit_ops(&self, _ops: &[GraphOp], _g: &Graph) {}
81
82 fn revert_ops(&self, _journal: &[UndoOp], _g: &Graph) {}
87}
88
89pub trait Diffuser: Debug + Send + Sync {
91 fn diffuse(&self, g: &Graph, z: &[f64], policy: DiffPolicy) -> Vec<f64>;
93}
94
95#[derive(Debug)]
97pub struct Engine<O, P, G, D>
98where
99 O: OpticalBackend,
100 P: Predictor,
101 G: GraphBackend,
102 D: Diffuser,
103{
104 config: AriaConfig,
105 optical: O,
106 predictor: P,
107 graph_backend: G,
108 diffuser: D,
109}
110
111impl<O, P, GB, D> Engine<O, P, GB, D>
112where
113 O: OpticalBackend,
114 P: Predictor,
115 GB: GraphBackend,
116 D: Diffuser,
117{
118 pub fn new(config: AriaConfig, optical: O, predictor: P, graph_backend: GB, diffuser: D) -> Self {
120 Engine {
121 config,
122 optical,
123 predictor,
124 graph_backend,
125 diffuser,
126 }
127 }
128
129 pub fn init(
137 &self,
138 psi0: Vec<num_complex::Complex64>,
139 g0: Graph,
140 a0: Condition,
141 ) -> Result<State, AriaError> {
142 self.config.validate()?;
145 if psi0.len() != self.config.n_modes {
146 return Err(AriaError::Config(format!(
147 "ψ₀ has {} modes but config.n_modes = {}",
148 psi0.len(),
149 self.config.n_modes
150 )));
151 }
152 for (i, c) in psi0.iter().enumerate() {
153 if !c.re.is_finite() || !c.im.is_finite() {
154 return Err(AriaError::Config(format!(
155 "ψ₀[{i}] = {c} is not finite"
156 )));
157 }
158 }
159
160 let energy_0 = self.optical.energy(&psi0);
161 let z0 = self.predictor.embed(&psi0);
162 if z0.len() != self.config.latent_dim {
163 return Err(AriaError::Config(format!(
164 "embed(ψ₀) has dim {} but config.latent_dim = {} — backend/config mismatch",
165 z0.len(),
166 self.config.latent_dim
167 )));
168 }
169 let p0 = self.predictor.predict(&z0, a0);
170 if p0.len() != self.config.latent_dim {
171 return Err(AriaError::Config(format!(
172 "P(z) has dim {} but config.latent_dim = {} — backend/config mismatch",
173 p0.len(),
174 self.config.latent_dim
175 )));
176 }
177 let prev_res = self.predictor.dist(&z0, &p0);
178
179 Ok(State {
180 psi: psi0,
181 z: z0,
182 g: g0,
183 t: 0,
184 prev_res,
185 energy_0,
186 })
187 }
188
189 #[allow(clippy::too_many_lines)]
197 pub fn apply(
198 &self,
199 mut state: State,
200 action: Action,
201 a: Condition,
202 ) -> Result<State, AriaError> {
203 match action {
204 Action::OpticalStep => {
205 let prev_psi = state.psi.clone();
207 let prev_prev_res = state.prev_res;
208 let pre_residual = self.compute_residual(&state, a);
209
210 state.psi = self.optical.unitary_step(state.t, &state.psi);
211 state.prev_res = pre_residual;
213
214 let post_residual = self.compute_residual(&state, a);
215 let report = invariants::check_all(
216 &state,
217 post_residual,
218 self.config.eps,
219 self.config.eps_energy,
220 self.config.n_modes,
221 self.config.latent_dim,
222 );
223 if self.config.strict && !report.all_ok() {
224 if let Some(v) = invariants::violation_from_report(
225 &report, action, state.energy(), state.energy_0,
226 post_residual, state.prev_res, self.config.eps,
227 ) {
228 state.psi = prev_psi;
229 state.prev_res = prev_prev_res;
230 return Err(AriaError::InvariantViolation(v));
231 }
232 }
233 }
234
235 Action::Predict => {
236 let prev_z = state.z.clone();
238 let prev_prev_res = state.prev_res;
239 let pre_residual = self.compute_residual(&state, a);
240
241 state.z = self.predictor.predict(&self.predictor.embed(&state.psi), a);
242 state.prev_res = pre_residual;
243
244 let post_residual = self.compute_residual(&state, a);
245 let report = invariants::check_all(
246 &state,
247 post_residual,
248 self.config.eps,
249 self.config.eps_energy,
250 self.config.n_modes,
251 self.config.latent_dim,
252 );
253 if self.config.strict && !report.all_ok() {
254 if let Some(v) = invariants::violation_from_report(
255 &report, action, state.energy(), state.energy_0,
256 post_residual, state.prev_res, self.config.eps,
257 ) {
258 state.z = prev_z;
259 state.prev_res = prev_prev_res;
260 return Err(AriaError::InvariantViolation(v));
261 }
262 }
263 }
264
265 Action::Match => {
266 let prev_prev_res = state.prev_res;
274 let pre_residual = self.compute_residual(&state, a);
275
276 let ops = self.graph_backend.edit_ops(
277 &state.g,
278 &state.z,
279 self.config.match_policy,
280 None,
281 state.t,
282 );
283
284 let journal = state
285 .g
286 .apply_ops(&ops, self.config.latent_dim)
287 .map_err(|e| AriaError::Backend(format!("Match op refused: {e}")))?;
288
289 if state.g.size() > self.config.max_graph_size {
292 let size = state.g.size();
293 state.g.undo_ops(&journal);
294 self.graph_backend.revert_ops(&journal, &state.g);
295 return Err(AriaError::Schedule(format!(
296 "graph size {} exceeds max {}",
297 size, self.config.max_graph_size
298 )));
299 }
300
301 self.graph_backend.commit_ops(&ops, &state.g);
302 state.prev_res = pre_residual;
303
304 let post_residual = self.compute_residual(&state, a);
305 let report = invariants::check_all(
306 &state,
307 post_residual,
308 self.config.eps,
309 self.config.eps_energy,
310 self.config.n_modes,
311 self.config.latent_dim,
312 );
313 if self.config.strict && !report.all_ok() {
314 if let Some(v) = invariants::violation_from_report(
315 &report, action, state.energy(), state.energy_0,
316 post_residual, state.prev_res, self.config.eps,
317 ) {
318 state.g.undo_ops(&journal);
319 self.graph_backend.revert_ops(&journal, &state.g);
320 state.prev_res = prev_prev_res;
321 return Err(AriaError::InvariantViolation(v));
322 }
323 }
324 }
325
326 Action::Diffuse => {
327 let prev_z = state.z.clone();
329 let prev_t = state.t;
330 let prev_prev_res = state.prev_res;
331 let pre_residual = self.compute_residual(&state, a);
332
333 state.z = self.diffuser.diffuse(&state.g, &state.z, self.config.diff_policy);
334 state.t = state
335 .t
336 .checked_add(1)
337 .ok_or_else(|| AriaError::Backend("t overflowed u64".into()))?;
338 state.prev_res = pre_residual;
339
340 let post_residual = self.compute_residual(&state, a);
341 let report = invariants::check_all(
342 &state,
343 post_residual,
344 self.config.eps,
345 self.config.eps_energy,
346 self.config.n_modes,
347 self.config.latent_dim,
348 );
349 if self.config.strict && !report.all_ok() {
350 if let Some(v) = invariants::violation_from_report(
351 &report, action, state.energy(), state.energy_0,
352 post_residual, state.prev_res, self.config.eps,
353 ) {
354 state.z = prev_z;
355 state.t = prev_t;
356 state.prev_res = prev_prev_res;
357 return Err(AriaError::InvariantViolation(v));
358 }
359 }
360 }
361
362 Action::Stutter => {
363 let residual = self.compute_residual(&state, a);
365
366 let report = invariants::check_all(
367 &state,
368 residual,
369 self.config.eps,
370 self.config.eps_energy,
371 self.config.n_modes,
372 self.config.latent_dim,
373 );
374 if self.config.strict && !report.all_ok() {
375 if let Some(v) = invariants::violation_from_report(
376 &report, action, state.energy(), state.energy_0,
377 residual, state.prev_res, self.config.eps,
378 ) {
379 return Err(AriaError::InvariantViolation(v));
380 }
381 }
382 }
383 }
384
385 Ok(state)
386 }
387
388 pub fn step_phi(&self, state: State, a: Condition) -> Result<State, AriaError> {
393 let s = state;
394 let s = self.apply(s, Action::OpticalStep, a)?;
395 let s = self.apply(s, Action::Predict, a)?;
396 let s = self.apply(s, Action::Match, a)?;
397 let s = self.apply(s, Action::Diffuse, a)?;
398 Ok(s)
399 }
400
401 pub fn run(
405 &self,
406 state: State,
407 scheduler: &mut Scheduler,
408 steps: u64,
409 a: Condition,
410 ) -> Result<(State, Trace), AriaError> {
411 let (state, trace, _) = self.run_monitored(state, scheduler, steps, a)?;
412 Ok((state, trace))
413 }
414
415 pub fn run_monitored(
421 &self,
422 mut state: State,
423 scheduler: &mut Scheduler,
424 steps: u64,
425 a: Condition,
426 ) -> Result<(State, Trace, GateReport), AriaError> {
427 let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
428 let mut monitor = GateMonitor::new(self.config.gates.clone());
429
430 for _ in 0..steps {
431 let action = scheduler.next_action_budgeted();
432 let t_before = state.t;
433
434 state = self.apply(state, action, a)?;
435
436 let residual = self.compute_residual(&state, a);
437 let energy = state.energy();
438 trace.push(
439 t_before,
440 action,
441 residual,
442 energy,
443 state.g.size(),
444 &format!("{a:?}").to_lowercase(),
445 );
446 monitor.observe(action, &state, residual, self.config.eps);
447 }
448
449 Ok((state, trace, monitor.finish()))
450 }
451
452 pub fn run_monitored_with_latents(
459 &self,
460 mut state: State,
461 scheduler: &mut Scheduler,
462 steps: u64,
463 a: Condition,
464 ) -> Result<MonitoredLatents, AriaError> {
465 let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
466 let mut monitor = GateMonitor::new(self.config.gates.clone());
467 let mut latents = Vec::with_capacity(usize::try_from(steps).unwrap_or(0));
468
469 for _ in 0..steps {
470 let action = scheduler.next_action_budgeted();
471 let t_before = state.t;
472
473 state = self.apply(state, action, a)?;
474
475 let residual = self.compute_residual(&state, a);
476 let energy = state.energy();
477 trace.push(
478 t_before,
479 action,
480 residual,
481 energy,
482 state.g.size(),
483 &format!("{a:?}").to_lowercase(),
484 );
485 monitor.observe(action, &state, residual, self.config.eps);
486 latents.push(state.z.clone());
487 }
488
489 Ok((state, trace, monitor.finish(), latents))
490 }
491
492 pub fn check(&self, state: &State, a: Condition) -> InvariantReport {
494 let residual = self.compute_residual(state, a);
495 invariants::check_all(state, residual, self.config.eps, self.config.eps_energy, self.config.n_modes, self.config.latent_dim)
496 }
497
498 pub fn residual(&self, state: &State, a: Condition) -> f64 {
503 self.compute_residual(state, a)
504 }
505
506 fn compute_residual(&self, state: &State, a: Condition) -> f64 {
508 let embedded = self.predictor.embed(&state.psi);
509 let predicted = self.predictor.predict(&embedded, a);
510 self.predictor.dist(&state.z, &predicted)
511 }
512
513 pub fn config(&self) -> &AriaConfig {
515 &self.config
516 }
517
518 pub fn graph_backend(&self) -> &GB {
524 &self.graph_backend
525 }
526}