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;
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 trait OpticalBackend: Debug + Send + Sync {
24 fn unitary_step(&self, t: u64, psi: &[num_complex::Complex64]) -> Vec<num_complex::Complex64>;
26 fn energy(&self, psi: &[num_complex::Complex64]) -> f64;
28}
29
30pub trait Predictor: Debug + Send + Sync {
32 fn embed(&self, psi: &[num_complex::Complex64]) -> Vec<f64>;
34 fn predict(&self, z: &[f64], a: Condition) -> Vec<f64>;
36 fn dist(&self, a: &[f64], b: &[f64]) -> f64;
38}
39
40pub trait GraphBackend: Debug + Send + Sync {
42 fn edit(
44 &self,
45 g: &Graph,
46 z: &[f64],
47 policy: MatchPolicy,
48 target: Option<&Graph>,
49 ) -> Graph;
50 fn ok(&self, g: &Graph) -> bool;
52}
53
54pub trait Diffuser: Debug + Send + Sync {
56 fn diffuse(&self, g: &Graph, z: &[f64], policy: DiffPolicy) -> Vec<f64>;
58}
59
60#[derive(Debug)]
62pub struct Engine<O, P, G, D>
63where
64 O: OpticalBackend,
65 P: Predictor,
66 G: GraphBackend,
67 D: Diffuser,
68{
69 config: AriaConfig,
70 optical: O,
71 predictor: P,
72 graph_backend: G,
73 diffuser: D,
74}
75
76impl<O, P, GB, D> Engine<O, P, GB, D>
77where
78 O: OpticalBackend,
79 P: Predictor,
80 GB: GraphBackend,
81 D: Diffuser,
82{
83 pub fn new(config: AriaConfig, optical: O, predictor: P, graph_backend: GB, diffuser: D) -> Self {
85 Engine {
86 config,
87 optical,
88 predictor,
89 graph_backend,
90 diffuser,
91 }
92 }
93
94 pub fn init(
102 &self,
103 psi0: Vec<num_complex::Complex64>,
104 g0: Graph,
105 a0: Condition,
106 ) -> Result<State, AriaError> {
107 if self.config.n_modes == 0 {
108 return Err(AriaError::Config("n_modes must be ≥ 1".into()));
109 }
110 if self.config.latent_dim == 0 {
111 return Err(AriaError::Config("latent_dim must be ≥ 1".into()));
112 }
113 if psi0.len() != self.config.n_modes {
114 return Err(AriaError::Config(format!(
115 "ψ₀ has {} modes but config.n_modes = {}",
116 psi0.len(),
117 self.config.n_modes
118 )));
119 }
120 for (i, c) in psi0.iter().enumerate() {
121 if !c.re.is_finite() || !c.im.is_finite() {
122 return Err(AriaError::Config(format!(
123 "ψ₀[{}] = {} is not finite",
124 i, c
125 )));
126 }
127 }
128
129 let energy_0 = self.optical.energy(&psi0);
130 let z0 = self.predictor.embed(&psi0);
131 if z0.len() != self.config.latent_dim {
132 return Err(AriaError::Config(format!(
133 "embed(ψ₀) has dim {} but config.latent_dim = {} — backend/config mismatch",
134 z0.len(),
135 self.config.latent_dim
136 )));
137 }
138 let p0 = self.predictor.predict(&z0, a0);
139 if p0.len() != self.config.latent_dim {
140 return Err(AriaError::Config(format!(
141 "P(z) has dim {} but config.latent_dim = {} — backend/config mismatch",
142 p0.len(),
143 self.config.latent_dim
144 )));
145 }
146 let prev_res = self.predictor.dist(&z0, &p0);
147
148 Ok(State {
149 psi: psi0,
150 z: z0,
151 g: g0,
152 t: 0,
153 prev_res,
154 energy_0,
155 })
156 }
157
158 pub fn apply(
163 &self,
164 mut state: State,
165 action: Action,
166 a: Condition,
167 ) -> Result<State, AriaError> {
168 match action {
169 Action::OpticalStep => {
170 let prev_psi = state.psi.clone();
172 let prev_prev_res = state.prev_res;
173 let pre_residual = self.compute_residual(&state, a);
174
175 state.psi = self.optical.unitary_step(state.t, &state.psi);
176 state.prev_res = pre_residual;
178
179 let post_residual = self.compute_residual(&state, a);
180 let report = invariants::check_all(
181 &state,
182 post_residual,
183 self.config.eps,
184 self.config.n_modes,
185 self.config.latent_dim,
186 );
187 if self.config.strict && !report.all_ok() {
188 if let Some(v) = invariants::violation_from_report(
189 &report, action, state.energy(), state.energy_0,
190 post_residual, state.prev_res, self.config.eps,
191 ) {
192 state.psi = prev_psi;
193 state.prev_res = prev_prev_res;
194 return Err(AriaError::InvariantViolation(v));
195 }
196 }
197 }
198
199 Action::Predict => {
200 let prev_z = state.z.clone();
202 let prev_prev_res = state.prev_res;
203 let pre_residual = self.compute_residual(&state, a);
204
205 state.z = self.predictor.predict(&self.predictor.embed(&state.psi), a);
206 state.prev_res = pre_residual;
207
208 let post_residual = self.compute_residual(&state, a);
209 let report = invariants::check_all(
210 &state,
211 post_residual,
212 self.config.eps,
213 self.config.n_modes,
214 self.config.latent_dim,
215 );
216 if self.config.strict && !report.all_ok() {
217 if let Some(v) = invariants::violation_from_report(
218 &report, action, state.energy(), state.energy_0,
219 post_residual, state.prev_res, self.config.eps,
220 ) {
221 state.z = prev_z;
222 state.prev_res = prev_prev_res;
223 return Err(AriaError::InvariantViolation(v));
224 }
225 }
226 }
227
228 Action::Match => {
229 let prev_g = state.g.clone();
231 let prev_prev_res = state.prev_res;
232 let pre_residual = self.compute_residual(&state, a);
233
234 let mut g_with_z = state.g.clone();
235 g_with_z.add_node(
236 format!("z_{}", state.t),
237 state.z.clone(),
238 Some("latent".into()),
239 );
240
241 if g_with_z.size() > self.config.max_graph_size {
243 return Err(AriaError::Schedule(format!(
244 "graph size {} exceeds max {}",
245 g_with_z.size(),
246 self.config.max_graph_size
247 )));
248 }
249
250 state.g = self.graph_backend.edit(
251 &g_with_z,
252 &state.z,
253 self.config.match_policy,
254 None,
255 );
256 state.prev_res = pre_residual;
257
258 let post_residual = self.compute_residual(&state, a);
259 let report = invariants::check_all(
260 &state,
261 post_residual,
262 self.config.eps,
263 self.config.n_modes,
264 self.config.latent_dim,
265 );
266 if self.config.strict && !report.all_ok() {
267 if let Some(v) = invariants::violation_from_report(
268 &report, action, state.energy(), state.energy_0,
269 post_residual, state.prev_res, self.config.eps,
270 ) {
271 state.g = prev_g;
272 state.prev_res = prev_prev_res;
273 return Err(AriaError::InvariantViolation(v));
274 }
275 }
276 }
277
278 Action::Diffuse => {
279 let prev_z = state.z.clone();
281 let prev_t = state.t;
282 let prev_prev_res = state.prev_res;
283 let pre_residual = self.compute_residual(&state, a);
284
285 state.z = self.diffuser.diffuse(&state.g, &state.z, self.config.diff_policy);
286 state.t = state
287 .t
288 .checked_add(1)
289 .ok_or_else(|| AriaError::Backend("t overflowed u64".into()))?;
290 state.prev_res = pre_residual;
291
292 let post_residual = self.compute_residual(&state, a);
293 let report = invariants::check_all(
294 &state,
295 post_residual,
296 self.config.eps,
297 self.config.n_modes,
298 self.config.latent_dim,
299 );
300 if self.config.strict && !report.all_ok() {
301 if let Some(v) = invariants::violation_from_report(
302 &report, action, state.energy(), state.energy_0,
303 post_residual, state.prev_res, self.config.eps,
304 ) {
305 state.z = prev_z;
306 state.t = prev_t;
307 state.prev_res = prev_prev_res;
308 return Err(AriaError::InvariantViolation(v));
309 }
310 }
311 }
312
313 Action::Stutter => {
314 let residual = self.compute_residual(&state, a);
316
317 let report = invariants::check_all(
318 &state,
319 residual,
320 self.config.eps,
321 self.config.n_modes,
322 self.config.latent_dim,
323 );
324 if self.config.strict && !report.all_ok() {
325 if let Some(v) = invariants::violation_from_report(
326 &report, action, state.energy(), state.energy_0,
327 residual, state.prev_res, self.config.eps,
328 ) {
329 return Err(AriaError::InvariantViolation(v));
330 }
331 }
332 }
333 }
334
335 Ok(state)
336 }
337
338 pub fn step_phi(&self, state: State, a: Condition) -> Result<State, AriaError> {
343 let s = state;
344 let s = self.apply(s, Action::OpticalStep, a)?;
345 let s = self.apply(s, Action::Predict, a)?;
346 let s = self.apply(s, Action::Match, a)?;
347 let s = self.apply(s, Action::Diffuse, a)?;
348 Ok(s)
349 }
350
351 pub fn run(
355 &self,
356 state: State,
357 scheduler: &mut Scheduler,
358 steps: u64,
359 a: Condition,
360 ) -> Result<(State, Trace), AriaError> {
361 let (state, trace, _) = self.run_monitored(state, scheduler, steps, a)?;
362 Ok((state, trace))
363 }
364
365 pub fn run_monitored(
371 &self,
372 mut state: State,
373 scheduler: &mut Scheduler,
374 steps: u64,
375 a: Condition,
376 ) -> Result<(State, Trace, GateReport), AriaError> {
377 let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
378 let mut monitor = GateMonitor::new(self.config.gates.clone());
379
380 for _ in 0..steps {
381 let action = scheduler.next_action_budgeted();
382 let t_before = state.t;
383
384 state = self.apply(state, action, a)?;
385
386 let residual = self.compute_residual(&state, a);
387 let energy = state.energy();
388 trace.push(
389 t_before,
390 action,
391 residual,
392 energy,
393 state.g.size(),
394 &format!("{:?}", a).to_lowercase(),
395 );
396 monitor.observe(action, &state, residual, self.config.eps);
397 }
398
399 Ok((state, trace, monitor.finish()))
400 }
401
402 pub fn check(&self, state: &State, a: Condition) -> InvariantReport {
404 let residual = self.compute_residual(state, a);
405 invariants::check_all(state, residual, self.config.eps, self.config.n_modes, self.config.latent_dim)
406 }
407
408 fn compute_residual(&self, state: &State, a: Condition) -> f64 {
410 let embedded = self.predictor.embed(&state.psi);
411 let predicted = self.predictor.predict(&embedded, a);
412 self.predictor.dist(&state.z, &predicted)
413 }
414
415 pub fn config(&self) -> &AriaConfig {
417 &self.config
418 }
419}