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    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
359        vec![
360            SlgOpcode::CheckMaxInclusive(self.max_matrix_size as f64),
361            SlgOpcode::CheckMaxInclusive(self.max_zone_capacity as f64),
362        ]
363    }
364}
365
366impl MatrixOperation {
367    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
368        vec![
369            SlgOpcode::CheckMaxInclusive(self.max_condition_number),
370            SlgOpcode::CheckHasValue(crate::q_hash(&self.precision_mode)),
371        ]
372    }
373}
374
375impl ModelConfiguration {
376    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
377        vec![
378            SlgOpcode::CheckMaxInclusive(self.max_model_size_mb as f64),
379            SlgOpcode::CheckMaxInclusive(self.max_parameters as f64),
380        ]
381    }
382}
383
384impl TrainingConfiguration {
385    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
386        vec![
387            SlgOpcode::CheckMaxInclusive(self.max_epochs as f64),
388            SlgOpcode::CheckMinInclusive(self.batch_size_range.0 as f64),
389            SlgOpcode::CheckMaxInclusive(self.batch_size_range.1 as f64),
390            SlgOpcode::CheckMinInclusive(self.learning_rate_range.0),
391            SlgOpcode::CheckMaxInclusive(self.learning_rate_range.1),
392        ]
393    }
394}
395
396impl SimulationConfiguration {
397    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
398        vec![
399            SlgOpcode::CheckMaxInclusive(self.max_time_steps as f64),
400            SlgOpcode::CheckMaxInclusive(self.max_spatial_resolution as f64),
401            SlgOpcode::CheckMaxInclusive(self.max_cfl_number),
402        ]
403    }
404}
405
406impl CryptographicConfiguration {
407    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
408        vec![
409            SlgOpcode::CheckMinInclusive(self.min_key_length_bits as f64),
410            SlgOpcode::CheckMaxInclusive(self.max_operation_time_ms as f64),
411        ]
412    }
413}
414
415impl QPUConfiguration {
416    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
417        vec![
418            SlgOpcode::CheckMaxInclusive(self.max_qubits as f64),
419            SlgOpcode::CheckMaxInclusive(self.max_circuit_depth as f64),
420        ]
421    }
422}
423
424// Generic opcode generation for other constraint types
425macro_rules! generate_simple_opcodes {
426    ($struct_name:ident, $field:ident) => {
427        impl $struct_name {
428            pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
429                vec![SlgOpcode::CheckMaxInclusive(self.$field as f64)]
430            }
431        }
432    };
433}
434
435generate_simple_opcodes!(EigenDecomposition, max_iterations);
436generate_simple_opcodes!(SvdConfiguration, max_dimension);
437generate_simple_opcodes!(DeterminantConfiguration, max_dimension);
438generate_simple_opcodes!(SymbolicExpressionConfiguration, max_depth);
439
440impl PolynomialSolveConfiguration {
441    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
442        vec![
443            SlgOpcode::CheckMaxInclusive(self.max_degree as f64),
444            SlgOpcode::CheckHasValue(crate::q_hash(&self.method)),
445            SlgOpcode::CheckMaxInclusive(self.max_iterations as f64),
446        ]
447    }
448}
449
450impl SymbolicOperationConfiguration {
451    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
452        vec![
453            SlgOpcode::CheckHasValue(crate::q_hash(&self.operation_type)),
454            SlgOpcode::CheckMaxInclusive(self.max_iterations as f64),
455        ]
456    }
457}
458generate_simple_opcodes!(InferenceConfiguration, max_batch_size);
459generate_simple_opcodes!(BoundaryConditions, max_gradient);
460generate_simple_opcodes!(MeshConfiguration, max_elements);
461generate_simple_opcodes!(MoleculeConfiguration, max_atoms);
462generate_simple_opcodes!(ReactionConfiguration, max_reactants);
463generate_simple_opcodes!(QuantumCalculation, max_basis_functions);
464generate_simple_opcodes!(MedicalDataConfiguration, max_patient_records);
465generate_simple_opcodes!(MedicalImagingConfiguration, max_file_size_mb);
466generate_simple_opcodes!(FinancialModelConfiguration, max_time_horizon_days);
467generate_simple_opcodes!(RiskCalculation, max_lookback_days);
468generate_simple_opcodes!(TradingConfiguration, max_daily_trades);
469generate_simple_opcodes!(EngineeringSimulationConfiguration, max_mesh_elements);
470generate_simple_opcodes!(MaterialProperties, max_temperature_kelvin);
471generate_simple_opcodes!(LoadConfiguration, max_load_magnitude);
472generate_simple_opcodes!(StatisticalAnalysisConfiguration, max_sample_size);
473generate_simple_opcodes!(DistributionConfiguration, max_mixture_components);
474generate_simple_opcodes!(SamplingConfiguration, max_iterations);
475generate_simple_opcodes!(KeyManagementConfiguration, max_key_lifetime_days);
476generate_simple_opcodes!(DigitalSignatureConfiguration, max_signature_size_bytes);
477generate_simple_opcodes!(QuantumCircuitConfiguration, max_gates);
478generate_simple_opcodes!(QuantumAnnealingConfiguration, max_annealing_time_us);
479generate_simple_opcodes!(BiomolecularConfiguration, max_atoms);
480impl QuantumBiologyCalculation {
481    pub fn to_opcodes(&self) -> Vec<SlgOpcode> {
482        let mut ops = vec![SlgOpcode::CheckMaxInclusive(self.max_quantum_states as f64)];
483        if self.require_solvent_model {
484            ops.push(SlgOpcode::CheckHasValue(crate::q_hash(
485                "solvent_model_required",
486            )));
487        }
488        ops
489    }
490}
491
492// ── SHACL TTL Vocabulary for Specialized Libraries ─────────────────────────────
493
494/// Returns comprehensive SHACL TTL vocabulary for all specialized libraries
495pub fn get_specialized_libs_shacl_ttl() -> &'static str {
496    r#"
497@prefix q42: <https://webizen.org/q42#> .
498@prefix sh: <http://www.w3.org/ns/shacl#> .
499@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
500
501# ── Linear Algebra Constraints ─────────────────────────────────────────────
502
503q42:MatrixConfigurationShape a sh:NodeShape ;
504    sh:property [
505        sh:path q42:maxMatrixSize ;
506        sh:datatype xsd:integer ;
507        sh:minInclusive 1 ;
508        sh:maxInclusive 1000000 ;
509        sh:message "Matrix size must be between 1 and 1,000,000" ;
510    ] ;
511    sh:property [
512        sh:path q42:maxZoneCapacity ;
513        sh:datatype xsd:integer ;
514        sh:minInclusive 1024 ;
515        sh:maxInclusive 1099511627776 ;
516        sh:message "Zone capacity must be between 1KB and 1TB" ;
517    ] .
518
519q42:MatrixOperationShape a sh:NodeShape ;
520    sh:property [
521        sh:path q42:operationType ;
522        sh:in ("multiply" "add" "subtract" "invert" "transpose" "decompose" "determinant" "eigen" "svd") ;
523        sh:message "Operation type must be a valid matrix operation" ;
524    ] ;
525    sh:property [
526        sh:path q42:maxConditionNumber ;
527        sh:datatype xsd:float ;
528        sh:minInclusive 1.0 ;
529        sh:maxInclusive 1e15 ;
530        sh:message "Condition number must be reasonable for numerical stability" ;
531    ] .
532
533q42:PolynomialSolveShape a sh:NodeShape ;
534    sh:property [
535        sh:path q42:maxDegree ;
536        sh:datatype xsd:integer ;
537        sh:minInclusive 1 ;
538        sh:maxInclusive 256 ;
539        sh:message "Polynomial degree must be between 1 and 256" ;
540    ] ;
541    sh:property [
542        sh:path q42:method ;
543        sh:in ("quadratic_closed_form" "durand_kerner" "companion") ;
544        sh:message "Root-finding method must be supported" ;
545    ] .
546
547q42:SingularValueDecompositionShape a sh:NodeShape ;
548    sh:property [
549        sh:path q42:maxDimension ;
550        sh:datatype xsd:integer ;
551        sh:minInclusive 1 ;
552        sh:maxInclusive 100000 ;
553        sh:message "SVD dimension must be between 1 and 100,000" ;
554    ] ;
555    sh:property [
556        sh:path q42:method ;
557        sh:in ("ata_eigen" "golub_reinsch") ;
558        sh:message "SVD method must be supported" ;
559    ] .
560
561q42:DeterminantShape a sh:NodeShape ;
562    sh:property [
563        sh:path q42:maxDimension ;
564        sh:datatype xsd:integer ;
565        sh:minInclusive 1 ;
566        sh:maxInclusive 100000 ;
567        sh:message "Determinant dimension must be between 1 and 100,000" ;
568    ] ;
569    sh:property [
570        sh:path q42:method ;
571        sh:in ("lu" "cofactor") ;
572        sh:message "Determinant method must be supported" ;
573    ] .
574
575q42:SymbolicExpressionShape a sh:NodeShape ;
576    sh:property [
577        sh:path q42:maxDepth ;
578        sh:datatype xsd:integer ;
579        sh:minInclusive 1 ;
580        sh:maxInclusive 1024 ;
581        sh:message "Symbolic expression depth must be between 1 and 1024" ;
582    ] ;
583    sh:property [
584        sh:path q42:allowedOperators ;
585        sh:in ("add" "sub" "mul" "div" "pow" "neg" "sqrt") ;
586        sh:message "Operator must be a supported CAS operator" ;
587    ] .
588
589q42:SymbolicOperationShape a sh:NodeShape ;
590    sh:property [
591        sh:path q42:operationType ;
592        sh:in ("differentiate" "simplify" "expand" "evaluate" "solve" "factor") ;
593        sh:message "Symbolic operation must be supported" ;
594    ] .
595
596# ── Machine Learning Constraints ─────────────────────────────────────────────
597
598q42:ModelConfigurationShape a sh:NodeShape ;
599    sh:property [
600        sh:path q42:maxModelSizeMb ;
601        sh:datatype xsd:integer ;
602        sh:minInclusive 1 ;
603        sh:maxInclusive 100000 ;
604        sh:message "Model size must be between 1MB and 100GB" ;
605    ] ;
606    sh:property [
607        sh:path q42:allowedModelTypes ;
608        sh:in ("neural_network" "decision_tree" "svm" "random_forest" "knn") ;
609        sh:message "Model type must be supported" ;
610    ] .
611
612q42:TrainingConfigurationShape a sh:NodeShape ;
613    sh:property [
614        sh:path q42:maxEpochs ;
615        sh:datatype xsd:integer ;
616        sh:minInclusive 1 ;
617        sh:maxInclusive 10000 ;
618        sh:message "Training epochs must be between 1 and 10,000" ;
619    ] ;
620    sh:property [
621        sh:path q42:learningRateRange ;
622        sh:datatype xsd:float ;
623        sh:minInclusive 0.0 ;
624        sh:maxInclusive 1.0 ;
625        sh:message "Learning rate must be between 0 and 1" ;
626    ] .
627
628# ── Physics Simulation Constraints ───────────────────────────────────────────
629
630q42:SimulationConfigurationShape a sh:NodeShape ;
631    sh:property [
632        sh:path q42:maxTimeSteps ;
633        sh:datatype xsd:integer ;
634        sh:minInclusive 1 ;
635        sh:maxInclusive 1000000000 ;
636        sh:message "Time steps must be between 1 and 1 billion" ;
637    ] ;
638    sh:property [
639        sh:path q42:maxCflNumber ;
640        sh:datatype xsd:float ;
641        sh:minInclusive 0.0 ;
642        sh:maxInclusive 1.0 ;
643        sh:message "CFL number must be ≤ 1.0 for stability" ;
644    ] .
645
646# ── Chemistry Modeling Constraints ───────────────────────────────────────────
647
648q42:MoleculeConfigurationShape a sh:NodeShape ;
649    sh:property [
650        sh:path q42:maxAtoms ;
651        sh:datatype xsd:integer ;
652        sh:minInclusive 1 ;
653        sh:maxInclusive 10000 ;
654        sh:message "Molecule must have between 1 and 10,000 atoms" ;
655    ] ;
656    sh:property [
657        sh:path q42:allowedElementTypes ;
658        sh:message "Element types must be valid periodic table symbols" ;
659    ] .
660
661# ── Medical Computing Constraints ─────────────────────────────────────────────
662
663q42:MedicalDataConfigurationShape a sh:NodeShape ;
664    sh:property [
665        sh:path q42:requireHipaaCompliance ;
666        sh:datatype xsd:boolean ;
667        sh:message "HIPAA compliance flag must be boolean" ;
668    ] ;
669    sh:property [
670        sh:path q42:allowedDataTypes ;
671        sh:in ("fhir" "dicom" "hl7" "cda") ;
672        sh:message "Data type must be a supported medical format" ;
673    ] .
674
675# ── Financial Modeling Constraints ───────────────────────────────────────────
676
677q42:FinancialModelConfigurationShape a sh:NodeShape ;
678    sh:property [
679        sh:path q42:maxTimeHorizonDays ;
680        sh:datatype xsd:integer ;
681        sh:minInclusive 1 ;
682        sh:maxInclusive 36500 ;
683        sh:message "Time horizon must be between 1 day and 100 years" ;
684    ] ;
685    sh:property [
686        sh:path q42:maxLeverageRatio ;
687        sh:datatype xsd:float ;
688        sh:minInclusive 0.0 ;
689        sh:maxInclusive 100.0 ;
690        sh:message "Leverage ratio must be between 0 and 100" ;
691    ] .
692
693# ── Cryptographic Constraints ─────────────────────────────────────────────────
694
695q42:CryptographicConfigurationShape a sh:NodeShape ;
696    sh:property [
697        sh:path q42:minKeyLengthBits ;
698        sh:datatype xsd:integer ;
699        sh:minInclusive 128 ;
700        sh:maxInclusive 4096 ;
701        sh:message "Key length must be between 128 and 4096 bits" ;
702    ] ;
703    sh:property [
704        sh:path q42:allowedAlgorithms ;
705        sh:in ("aes" "rsa" "ecc" "sha256" "sha512" "ed25519") ;
706        sh:message "Algorithm must be supported" ;
707    ] .
708
709# ── QPU Bridge Constraints ─────────────────────────────────────────────────────
710
711q42:QPUConfigurationShape a sh:NodeShape ;
712    sh:property [
713        sh:path q42:maxQubits ;
714        sh:datatype xsd:integer ;
715        sh:minInclusive 1 ;
716        sh:maxInclusive 10000 ;
717        sh:message "QPU must support between 1 and 10,000 qubits" ;
718    ] ;
719    sh:property [
720        sh:path q42:allowedQpuTypes ;
721        sh:in ("dwave" "ibm" "google" "rigetti" "ionq") ;
722        sh:message "QPU type must be supported" ;
723    ] .
724"#
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730
731    #[test]
732    fn algebra_and_cas_shapes_present() {
733        // Every new algebra/CAS capability must have a SHACL NodeShape in the Rust
734        // vocabulary (full coverage — mirrors shapes/specialized-libraries.shacl.ttl).
735        let ttl = get_specialized_libs_shacl_ttl();
736        for shape in [
737            "q42:PolynomialSolveShape",
738            "q42:SingularValueDecompositionShape",
739            "q42:DeterminantShape",
740            "q42:SymbolicExpressionShape",
741            "q42:SymbolicOperationShape",
742        ] {
743            assert!(ttl.contains(shape), "missing SHACL shape: {shape}");
744        }
745    }
746
747    #[test]
748    fn algebra_and_cas_configs_generate_opcodes() {
749        assert!(!PolynomialSolveConfiguration {
750            max_degree: 8,
751            method: "durand_kerner".to_string(),
752            max_iterations: 500,
753        }
754        .to_opcodes()
755        .is_empty());
756        assert!(!SvdConfiguration {
757            max_dimension: 256,
758            compute_vectors: true,
759            method: "ata_eigen".to_string(),
760        }
761        .to_opcodes()
762        .is_empty());
763        assert!(!DeterminantConfiguration {
764            max_dimension: 256,
765            method: "lu".to_string(),
766        }
767        .to_opcodes()
768        .is_empty());
769        assert!(!SymbolicExpressionConfiguration {
770            max_depth: 32,
771            max_variables: 8,
772            allowed_operators: vec!["add".to_string(), "mul".to_string()],
773        }
774        .to_opcodes()
775        .is_empty());
776        assert!(!SymbolicOperationConfiguration {
777            operation_type: "differentiate".to_string(),
778            max_iterations: 16,
779        }
780        .to_opcodes()
781        .is_empty());
782    }
783}