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::{initial_graph_of, Trace};
21
22pub type MonitoredLatents = (State, Trace, GateReport, Vec<Vec<f64>>);
25
26pub type MonitoredFields = (State, Trace, GateReport, Vec<Vec<f64>>, Vec<f64>);
28
29pub trait OpticalBackend: Debug + Send + Sync {
31 fn unitary_step(&self, t: u64, psi: &[num_complex::Complex64]) -> Vec<num_complex::Complex64>;
33 fn energy(&self, psi: &[num_complex::Complex64]) -> f64 {
38 crate::state::field_energy(psi)
39 }
40}
41
42pub trait Predictor: Debug + Send + Sync {
44 fn embed(&self, psi: &[num_complex::Complex64]) -> Vec<f64>;
46 fn predict(&self, z: &[f64], a: Condition) -> Vec<f64>;
48 fn dist(&self, a: &[f64], b: &[f64]) -> f64;
50}
51
52pub trait GraphBackend: Debug + Send + Sync {
62 fn edit_ops(
68 &self,
69 g: &Graph,
70 z: &[f64],
71 policy: MatchPolicy,
72 target: Option<&Graph>,
73 t: u64,
74 ) -> Vec<GraphOp>;
75
76 fn ok(&self, g: &Graph) -> bool;
78
79 fn commit_ops(&self, _ops: &[GraphOp], _g: &Graph) {}
84
85 fn revert_ops(&self, _journal: &[UndoOp], _g: &Graph) {}
90}
91
92pub trait Diffuser: Debug + Send + Sync {
94 fn diffuse(&self, g: &Graph, z: &[f64], policy: DiffPolicy) -> Vec<f64>;
96}
97
98#[derive(Debug)]
100pub struct Engine<O, P, G, D>
101where
102 O: OpticalBackend,
103 P: Predictor,
104 G: GraphBackend,
105 D: Diffuser,
106{
107 config: AriaConfig,
108 optical: O,
109 predictor: P,
110 graph_backend: G,
111 diffuser: D,
112}
113
114impl<O, P, GB, D> Engine<O, P, GB, D>
115where
116 O: OpticalBackend,
117 P: Predictor,
118 GB: GraphBackend,
119 D: Diffuser,
120{
121 pub fn new(
123 config: AriaConfig,
124 optical: O,
125 predictor: P,
126 graph_backend: GB,
127 diffuser: D,
128 ) -> Self {
129 Engine {
130 config,
131 optical,
132 predictor,
133 graph_backend,
134 diffuser,
135 }
136 }
137
138 pub fn init(
146 &self,
147 psi0: Vec<num_complex::Complex64>,
148 g0: Graph,
149 a0: Condition,
150 ) -> Result<State, AriaError> {
151 self.config.validate()?;
154 if psi0.len() != self.config.n_modes {
155 return Err(AriaError::Config(format!(
156 "ψ₀ has {} modes but config.n_modes = {}",
157 psi0.len(),
158 self.config.n_modes
159 )));
160 }
161 for (i, c) in psi0.iter().enumerate() {
162 if !c.re.is_finite() || !c.im.is_finite() {
163 return Err(AriaError::Config(format!("ψ₀[{i}] = {c} is not finite")));
164 }
165 }
166
167 let energy_0 = self.optical.energy(&psi0);
168 let z0 = self.predictor.embed(&psi0);
169 if z0.len() != self.config.latent_dim {
170 return Err(AriaError::Config(format!(
171 "embed(ψ₀) has dim {} but config.latent_dim = {} — backend/config mismatch",
172 z0.len(),
173 self.config.latent_dim
174 )));
175 }
176 let p0 = self.predictor.predict(&z0, a0);
177 if p0.len() != self.config.latent_dim {
178 return Err(AriaError::Config(format!(
179 "P(z) has dim {} but config.latent_dim = {} — backend/config mismatch",
180 p0.len(),
181 self.config.latent_dim
182 )));
183 }
184 let prev_res = self.predictor.dist(&z0, &p0);
185
186 Ok(State {
187 psi: psi0,
188 z: z0,
189 g: g0,
190 t: 0,
191 prev_res,
192 energy_0,
193 })
194 }
195
196 #[allow(clippy::too_many_lines)]
204 pub fn apply(
205 &self,
206 mut state: State,
207 action: Action,
208 a: Condition,
209 ) -> Result<State, AriaError> {
210 match action {
211 Action::OpticalStep => {
212 let prev_psi = state.psi.clone();
214 let prev_prev_res = state.prev_res;
215 let pre_residual = self.compute_residual(&state, a);
216
217 state.psi = self.optical.unitary_step(state.t, &state.psi);
218 state.prev_res = pre_residual;
220
221 let post_residual = self.compute_residual(&state, a);
222 let report = invariants::check_all(
223 &state,
224 post_residual,
225 self.config.eps,
226 self.config.eps_energy,
227 self.config.n_modes,
228 self.config.latent_dim,
229 );
230 if self.config.strict && !report.all_ok() {
231 if let Some(v) = invariants::violation_from_report(
232 &report,
233 action,
234 state.energy(),
235 state.energy_0,
236 post_residual,
237 state.prev_res,
238 self.config.eps,
239 ) {
240 state.psi = prev_psi;
241 state.prev_res = prev_prev_res;
242 return Err(AriaError::InvariantViolation(v));
243 }
244 }
245 }
246
247 Action::Predict => {
248 let prev_z = state.z.clone();
250 let prev_prev_res = state.prev_res;
251 let pre_residual = self.compute_residual(&state, a);
252
253 state.z = self.predictor.predict(&self.predictor.embed(&state.psi), a);
254 state.prev_res = pre_residual;
255
256 let post_residual = self.compute_residual(&state, a);
257 let report = invariants::check_all(
258 &state,
259 post_residual,
260 self.config.eps,
261 self.config.eps_energy,
262 self.config.n_modes,
263 self.config.latent_dim,
264 );
265 if self.config.strict && !report.all_ok() {
266 if let Some(v) = invariants::violation_from_report(
267 &report,
268 action,
269 state.energy(),
270 state.energy_0,
271 post_residual,
272 state.prev_res,
273 self.config.eps,
274 ) {
275 state.z = prev_z;
276 state.prev_res = prev_prev_res;
277 return Err(AriaError::InvariantViolation(v));
278 }
279 }
280 }
281
282 Action::Match => {
283 let prev_prev_res = state.prev_res;
291 let pre_residual = self.compute_residual(&state, a);
292
293 let ops = self.graph_backend.edit_ops(
294 &state.g,
295 &state.z,
296 self.config.match_policy,
297 None,
298 state.t,
299 );
300
301 let journal = state
302 .g
303 .apply_ops(&ops, self.config.latent_dim)
304 .map_err(|e| AriaError::Backend(format!("Match op refused: {e}")))?;
305
306 if state.g.size() > self.config.max_graph_size {
309 let size = state.g.size();
310 state.g.undo_ops(&journal);
311 self.graph_backend.revert_ops(&journal, &state.g);
312 return Err(AriaError::Schedule(format!(
313 "graph size {} exceeds max {}",
314 size, self.config.max_graph_size
315 )));
316 }
317
318 self.graph_backend.commit_ops(&ops, &state.g);
319 state.prev_res = pre_residual;
320
321 let post_residual = self.compute_residual(&state, a);
322 let report = invariants::check_all(
323 &state,
324 post_residual,
325 self.config.eps,
326 self.config.eps_energy,
327 self.config.n_modes,
328 self.config.latent_dim,
329 );
330 if self.config.strict && !report.all_ok() {
331 if let Some(v) = invariants::violation_from_report(
332 &report,
333 action,
334 state.energy(),
335 state.energy_0,
336 post_residual,
337 state.prev_res,
338 self.config.eps,
339 ) {
340 state.g.undo_ops(&journal);
341 self.graph_backend.revert_ops(&journal, &state.g);
342 state.prev_res = prev_prev_res;
343 return Err(AriaError::InvariantViolation(v));
344 }
345 }
346 }
347
348 Action::Diffuse => {
349 let prev_z = state.z.clone();
351 let prev_t = state.t;
352 let prev_prev_res = state.prev_res;
353 let pre_residual = self.compute_residual(&state, a);
354
355 state.z = self
356 .diffuser
357 .diffuse(&state.g, &state.z, self.config.diff_policy);
358 state.t = state
359 .t
360 .checked_add(1)
361 .ok_or_else(|| AriaError::Backend("t overflowed u64".into()))?;
362 state.prev_res = pre_residual;
363
364 let post_residual = self.compute_residual(&state, a);
365 let report = invariants::check_all(
366 &state,
367 post_residual,
368 self.config.eps,
369 self.config.eps_energy,
370 self.config.n_modes,
371 self.config.latent_dim,
372 );
373 if self.config.strict && !report.all_ok() {
374 if let Some(v) = invariants::violation_from_report(
375 &report,
376 action,
377 state.energy(),
378 state.energy_0,
379 post_residual,
380 state.prev_res,
381 self.config.eps,
382 ) {
383 state.z = prev_z;
384 state.t = prev_t;
385 state.prev_res = prev_prev_res;
386 return Err(AriaError::InvariantViolation(v));
387 }
388 }
389 }
390
391 Action::Stutter => {
392 let residual = self.compute_residual(&state, a);
394
395 let report = invariants::check_all(
396 &state,
397 residual,
398 self.config.eps,
399 self.config.eps_energy,
400 self.config.n_modes,
401 self.config.latent_dim,
402 );
403 if self.config.strict && !report.all_ok() {
404 if let Some(v) = invariants::violation_from_report(
405 &report,
406 action,
407 state.energy(),
408 state.energy_0,
409 residual,
410 state.prev_res,
411 self.config.eps,
412 ) {
413 return Err(AriaError::InvariantViolation(v));
414 }
415 }
416 }
417 }
418
419 Ok(state)
420 }
421
422 pub fn step_phi(&self, state: State, a: Condition) -> Result<State, AriaError> {
427 let s = state;
428 let s = self.apply(s, Action::OpticalStep, a)?;
429 let s = self.apply(s, Action::Predict, a)?;
430 let s = self.apply(s, Action::Match, a)?;
431 let s = self.apply(s, Action::Diffuse, a)?;
432 Ok(s)
433 }
434
435 pub fn run(
439 &self,
440 state: State,
441 scheduler: &mut Scheduler,
442 steps: u64,
443 a: Condition,
444 ) -> Result<(State, Trace), AriaError> {
445 let (state, trace, _) = self.run_monitored(state, scheduler, steps, a)?;
446 Ok((state, trace))
447 }
448
449 pub fn run_monitored(
455 &self,
456 mut state: State,
457 scheduler: &mut Scheduler,
458 steps: u64,
459 a: Condition,
460 ) -> Result<(State, Trace, GateReport), AriaError> {
461 let mut trace = Trace::new(
462 self.config.n_modes,
463 self.config.latent_dim,
464 self.config.eps,
465 self.config.seed,
466 &self.config.schedule,
467 a,
468 self.config.match_policy,
469 self.config.diff_policy,
470 self.config.stutter_k,
471 self.config.optical.clone(),
472 self.config.merge_tau,
473 initial_graph_of(&state.g),
474 );
475 let mut monitor = GateMonitor::new(self.config.gates.clone());
476
477 for _ in 0..steps {
478 let action = scheduler.next_action_budgeted();
479 let t_before = state.t;
480
481 state = self.apply(state, action, a)?;
482
483 let residual = self.compute_residual(&state, a);
484 let energy = state.energy();
485 trace.push(
486 t_before,
487 action,
488 residual,
489 energy,
490 state.g.size(),
491 &format!("{a:?}").to_lowercase(),
492 );
493 monitor.observe(action, &state, residual, self.config.eps);
494 }
495
496 Ok((state, trace, monitor.finish()))
497 }
498
499 pub fn run_monitored_with_latents(
506 &self,
507 mut state: State,
508 scheduler: &mut Scheduler,
509 steps: u64,
510 a: Condition,
511 ) -> Result<MonitoredLatents, AriaError> {
512 let mut trace = Trace::new(
513 self.config.n_modes,
514 self.config.latent_dim,
515 self.config.eps,
516 self.config.seed,
517 &self.config.schedule,
518 a,
519 self.config.match_policy,
520 self.config.diff_policy,
521 self.config.stutter_k,
522 self.config.optical.clone(),
523 self.config.merge_tau,
524 initial_graph_of(&state.g),
525 );
526 let mut monitor = GateMonitor::new(self.config.gates.clone());
527 let mut latents = Vec::with_capacity(usize::try_from(steps).unwrap_or(0));
528
529 for _ in 0..steps {
530 let action = scheduler.next_action_budgeted();
531 let t_before = state.t;
532
533 state = self.apply(state, action, a)?;
534
535 let residual = self.compute_residual(&state, a);
536 let energy = state.energy();
537 trace.push(
538 t_before,
539 action,
540 residual,
541 energy,
542 state.g.size(),
543 &format!("{a:?}").to_lowercase(),
544 );
545 monitor.observe(action, &state, residual, self.config.eps);
546 latents.push(state.z.clone());
547 }
548
549 Ok((state, trace, monitor.finish(), latents))
550 }
551
552 pub fn run_monitored_fields(
556 &self,
557 mut state: State,
558 scheduler: &mut Scheduler,
559 steps: u64,
560 a: Condition,
561 ) -> Result<MonitoredFields, AriaError> {
562 let mut trace = Trace::new(
563 self.config.n_modes,
564 self.config.latent_dim,
565 self.config.eps,
566 self.config.seed,
567 &self.config.schedule,
568 a,
569 self.config.match_policy,
570 self.config.diff_policy,
571 self.config.stutter_k,
572 self.config.optical.clone(),
573 self.config.merge_tau,
574 initial_graph_of(&state.g),
575 );
576 let mut monitor = GateMonitor::new(self.config.gates.clone());
577 let cap = usize::try_from(steps).unwrap_or(0);
578 let mut latents = Vec::with_capacity(cap);
579 let mut phases = Vec::with_capacity(cap);
580
581 for _ in 0..steps {
582 let action = scheduler.next_action_budgeted();
583 let t_before = state.t;
584
585 state = self.apply(state, action, a)?;
586
587 let residual = self.compute_residual(&state, a);
588 let energy = state.energy();
589 trace.push(
590 t_before,
591 action,
592 residual,
593 energy,
594 state.g.size(),
595 &format!("{a:?}").to_lowercase(),
596 );
597 monitor.observe(action, &state, residual, self.config.eps);
598 latents.push(state.z.clone());
599 phases.push(state.psi.first().map_or(0.0, |c| c.arg()));
600 }
601
602 Ok((state, trace, monitor.finish(), latents, phases))
603 }
604
605 pub fn check(&self, state: &State, a: Condition) -> InvariantReport {
607 let residual = self.compute_residual(state, a);
608 invariants::check_all(
609 state,
610 residual,
611 self.config.eps,
612 self.config.eps_energy,
613 self.config.n_modes,
614 self.config.latent_dim,
615 )
616 }
617
618 pub fn residual(&self, state: &State, a: Condition) -> f64 {
623 self.compute_residual(state, a)
624 }
625
626 fn compute_residual(&self, state: &State, a: Condition) -> f64 {
628 let embedded = self.predictor.embed(&state.psi);
629 let predicted = self.predictor.predict(&embedded, a);
630 self.predictor.dist(&state.z, &predicted)
631 }
632
633 pub fn config(&self) -> &AriaConfig {
635 &self.config
636 }
637
638 pub fn graph_backend(&self) -> &GB {
644 &self.graph_backend
645 }
646}