Skip to main content

qualia_core_db/modalities/logic/
specialized_libs_shacl.rs

1//! SHACL Extensions for Specialized Libraries
2//!
3//! This module provides SHACL constraint extensions for all specialized libraries
4//! including linear algebra, machine learning, physics simulation, chemistry modeling,
5//! medical computing, financial modeling, engineering analysis, and statistical computing.
6
7use crate::webizen::SlgOpcode;
8
9// ── Linear Algebra Constraints ───────────────────────────────────────────────
10
11/// `q42:MatrixConfiguration` — validates matrix storage and computation configuration
12#[derive(Debug, Clone)]
13pub struct MatrixConfiguration {
14    pub max_matrix_size: u64,            // Maximum matrix dimension
15    pub max_zone_capacity: u64,          // Maximum zone capacity in bytes
16    pub allowed_zone_types: Vec<String>, // ["Dense", "Sparse", "Structured", "Temporary"]
17    pub require_zero_copy: bool,         // Require zero-copy operations
18}
19
20/// `q42:MatrixOperation` — validates matrix operation parameters
21#[derive(Debug, Clone)]
22pub struct MatrixOperation {
23    pub operation_type: String, // "multiply", "add", "subtract", "invert", etc.
24    pub max_condition_number: f64, // Maximum allowed condition number
25    pub require_numerical_stability: bool,
26    pub precision_mode: String, // "f32", "f64", "f128"
27}
28
29/// `q42:EigenDecomposition` — validates eigenvalue decomposition parameters
30#[derive(Debug, Clone)]
31pub struct EigenDecomposition {
32    pub max_iterations: u32,
33    pub convergence_tolerance: f64,
34    pub require_hermitian: bool, // For real eigenvalues
35    pub algorithm_type: String,  // "qr", "power", "jacobi"
36}
37
38/// `q42:PolynomialSolve` — validates polynomial root-finding parameters
39#[derive(Debug, Clone)]
40pub struct PolynomialSolveConfiguration {
41    pub max_degree: u32,     // Maximum polynomial degree
42    pub method: String,      // "quadratic_closed_form", "durand_kerner", "companion"
43    pub max_iterations: u32, // Iteration cap for iterative methods
44}
45
46/// `q42:SingularValueDecomposition` — validates SVD parameters
47#[derive(Debug, Clone)]
48pub struct SvdConfiguration {
49    pub max_dimension: u32,    // Maximum of m, n
50    pub compute_vectors: bool, // Whether U/V are returned
51    pub method: String,        // "ata_eigen", "golub_reinsch"
52}
53
54/// `q42:Determinant` — validates determinant computation parameters
55#[derive(Debug, Clone)]
56pub struct DeterminantConfiguration {
57    pub max_dimension: u32, // Maximum n for an n×n matrix
58    pub method: String,     // "lu", "cofactor"
59}
60
61/// `q42:SymbolicExpression` — validates symbolic (CAS) expression structure
62#[derive(Debug, Clone)]
63pub struct SymbolicExpressionConfiguration {
64    pub max_depth: u32,                 // Maximum expression-tree depth
65    pub max_variables: u32,             // Maximum distinct variables
66    pub allowed_operators: Vec<String>, // ["add","sub","mul","div","pow","neg","sqrt"]
67}
68
69/// `q42:SymbolicOperation` — validates a symbolic algebra operation request
70#[derive(Debug, Clone)]
71pub struct SymbolicOperationConfiguration {
72    pub operation_type: String, // "differentiate","simplify","expand","evaluate","solve","factor"
73    pub max_iterations: u32,    // Simplification fixpoint bound
74}
75
76// ── Machine Learning Constraints ─────────────────────────────────────────────
77
78/// `q42:ModelConfiguration` — validates ML model configuration
79#[derive(Debug, Clone)]
80pub struct ModelConfiguration {
81    pub max_model_size_mb: u64,           // Maximum model size in MB
82    pub max_parameters: u64,              // Maximum number of parameters
83    pub allowed_model_types: Vec<String>, // ["neural_network", "decision_tree", "svm", etc.]
84    pub require_quantization: bool,       // Require model quantization
85}
86
87/// `q42:TrainingConfiguration` — validates training hyperparameters
88#[derive(Debug, Clone)]
89pub struct TrainingConfiguration {
90    pub max_epochs: u32,
91    pub batch_size_range: (u32, u32),
92    pub learning_rate_range: (f64, f64),
93    pub allowed_optimizers: Vec<String>, // ["adam", "sgd", "rmsprop", etc.]
94    pub require_early_stopping: bool,
95}
96
97/// `q42:InferenceConfiguration` — validates inference parameters
98#[derive(Debug, Clone)]
99pub struct InferenceConfiguration {
100    pub max_batch_size: u32,
101    pub max_latency_ms: u64,
102    pub allowed_precision_modes: Vec<String>, // ["fp32", "fp16", "int8"]
103    pub require_batch_normalization: bool,
104}
105
106// ── Physics Simulation Constraints ───────────────────────────────────────────
107
108/// `q42:SimulationConfiguration` — validates physics simulation configuration
109#[derive(Debug, Clone)]
110pub struct SimulationConfiguration {
111    pub max_time_steps: u64,
112    pub max_spatial_resolution: u32,
113    pub allowed_time_integrators: Vec<String>, // ["euler", "runge_kutta", "verlet"]
114    pub require_energy_conservation: bool,
115    pub max_cfl_number: f64, // Courant-Friedrichs-Lewy condition
116}
117
118/// `q42:BoundaryConditions` — validates boundary condition parameters
119#[derive(Debug, Clone)]
120pub struct BoundaryConditions {
121    pub allowed_boundary_types: Vec<String>, // ["dirichlet", "neumann", "periodic", "mixed"]
122    pub require_consistency: bool,
123    pub max_gradient: f64,
124}
125
126/// `q42:MeshConfiguration` — validates mesh generation parameters
127#[derive(Debug, Clone)]
128pub struct MeshConfiguration {
129    pub max_elements: u64,
130    pub min_element_quality: f64, // Aspect ratio, skewness, etc.
131    pub allowed_element_types: Vec<String>, // ["triangle", "quad", "tetrahedron", "hexahedron"]
132    pub require_manifold: bool,
133}
134
135// ── Chemistry Modeling Constraints ───────────────────────────────────────────
136
137/// `q42:MoleculeConfiguration` — validates molecular structure configuration
138#[derive(Debug, Clone)]
139pub struct MoleculeConfiguration {
140    pub max_atoms: u32,
141    pub max_bonds: u32,
142    pub allowed_element_types: Vec<String>, // Periodic table symbols
143    pub require_valence_satisfaction: bool,
144}
145
146/// `q42:ReactionConfiguration` — validates chemical reaction parameters
147#[derive(Debug, Clone)]
148pub struct ReactionConfiguration {
149    pub max_reactants: u32,
150    pub max_products: u32,
151    pub require_mass_balance: bool,
152    pub require_charge_balance: bool,
153    pub allowed_reaction_types: Vec<String>, // ["synthesis", "decomposition", "redox"]
154}
155
156/// `q42:QuantumCalculation` — validates quantum chemistry calculation parameters
157#[derive(Debug, Clone)]
158pub struct QuantumCalculation {
159    pub max_basis_functions: u32,
160    pub allowed_methods: Vec<String>, // ["dft", "hf", "mp2", "ccsd"]
161    pub max_scf_iterations: u32,
162    pub convergence_threshold: f64,
163}
164
165// ── Medical Computing Constraints ─────────────────────────────────────────────
166
167/// `q42:MedicalDataConfiguration` — validates medical data parameters
168#[derive(Debug, Clone)]
169pub struct MedicalDataConfiguration {
170    pub require_hipaa_compliance: bool,
171    pub require_de_identification: bool,
172    pub allowed_data_types: Vec<String>, // ["fhir", "dicom", "hl7"]
173    pub max_patient_records: u64,
174}
175
176/// `q42:ClinicalDecisionConfiguration` — validates clinical decision support parameters
177#[derive(Debug, Clone)]
178pub struct ClinicalDecisionConfiguration {
179    pub require_evidence_based: bool,
180    pub max_confidence_interval: f64,
181    pub allowed_decision_types: Vec<String>, // ["diagnosis", "treatment", "prognosis"]
182    pub require_physician_review: bool,
183}
184
185/// `q42:MedicalImagingConfiguration` — validates medical imaging parameters
186#[derive(Debug, Clone)]
187pub struct MedicalImagingConfiguration {
188    pub allowed_modalities: Vec<String>, // ["mri", "ct", "xray", "ultrasound"]
189    pub max_resolution: (u32, u32),      // (width, height)
190    pub require_dicom_compliance: bool,
191    pub max_file_size_mb: u64,
192}
193
194// ── Financial Modeling Constraints ───────────────────────────────────────────
195
196/// `q42:FinancialModelConfiguration` — validates financial model parameters
197#[derive(Debug, Clone)]
198pub struct FinancialModelConfiguration {
199    pub max_time_horizon_days: u32,
200    pub allowed_asset_classes: Vec<String>, // ["equity", "fixed_income", "derivative", "crypto"]
201    pub require_risk_metrics: bool,
202    pub max_leverage_ratio: f64,
203}
204
205/// `q42:RiskCalculation` — validates risk calculation parameters
206#[derive(Debug, Clone)]
207pub struct RiskCalculation {
208    pub allowed_risk_models: Vec<String>, // ["var", "cvar", "expected_shortfall"]
209    pub confidence_level_range: (f64, f64), // e.g., (0.95, 0.99)
210    pub max_lookback_days: u32,
211    pub require_stress_testing: bool,
212}
213
214/// `q42:TradingConfiguration` — validates trading strategy parameters
215#[derive(Debug, Clone)]
216pub struct TradingConfiguration {
217    pub max_position_size: f64,
218    pub allowed_order_types: Vec<String>, // ["market", "limit", "stop", "stop_limit"]
219    pub require_risk_limits: bool,
220    pub max_daily_trades: u32,
221}
222
223// ── Engineering Analysis Constraints ─────────────────────────────────────────
224
225/// `q42:EngineeringSimulationConfiguration` — validates engineering simulation parameters
226#[derive(Debug, Clone)]
227pub struct EngineeringSimulationConfiguration {
228    pub max_mesh_elements: u64,
229    pub allowed_analysis_types: Vec<String>, // ["structural", "thermal", "fluid", "electromagnetic"]
230    pub require_convergence: bool,
231    pub max_simulation_time_hours: f64,
232}
233
234/// `q42:MaterialProperties` — validates material property parameters
235#[derive(Debug, Clone)]
236pub struct MaterialProperties {
237    pub allowed_material_types: Vec<String>, // ["metal", "polymer", "ceramic", "composite"]
238    pub require_standard_compliance: bool,   // ASTM, ISO, etc.
239    pub max_temperature_kelvin: f64,
240    pub min_safety_factor: f64,
241}
242
243/// `q42:LoadConfiguration` — validates load and boundary condition parameters
244#[derive(Debug, Clone)]
245pub struct LoadConfiguration {
246    pub max_load_magnitude: f64,
247    pub allowed_load_types: Vec<String>, // ["static", "dynamic", "thermal", "electromagnetic"]
248    pub require_load_combination: bool,
249    pub safety_factor_range: (f64, f64),
250}
251
252// ── Statistical Computing Constraints ───────────────────────────────────────
253
254/// `q42:StatisticalAnalysisConfiguration` — validates statistical analysis parameters
255#[derive(Debug, Clone)]
256pub struct StatisticalAnalysisConfiguration {
257    pub max_sample_size: u64,
258    pub allowed_test_types: Vec<String>, // ["t_test", "anova", "chi_square", "regression"]
259    pub require_normality_test: bool,
260    pub significance_level_range: (f64, f64),
261}
262
263/// `q42:DistributionConfiguration` — validates probability distribution parameters
264#[derive(Debug, Clone)]
265pub struct DistributionConfiguration {
266    pub allowed_distributions: Vec<String>, // ["normal", "binomial", "poisson", "exponential"]
267    pub require_parameter_constraints: bool,
268    pub max_mixture_components: u32,
269}
270
271/// `q42:SamplingConfiguration` — validates sampling method parameters
272#[derive(Debug, Clone)]
273pub struct SamplingConfiguration {
274    pub allowed_sampling_methods: Vec<String>, // ["monte_carlo", "bootstrap", "jackknife"]
275    pub max_iterations: u32,
276    pub require_convergence_diagnostics: bool,
277}
278
279// ── Cryptographic Library Constraints ─────────────────────────────────────────
280
281/// `q42:CryptographicConfiguration` — validates cryptographic operation parameters
282#[derive(Debug, Clone)]
283pub struct CryptographicConfiguration {
284    pub min_key_length_bits: u16,
285    pub allowed_algorithms: Vec<String>, // ["aes", "rsa", "ecc", "sha256"]
286    pub require_fips_compliance: bool,
287    pub max_operation_time_ms: u64,
288}
289
290/// `q42:KeyManagementConfiguration` — validates key management parameters
291#[derive(Debug, Clone)]
292pub struct KeyManagementConfiguration {
293    pub require_hsm: bool,              // Hardware Security Module
294    pub allowed_key_types: Vec<String>, // ["symmetric", "asymmetric", "hash"]
295    pub max_key_lifetime_days: u32,
296    pub require_key_rotation: bool,
297}
298
299/// `q42:DigitalSignatureConfiguration` — validates digital signature parameters
300#[derive(Debug, Clone)]
301pub struct DigitalSignatureConfiguration {
302    pub allowed_signature_algorithms: Vec<String>, // ["ed25519", "rsa_pss", "ecdsa"]
303    pub require_timestamp: bool,
304    pub max_signature_size_bytes: u32,
305}
306
307// ── QPU Bridge Constraints ─────────────────────────────────────────────────────
308
309/// `q42:QPUConfiguration` — validates quantum processing unit parameters
310#[derive(Debug, Clone)]
311pub struct QPUConfiguration {
312    pub max_qubits: u16,
313    pub allowed_qpu_types: Vec<String>, // ["dwave", "ibm", "google", "rigetti"]
314    pub max_circuit_depth: u32,
315    pub require_error_correction: bool,
316}
317
318/// `q42:QuantumCircuitConfiguration` — validates quantum circuit parameters
319#[derive(Debug, Clone)]
320pub struct QuantumCircuitConfiguration {
321    pub max_gates: u32,
322    pub allowed_gate_types: Vec<String>, // ["hadamard", "cnot", "phase", "measurement"]
323    pub require_compilation: bool,
324    pub max_execution_time_ms: u64,
325}
326
327/// `q42:QuantumAnnealingConfiguration` — validates quantum annealing parameters
328#[derive(Debug, Clone)]
329pub struct QuantumAnnealingConfiguration {
330    pub max_annealing_time_us: u32,
331    pub allowed_anneal_schedules: Vec<String>, // ["linear", "reverse", "custom"]
332    pub require_ground_state_verification: bool,
333}
334
335// ── Quantum Biology Constraints ───────────────────────────────────────────────
336
337/// `q42:BiomolecularConfiguration` — validates biomolecular simulation parameters
338#[derive(Debug, Clone)]
339pub struct BiomolecularConfiguration {
340    pub max_atoms: u32,
341    pub max_residues: u32,
342    pub allowed_force_fields: Vec<String>, // ["amber", "charmm", "opls"]
343    pub max_simulation_time_ns: f64,
344}
345
346/// `q42:QuantumBiologyCalculation` — validates quantum biology calculation parameters
347#[derive(Debug, Clone)]
348pub struct QuantumBiologyCalculation {
349    pub max_quantum_states: u32,
350    pub allowed_methods: Vec<String>, // ["dft", "semi_empirical", "force_field"]
351    pub max_convergence_iterations: u32,
352    require_solvent_model: bool,
353}
354
355// ── Opcode Generation Functions ───────────────────────────────────────────────
356
357impl MatrixConfiguration {
358    /// Emits the SLG opcode sequence configuring matrix ops.
359    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
360        vec![
361            SlgOpcode::CheckMaxInclusive(self.max_matrix_size as f64),
362            SlgOpcode::CheckMaxInclusive(self.max_zone_capacity as f64),
363        ]
364    }
365}
366
367impl MatrixOperation {
368    /// Emits the SLG opcode sequence for a matrix operation.
369    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
370        vec![
371            SlgOpcode::CheckMaxInclusive(self.max_condition_number),
372            SlgOpcode::CheckHasValue(crate::q_hash(&self.precision_mode)),
373        ]
374    }
375}
376
377impl ModelConfiguration {
378    /// Emits SLG opcodes configuring an ML model.
379    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
380        vec![
381            SlgOpcode::CheckMaxInclusive(self.max_model_size_mb as f64),
382            SlgOpcode::CheckMaxInclusive(self.max_parameters as f64),
383        ]
384    }
385}
386
387impl TrainingConfiguration {
388    /// Emits SLG opcodes configuring a training run.
389    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
390        vec![
391            SlgOpcode::CheckMaxInclusive(self.max_epochs as f64),
392            SlgOpcode::CheckMinInclusive(self.batch_size_range.0 as f64),
393            SlgOpcode::CheckMaxInclusive(self.batch_size_range.1 as f64),
394            SlgOpcode::CheckMinInclusive(self.learning_rate_range.0),
395            SlgOpcode::CheckMaxInclusive(self.learning_rate_range.1),
396        ]
397    }
398}
399
400impl SimulationConfiguration {
401    /// Emits SLG opcodes configuring a simulation.
402    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
403        vec![
404            SlgOpcode::CheckMaxInclusive(self.max_time_steps as f64),
405            SlgOpcode::CheckMaxInclusive(self.max_spatial_resolution as f64),
406            SlgOpcode::CheckMaxInclusive(self.max_cfl_number),
407        ]
408    }
409}
410
411impl CryptographicConfiguration {
412    /// Emits SLG opcodes configuring cryptography.
413    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
414        vec![
415            SlgOpcode::CheckMinInclusive(self.min_key_length_bits as f64),
416            SlgOpcode::CheckMaxInclusive(self.max_operation_time_ms as f64),
417        ]
418    }
419}
420
421impl QPUConfiguration {
422    /// Emits SLG opcodes configuring a QPU request.
423    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
424        vec![
425            SlgOpcode::CheckMaxInclusive(self.max_qubits as f64),
426            SlgOpcode::CheckMaxInclusive(self.max_circuit_depth as f64),
427        ]
428    }
429}
430
431// Generic opcode generation for other constraint types
432macro_rules! generate_simple_opcodes {
433    ($struct_name:ident, $field:ident) => {
434        impl $struct_name {
435            /// Emits SLG opcodes configuring a QPU request.
436            pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
437                vec![SlgOpcode::CheckMaxInclusive(self.$field as f64)]
438            }
439        }
440    };
441}
442
443generate_simple_opcodes!(EigenDecomposition, max_iterations);
444generate_simple_opcodes!(SvdConfiguration, max_dimension);
445generate_simple_opcodes!(DeterminantConfiguration, max_dimension);
446generate_simple_opcodes!(SymbolicExpressionConfiguration, max_depth);
447
448impl PolynomialSolveConfiguration {
449    /// Emits SLG opcodes for polynomial solving.
450    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
451        vec![
452            SlgOpcode::CheckMaxInclusive(self.max_degree as f64),
453            SlgOpcode::CheckHasValue(crate::q_hash(&self.method)),
454            SlgOpcode::CheckMaxInclusive(self.max_iterations as f64),
455        ]
456    }
457}
458
459impl SymbolicOperationConfiguration {
460    /// Emits SLG opcodes for symbolic operations.
461    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
462        vec![
463            SlgOpcode::CheckHasValue(crate::q_hash(&self.operation_type)),
464            SlgOpcode::CheckMaxInclusive(self.max_iterations as f64),
465        ]
466    }
467}
468generate_simple_opcodes!(InferenceConfiguration, max_batch_size);
469generate_simple_opcodes!(BoundaryConditions, max_gradient);
470generate_simple_opcodes!(MeshConfiguration, max_elements);
471generate_simple_opcodes!(MoleculeConfiguration, max_atoms);
472generate_simple_opcodes!(ReactionConfiguration, max_reactants);
473generate_simple_opcodes!(QuantumCalculation, max_basis_functions);
474generate_simple_opcodes!(MedicalDataConfiguration, max_patient_records);
475generate_simple_opcodes!(MedicalImagingConfiguration, max_file_size_mb);
476generate_simple_opcodes!(FinancialModelConfiguration, max_time_horizon_days);
477generate_simple_opcodes!(RiskCalculation, max_lookback_days);
478generate_simple_opcodes!(TradingConfiguration, max_daily_trades);
479generate_simple_opcodes!(EngineeringSimulationConfiguration, max_mesh_elements);
480generate_simple_opcodes!(MaterialProperties, max_temperature_kelvin);
481generate_simple_opcodes!(LoadConfiguration, max_load_magnitude);
482generate_simple_opcodes!(StatisticalAnalysisConfiguration, max_sample_size);
483generate_simple_opcodes!(DistributionConfiguration, max_mixture_components);
484generate_simple_opcodes!(SamplingConfiguration, max_iterations);
485generate_simple_opcodes!(KeyManagementConfiguration, max_key_lifetime_days);
486generate_simple_opcodes!(DigitalSignatureConfiguration, max_signature_size_bytes);
487generate_simple_opcodes!(QuantumCircuitConfiguration, max_gates);
488generate_simple_opcodes!(QuantumAnnealingConfiguration, max_annealing_time_us);
489generate_simple_opcodes!(BiomolecularConfiguration, max_atoms);
490impl QuantumBiologyCalculation {
491    /// Emits SLG opcodes for a quantum-biology calculation.
492    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
493        let mut ops = vec![SlgOpcode::CheckMaxInclusive(self.max_quantum_states as f64)];
494        if self.require_solvent_model {
495            ops.push(SlgOpcode::CheckHasValue(crate::q_hash(
496                "solvent_model_required",
497            )));
498        }
499        ops
500    }
501}
502
503// ── SHACL TTL Vocabulary for Specialized Libraries ─────────────────────────────
504
505/// Returns comprehensive SHACL TTL vocabulary for all specialized libraries
506pub fn get_specialized_libs_shacl_ttl() -> &'static str {
507    r#"
508@prefix q42: <https://webizen.org/q42#> .
509@prefix sh: <http://www.w3.org/ns/shacl#> .
510@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
511
512# ── Linear Algebra Constraints ─────────────────────────────────────────────
513
514q42:MatrixConfigurationShape a sh:NodeShape ;
515    sh:property [
516        sh:path q42:maxMatrixSize ;
517        sh:datatype xsd:integer ;
518        sh:minInclusive 1 ;
519        sh:maxInclusive 1000000 ;
520        sh:message "Matrix size must be between 1 and 1,000,000" ;
521    ] ;
522    sh:property [
523        sh:path q42:maxZoneCapacity ;
524        sh:datatype xsd:integer ;
525        sh:minInclusive 1024 ;
526        sh:maxInclusive 1099511627776 ;
527        sh:message "Zone capacity must be between 1KB and 1TB" ;
528    ] .
529
530q42:MatrixOperationShape a sh:NodeShape ;
531    sh:property [
532        sh:path q42:operationType ;
533        sh:in ("multiply" "add" "subtract" "invert" "transpose" "decompose" "determinant" "eigen" "svd") ;
534        sh:message "Operation type must be a valid matrix operation" ;
535    ] ;
536    sh:property [
537        sh:path q42:maxConditionNumber ;
538        sh:datatype xsd:float ;
539        sh:minInclusive 1.0 ;
540        sh:maxInclusive 1e15 ;
541        sh:message "Condition number must be reasonable for numerical stability" ;
542    ] .
543
544q42:PolynomialSolveShape a sh:NodeShape ;
545    sh:property [
546        sh:path q42:maxDegree ;
547        sh:datatype xsd:integer ;
548        sh:minInclusive 1 ;
549        sh:maxInclusive 256 ;
550        sh:message "Polynomial degree must be between 1 and 256" ;
551    ] ;
552    sh:property [
553        sh:path q42:method ;
554        sh:in ("quadratic_closed_form" "durand_kerner" "companion") ;
555        sh:message "Root-finding method must be supported" ;
556    ] .
557
558q42:SingularValueDecompositionShape a sh:NodeShape ;
559    sh:property [
560        sh:path q42:maxDimension ;
561        sh:datatype xsd:integer ;
562        sh:minInclusive 1 ;
563        sh:maxInclusive 100000 ;
564        sh:message "SVD dimension must be between 1 and 100,000" ;
565    ] ;
566    sh:property [
567        sh:path q42:method ;
568        sh:in ("ata_eigen" "golub_reinsch") ;
569        sh:message "SVD method must be supported" ;
570    ] .
571
572q42:DeterminantShape a sh:NodeShape ;
573    sh:property [
574        sh:path q42:maxDimension ;
575        sh:datatype xsd:integer ;
576        sh:minInclusive 1 ;
577        sh:maxInclusive 100000 ;
578        sh:message "Determinant dimension must be between 1 and 100,000" ;
579    ] ;
580    sh:property [
581        sh:path q42:method ;
582        sh:in ("lu" "cofactor") ;
583        sh:message "Determinant method must be supported" ;
584    ] .
585
586q42:SymbolicExpressionShape a sh:NodeShape ;
587    sh:property [
588        sh:path q42:maxDepth ;
589        sh:datatype xsd:integer ;
590        sh:minInclusive 1 ;
591        sh:maxInclusive 1024 ;
592        sh:message "Symbolic expression depth must be between 1 and 1024" ;
593    ] ;
594    sh:property [
595        sh:path q42:allowedOperators ;
596        sh:in ("add" "sub" "mul" "div" "pow" "neg" "sqrt") ;
597        sh:message "Operator must be a supported CAS operator" ;
598    ] .
599
600q42:SymbolicOperationShape a sh:NodeShape ;
601    sh:property [
602        sh:path q42:operationType ;
603        sh:in ("differentiate" "simplify" "expand" "evaluate" "solve" "factor") ;
604        sh:message "Symbolic operation must be supported" ;
605    ] .
606
607# ── Machine Learning Constraints ─────────────────────────────────────────────
608
609q42:ModelConfigurationShape a sh:NodeShape ;
610    sh:property [
611        sh:path q42:maxModelSizeMb ;
612        sh:datatype xsd:integer ;
613        sh:minInclusive 1 ;
614        sh:maxInclusive 100000 ;
615        sh:message "Model size must be between 1MB and 100GB" ;
616    ] ;
617    sh:property [
618        sh:path q42:allowedModelTypes ;
619        sh:in ("neural_network" "decision_tree" "svm" "random_forest" "knn") ;
620        sh:message "Model type must be supported" ;
621    ] .
622
623q42:TrainingConfigurationShape a sh:NodeShape ;
624    sh:property [
625        sh:path q42:maxEpochs ;
626        sh:datatype xsd:integer ;
627        sh:minInclusive 1 ;
628        sh:maxInclusive 10000 ;
629        sh:message "Training epochs must be between 1 and 10,000" ;
630    ] ;
631    sh:property [
632        sh:path q42:learningRateRange ;
633        sh:datatype xsd:float ;
634        sh:minInclusive 0.0 ;
635        sh:maxInclusive 1.0 ;
636        sh:message "Learning rate must be between 0 and 1" ;
637    ] .
638
639# ── Physics Simulation Constraints ───────────────────────────────────────────
640
641q42:SimulationConfigurationShape a sh:NodeShape ;
642    sh:property [
643        sh:path q42:maxTimeSteps ;
644        sh:datatype xsd:integer ;
645        sh:minInclusive 1 ;
646        sh:maxInclusive 1000000000 ;
647        sh:message "Time steps must be between 1 and 1 billion" ;
648    ] ;
649    sh:property [
650        sh:path q42:maxCflNumber ;
651        sh:datatype xsd:float ;
652        sh:minInclusive 0.0 ;
653        sh:maxInclusive 1.0 ;
654        sh:message "CFL number must be ≤ 1.0 for stability" ;
655    ] .
656
657# ── Chemistry Modeling Constraints ───────────────────────────────────────────
658
659q42:MoleculeConfigurationShape a sh:NodeShape ;
660    sh:property [
661        sh:path q42:maxAtoms ;
662        sh:datatype xsd:integer ;
663        sh:minInclusive 1 ;
664        sh:maxInclusive 10000 ;
665        sh:message "Molecule must have between 1 and 10,000 atoms" ;
666    ] ;
667    sh:property [
668        sh:path q42:allowedElementTypes ;
669        sh:message "Element types must be valid periodic table symbols" ;
670    ] .
671
672# ── Medical Computing Constraints ─────────────────────────────────────────────
673
674q42:MedicalDataConfigurationShape a sh:NodeShape ;
675    sh:property [
676        sh:path q42:requireHipaaCompliance ;
677        sh:datatype xsd:boolean ;
678        sh:message "HIPAA compliance flag must be boolean" ;
679    ] ;
680    sh:property [
681        sh:path q42:allowedDataTypes ;
682        sh:in ("fhir" "dicom" "hl7" "cda") ;
683        sh:message "Data type must be a supported medical format" ;
684    ] .
685
686# ── Financial Modeling Constraints ───────────────────────────────────────────
687
688q42:FinancialModelConfigurationShape a sh:NodeShape ;
689    sh:property [
690        sh:path q42:maxTimeHorizonDays ;
691        sh:datatype xsd:integer ;
692        sh:minInclusive 1 ;
693        sh:maxInclusive 36500 ;
694        sh:message "Time horizon must be between 1 day and 100 years" ;
695    ] ;
696    sh:property [
697        sh:path q42:maxLeverageRatio ;
698        sh:datatype xsd:float ;
699        sh:minInclusive 0.0 ;
700        sh:maxInclusive 100.0 ;
701        sh:message "Leverage ratio must be between 0 and 100" ;
702    ] .
703
704# ── Cryptographic Constraints ─────────────────────────────────────────────────
705
706q42:CryptographicConfigurationShape a sh:NodeShape ;
707    sh:property [
708        sh:path q42:minKeyLengthBits ;
709        sh:datatype xsd:integer ;
710        sh:minInclusive 128 ;
711        sh:maxInclusive 4096 ;
712        sh:message "Key length must be between 128 and 4096 bits" ;
713    ] ;
714    sh:property [
715        sh:path q42:allowedAlgorithms ;
716        sh:in ("aes" "rsa" "ecc" "sha256" "sha512" "ed25519") ;
717        sh:message "Algorithm must be supported" ;
718    ] .
719
720# ── QPU Bridge Constraints ─────────────────────────────────────────────────────
721
722q42:QPUConfigurationShape a sh:NodeShape ;
723    sh:property [
724        sh:path q42:maxQubits ;
725        sh:datatype xsd:integer ;
726        sh:minInclusive 1 ;
727        sh:maxInclusive 10000 ;
728        sh:message "QPU must support between 1 and 10,000 qubits" ;
729    ] ;
730    sh:property [
731        sh:path q42:allowedQpuTypes ;
732        sh:in ("dwave" "ibm" "google" "rigetti" "ionq") ;
733        sh:message "QPU type must be supported" ;
734    ] .
735"#
736}
737
738#[cfg(test)]
739mod tests {
740    use super::*;
741
742    #[test]
743    fn algebra_and_cas_shapes_present() {
744        // Every new algebra/CAS capability must have a SHACL NodeShape in the Rust
745        // vocabulary (full coverage — mirrors shapes/specialized-libraries.shacl.ttl).
746        let ttl = get_specialized_libs_shacl_ttl();
747        for shape in [
748            "q42:PolynomialSolveShape",
749            "q42:SingularValueDecompositionShape",
750            "q42:DeterminantShape",
751            "q42:SymbolicExpressionShape",
752            "q42:SymbolicOperationShape",
753        ] {
754            assert!(ttl.contains(shape), "missing SHACL shape: {shape}");
755        }
756    }
757
758    #[test]
759    fn algebra_and_cas_configs_generate_opcodes() {
760        assert!(!PolynomialSolveConfiguration {
761            max_degree: 8,
762            method: "durand_kerner".to_string(),
763            max_iterations: 500,
764        }
765        .to_opcodes()
766        .is_empty());
767        assert!(!SvdConfiguration {
768            max_dimension: 256,
769            compute_vectors: true,
770            method: "ata_eigen".to_string(),
771        }
772        .to_opcodes()
773        .is_empty());
774        assert!(!DeterminantConfiguration {
775            max_dimension: 256,
776            method: "lu".to_string(),
777        }
778        .to_opcodes()
779        .is_empty());
780        assert!(!SymbolicExpressionConfiguration {
781            max_depth: 32,
782            max_variables: 8,
783            allowed_operators: vec!["add".to_string(), "mul".to_string()],
784        }
785        .to_opcodes()
786        .is_empty());
787        assert!(!SymbolicOperationConfiguration {
788            operation_type: "differentiate".to_string(),
789            max_iterations: 16,
790        }
791        .to_opcodes()
792        .is_empty());
793    }
794}