Skip to main content

qualia_core_db/modalities/logic/
computational_maths_shacl.rs

1//! SHACL constraint surface for the **computational-mathematics engine**.
2//!
3//! Mirrors, in the SHACL/`SlgOpcode` validation layer, the STEM capability libraries built
4//! out under the CALCULUS plan + the computational-engine gap analysis: units & dimensional
5//! analysis, number theory &
6//! combinatorics, special functions, interpolation, integral transforms, vector calculus,
7//! exact/arbitrary-precision arithmetic, the CAS calculus extensions (symbolic integration /
8//! series / limits / equation-solving / assumptions / trig / ODE-PDE / multivariable diff),
9//! and the general-dimension numerical methods.
10//!
11//! Each capability has a typed `*Configuration` (compiled to a bounded `Vec<SlgOpcode>` at
12//! config time, off the hot path) and a SHACL `NodeShape` in [`get_computational_maths_shacl_ttl`].
13//! Wired into the runtime via [`super::shacl::shacl_extension_bridge::append_extension_opcodes`].
14
15use crate::webizen::SlgOpcode;
16
17/// `q42:UnitsConfiguration` — dimensional-analysis / unit-conversion validation.
18#[derive(Debug, Clone)]
19pub struct UnitsConfiguration {
20    /// SI base-dimension vector length (mass, length, time, current, temp, amount, luminous = 7).
21    pub dimension_components: u8,
22    pub require_dimensional_consistency: bool,
23    pub allowed_unit_systems: Vec<String>, // ["si", "cgs", "imperial"]
24}
25
26/// `q42:NumberTheoryConfiguration` — primality / factorization / modular bounds.
27#[derive(Debug, Clone)]
28pub struct NumberTheoryConfiguration {
29    pub max_input_bits: u32, // Miller-Rabin / Pollard-rho input bound
30    pub max_factorization_iterations: u32,
31    pub allowed_operations: Vec<String>, // ["primality","factorization","gcd","totient","modular","combinatorics"]
32}
33
34/// `q42:SpecialFunctionConfiguration` — special-function evaluation parameters.
35#[derive(Debug, Clone)]
36pub struct SpecialFunctionConfiguration {
37    pub max_series_terms: u32,
38    pub convergence_tolerance: f64,
39    pub allowed_families: Vec<String>, // ["bessel","airy","zeta","legendre","chebyshev","hermite","laguerre"]
40}
41
42/// `q42:InterpolationConfiguration` — interpolation / approximation parameters.
43#[derive(Debug, Clone)]
44pub struct InterpolationConfiguration {
45    pub max_nodes: u32,
46    pub require_distinct_nodes: bool,
47    pub allowed_methods: Vec<String>, // ["lagrange","newton","cubic_spline","least_squares"]
48}
49
50/// `q42:IntegralTransformConfiguration` — DFT / Laplace / Z transform parameters.
51#[derive(Debug, Clone)]
52pub struct IntegralTransformConfiguration {
53    pub max_samples: u32,
54    pub require_invertibility_check: bool,
55    pub allowed_transforms: Vec<String>, // ["dft","laplace","ztransform"]
56}
57
58/// `q42:VectorCalculusConfiguration` — grad/div/curl + line/surface integral parameters.
59#[derive(Debug, Clone)]
60pub struct VectorCalculusConfiguration {
61    pub max_spatial_dimension: u8, // 2 or 3
62    pub require_field_smoothness: bool,
63    pub allowed_operators: Vec<String>, // ["gradient","divergence","curl","laplacian","line_integral","surface_integral"]
64}
65
66/// `q42:ExactArithmeticConfiguration` — arbitrary-precision integer / rational parameters.
67#[derive(Debug, Clone)]
68pub struct ExactArithmeticConfiguration {
69    pub max_digits: u32,            // precision ceiling
70    pub require_exact: bool,        // no silent float fallback
71    pub allowed_types: Vec<String>, // ["bigint","bigrational"]
72}
73
74/// `q42:SymbolicCalculusConfiguration` — CAS calculus operations (integration, series,
75/// limits, equation-solving, ODE/PDE, multivariable differentiation).
76#[derive(Debug, Clone)]
77pub struct SymbolicCalculusConfiguration {
78    pub max_order: u32,                       // Taylor / derivative order ceiling
79    pub require_roundtrip_verification: bool, // the honesty gate (d/dx ∘ ∫, residual checks)
80    pub allowed_operations: Vec<String>, // ["integrate","series","limit","solve","ode_solve","pde_classify","gradient","jacobian","hessian"]
81}
82
83/// `q42:AssumptionConfiguration` — simplify-under-assumptions soundness parameters.
84#[derive(Debug, Clone)]
85pub struct AssumptionConfiguration {
86    pub require_sound_rewrite: bool, // no rewrite unless the sign side-condition is proven
87    pub allowed_signs: Vec<String>, // ["positive","nonnegative","negative","nonpositive","nonzero"]
88}
89
90/// `q42:NumericalMethodConfiguration` — general-dimension RK4 / Simpson / shooting-BVP.
91#[derive(Debug, Clone)]
92pub struct NumericalMethodConfiguration {
93    pub max_state_dimension: u32,
94    pub max_steps: u32,
95    pub convergence_tolerance: f64,
96    pub allowed_integrators: Vec<String>, // ["rk4","simpson","shooting_bvp"]
97}
98
99// ── Opcode generation ──────────────────────────────────────────────────────────
100
101impl UnitsConfiguration {
102    /// Emits SLG opcodes configuring units handling.
103    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
104        vec![SlgOpcode::CheckMaxInclusive(
105            self.dimension_components as f64,
106        )]
107    }
108}
109impl NumberTheoryConfiguration {
110    /// Emits SLG opcodes configuring number theory.
111    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
112        vec![
113            SlgOpcode::CheckMaxInclusive(self.max_input_bits as f64),
114            SlgOpcode::CheckMaxInclusive(self.max_factorization_iterations as f64),
115        ]
116    }
117}
118impl SpecialFunctionConfiguration {
119    /// Emits SLG opcodes configuring special functions.
120    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
121        vec![
122            SlgOpcode::CheckMaxInclusive(self.max_series_terms as f64),
123            SlgOpcode::CheckMinInclusive(self.convergence_tolerance),
124        ]
125    }
126}
127impl InterpolationConfiguration {
128    /// Emits SLG opcodes configuring interpolation.
129    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
130        vec![SlgOpcode::CheckMaxInclusive(self.max_nodes as f64)]
131    }
132}
133impl IntegralTransformConfiguration {
134    /// Emits SLG opcodes configuring integral transforms.
135    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
136        vec![SlgOpcode::CheckMaxInclusive(self.max_samples as f64)]
137    }
138}
139impl VectorCalculusConfiguration {
140    /// Emits SLG opcodes configuring vector calculus.
141    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
142        vec![SlgOpcode::CheckMaxInclusive(
143            self.max_spatial_dimension as f64,
144        )]
145    }
146}
147impl ExactArithmeticConfiguration {
148    /// Emits SLG opcodes configuring exact arithmetic.
149    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
150        vec![SlgOpcode::CheckMaxInclusive(self.max_digits as f64)]
151    }
152}
153impl SymbolicCalculusConfiguration {
154    /// Emits SLG opcodes configuring symbolic calculus.
155    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
156        vec![SlgOpcode::CheckMaxInclusive(self.max_order as f64)]
157    }
158}
159impl AssumptionConfiguration {
160    /// Emits SLG opcodes configuring assumptions.
161    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
162        // A single representative allowed sign is bound-checked via has-value.
163        let first = self.allowed_signs.first().cloned().unwrap_or_default();
164        vec![SlgOpcode::CheckHasValue(crate::q_hash(&first))]
165    }
166}
167impl NumericalMethodConfiguration {
168    /// Emits SLG opcodes configuring numerical methods.
169    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
170        vec![
171            SlgOpcode::CheckMaxInclusive(self.max_state_dimension as f64),
172            SlgOpcode::CheckMaxInclusive(self.max_steps as f64),
173        ]
174    }
175}
176
177/// Comprehensive SHACL TTL vocabulary for the computational-mathematics engine.
178pub fn get_computational_maths_shacl_ttl() -> &'static str {
179    r#"
180@prefix q42: <https://webizen.org/q42#> .
181@prefix sh: <http://www.w3.org/ns/shacl#> .
182@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
183
184q42:UnitsConfigurationShape a sh:NodeShape ;
185    sh:property [
186        sh:path q42:dimensionComponents ;
187        sh:datatype xsd:integer ;
188        sh:minInclusive 1 ;
189        sh:maxInclusive 7 ;
190        sh:message "SI base-dimension vector has 7 components" ;
191    ] ;
192    sh:property [
193        sh:path q42:allowedUnitSystems ;
194        sh:in ("si" "cgs" "imperial") ;
195        sh:message "Unit system must be supported" ;
196    ] .
197
198q42:NumberTheoryConfigurationShape a sh:NodeShape ;
199    sh:property [
200        sh:path q42:maxInputBits ;
201        sh:datatype xsd:integer ;
202        sh:minInclusive 1 ;
203        sh:maxInclusive 4096 ;
204        sh:message "Number-theory input must be within the supported bit width" ;
205    ] ;
206    sh:property [
207        sh:path q42:allowedOperations ;
208        sh:in ("primality" "factorization" "gcd" "totient" "modular" "combinatorics") ;
209        sh:message "Operation must be a supported number-theory primitive" ;
210    ] .
211
212q42:SpecialFunctionConfigurationShape a sh:NodeShape ;
213    sh:property [
214        sh:path q42:maxSeriesTerms ;
215        sh:datatype xsd:integer ;
216        sh:minInclusive 1 ;
217        sh:maxInclusive 100000 ;
218        sh:message "Series truncation must be within bounds" ;
219    ] ;
220    sh:property [
221        sh:path q42:allowedFamilies ;
222        sh:in ("bessel" "airy" "zeta" "legendre" "chebyshev" "hermite" "laguerre") ;
223        sh:message "Special-function family must be supported" ;
224    ] .
225
226q42:InterpolationConfigurationShape a sh:NodeShape ;
227    sh:property [
228        sh:path q42:maxNodes ;
229        sh:datatype xsd:integer ;
230        sh:minInclusive 2 ;
231        sh:maxInclusive 1000000 ;
232        sh:message "Interpolation node count must be between 2 and 1,000,000" ;
233    ] ;
234    sh:property [
235        sh:path q42:allowedMethods ;
236        sh:in ("lagrange" "newton" "cubic_spline" "least_squares") ;
237        sh:message "Interpolation method must be supported" ;
238    ] .
239
240q42:IntegralTransformConfigurationShape a sh:NodeShape ;
241    sh:property [
242        sh:path q42:maxSamples ;
243        sh:datatype xsd:integer ;
244        sh:minInclusive 2 ;
245        sh:maxInclusive 16777216 ;
246        sh:message "Transform sample count must be within bounds" ;
247    ] ;
248    sh:property [
249        sh:path q42:allowedTransforms ;
250        sh:in ("dft" "laplace" "ztransform") ;
251        sh:message "Transform must be supported" ;
252    ] .
253
254q42:VectorCalculusConfigurationShape a sh:NodeShape ;
255    sh:property [
256        sh:path q42:maxSpatialDimension ;
257        sh:datatype xsd:integer ;
258        sh:minInclusive 2 ;
259        sh:maxInclusive 3 ;
260        sh:message "Vector calculus supports 2D and 3D fields" ;
261    ] ;
262    sh:property [
263        sh:path q42:allowedOperators ;
264        sh:in ("gradient" "divergence" "curl" "laplacian" "line_integral" "surface_integral") ;
265        sh:message "Vector-calculus operator must be supported" ;
266    ] .
267
268q42:ExactArithmeticConfigurationShape a sh:NodeShape ;
269    sh:property [
270        sh:path q42:maxDigits ;
271        sh:datatype xsd:integer ;
272        sh:minInclusive 1 ;
273        sh:maxInclusive 1000000 ;
274        sh:message "Arbitrary-precision digit count must be within bounds" ;
275    ] ;
276    sh:property [
277        sh:path q42:allowedTypes ;
278        sh:in ("bigint" "bigrational") ;
279        sh:message "Exact-arithmetic type must be supported" ;
280    ] .
281
282q42:SymbolicCalculusConfigurationShape a sh:NodeShape ;
283    sh:property [
284        sh:path q42:maxOrder ;
285        sh:datatype xsd:integer ;
286        sh:minInclusive 1 ;
287        sh:maxInclusive 1024 ;
288        sh:message "Symbolic calculus order must be within bounds" ;
289    ] ;
290    sh:property [
291        sh:path q42:allowedOperations ;
292        sh:in ("integrate" "series" "limit" "solve" "ode_solve" "pde_classify" "gradient" "jacobian" "hessian") ;
293        sh:message "Symbolic-calculus operation must be supported" ;
294    ] .
295
296q42:AssumptionConfigurationShape a sh:NodeShape ;
297    sh:property [
298        sh:path q42:requireSoundRewrite ;
299        sh:datatype xsd:boolean ;
300        sh:message "Assumption-gated rewrites must remain sound" ;
301    ] ;
302    sh:property [
303        sh:path q42:allowedSigns ;
304        sh:in ("positive" "nonnegative" "negative" "nonpositive" "nonzero") ;
305        sh:message "Sign assumption must be a supported domain predicate" ;
306    ] .
307
308q42:NumericalMethodConfigurationShape a sh:NodeShape ;
309    sh:property [
310        sh:path q42:maxStateDimension ;
311        sh:datatype xsd:integer ;
312        sh:minInclusive 1 ;
313        sh:maxInclusive 100000 ;
314        sh:message "ODE state dimension must be within bounds" ;
315    ] ;
316    sh:property [
317        sh:path q42:allowedIntegrators ;
318        sh:in ("rk4" "simpson" "shooting_bvp") ;
319        sh:message "Numerical integrator must be supported" ;
320    ] .
321"#
322}
323
324/// Every NodeShape name in this module's vocabulary (full-coverage assertion target).
325pub const COMPUTATIONAL_MATHS_SHAPES: &[&str] = &[
326    "q42:UnitsConfigurationShape",
327    "q42:NumberTheoryConfigurationShape",
328    "q42:SpecialFunctionConfigurationShape",
329    "q42:InterpolationConfigurationShape",
330    "q42:IntegralTransformConfigurationShape",
331    "q42:VectorCalculusConfigurationShape",
332    "q42:ExactArithmeticConfigurationShape",
333    "q42:SymbolicCalculusConfigurationShape",
334    "q42:AssumptionConfigurationShape",
335    "q42:NumericalMethodConfigurationShape",
336];
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    #[test]
343    fn every_capability_has_a_shape() {
344        let ttl = get_computational_maths_shacl_ttl();
345        for shape in COMPUTATIONAL_MATHS_SHAPES {
346            assert!(ttl.contains(shape), "missing SHACL shape: {shape}");
347        }
348    }
349
350    #[test]
351    fn every_config_generates_opcodes() {
352        assert!(!UnitsConfiguration {
353            dimension_components: 7,
354            require_dimensional_consistency: true,
355            allowed_unit_systems: vec!["si".into()],
356        }
357        .to_opcodes()
358        .is_empty());
359        assert!(!NumberTheoryConfiguration {
360            max_input_bits: 256,
361            max_factorization_iterations: 100_000,
362            allowed_operations: vec!["primality".into()],
363        }
364        .to_opcodes()
365        .is_empty());
366        assert!(!SpecialFunctionConfiguration {
367            max_series_terms: 1000,
368            convergence_tolerance: 1e-12,
369            allowed_families: vec!["bessel".into()],
370        }
371        .to_opcodes()
372        .is_empty());
373        assert!(!InterpolationConfiguration {
374            max_nodes: 1024,
375            require_distinct_nodes: true,
376            allowed_methods: vec!["cubic_spline".into()],
377        }
378        .to_opcodes()
379        .is_empty());
380        assert!(!IntegralTransformConfiguration {
381            max_samples: 4096,
382            require_invertibility_check: true,
383            allowed_transforms: vec!["dft".into()],
384        }
385        .to_opcodes()
386        .is_empty());
387        assert!(!VectorCalculusConfiguration {
388            max_spatial_dimension: 3,
389            require_field_smoothness: true,
390            allowed_operators: vec!["curl".into()],
391        }
392        .to_opcodes()
393        .is_empty());
394        assert!(!ExactArithmeticConfiguration {
395            max_digits: 10_000,
396            require_exact: true,
397            allowed_types: vec!["bigint".into()],
398        }
399        .to_opcodes()
400        .is_empty());
401        assert!(!SymbolicCalculusConfiguration {
402            max_order: 16,
403            require_roundtrip_verification: true,
404            allowed_operations: vec!["integrate".into()],
405        }
406        .to_opcodes()
407        .is_empty());
408        assert!(!AssumptionConfiguration {
409            require_sound_rewrite: true,
410            allowed_signs: vec!["positive".into()],
411        }
412        .to_opcodes()
413        .is_empty());
414        assert!(!NumericalMethodConfiguration {
415            max_state_dimension: 64,
416            max_steps: 10_000,
417            convergence_tolerance: 1e-9,
418            allowed_integrators: vec!["rk4".into()],
419        }
420        .to_opcodes()
421        .is_empty());
422    }
423}