1use anyhow::Result;
7
8use crate::{Rule, RuleAtom, RuleEngine, Term};
9
10pub struct GettingStartedGuide;
58
59impl GettingStartedGuide {
60 pub fn create_basic_engine() -> RuleEngine {
62 RuleEngine::new()
63 }
64
65 pub fn basic_example() -> Result<Vec<RuleAtom>> {
67 let mut engine = RuleEngine::new();
68
69 let mortality_rule = Rule {
71 name: "mortality_rule".to_string(),
72 body: vec![RuleAtom::Triple {
73 subject: Term::Variable("X".to_string()),
74 predicate: Term::Constant("type".to_string()),
75 object: Term::Constant("Person".to_string()),
76 }],
77 head: vec![RuleAtom::Triple {
78 subject: Term::Variable("X".to_string()),
79 predicate: Term::Constant("type".to_string()),
80 object: Term::Constant("Mortal".to_string()),
81 }],
82 };
83
84 engine.add_rule(mortality_rule);
85
86 let facts = vec![
88 RuleAtom::Triple {
89 subject: Term::Constant("socrates".to_string()),
90 predicate: Term::Constant("type".to_string()),
91 object: Term::Constant("Person".to_string()),
92 },
93 RuleAtom::Triple {
94 subject: Term::Constant("plato".to_string()),
95 predicate: Term::Constant("type".to_string()),
96 object: Term::Constant("Person".to_string()),
97 },
98 ];
99
100 engine.forward_chain(&facts)
101 }
102
103 pub fn backward_chaining_example() -> Result<bool> {
105 let mut engine = RuleEngine::new();
106
107 let teaching_rule = Rule {
109 name: "teaching_rule".to_string(),
110 body: vec![
111 RuleAtom::Triple {
112 subject: Term::Variable("X".to_string()),
113 predicate: Term::Constant("teaches".to_string()),
114 object: Term::Variable("Y".to_string()),
115 },
116 RuleAtom::Triple {
117 subject: Term::Variable("Y".to_string()),
118 predicate: Term::Constant("type".to_string()),
119 object: Term::Constant("Student".to_string()),
120 },
121 ],
122 head: vec![RuleAtom::Triple {
123 subject: Term::Variable("X".to_string()),
124 predicate: Term::Constant("type".to_string()),
125 object: Term::Constant("Teacher".to_string()),
126 }],
127 };
128
129 engine.add_rule(teaching_rule);
130
131 engine.add_fact(RuleAtom::Triple {
133 subject: Term::Constant("aristotle".to_string()),
134 predicate: Term::Constant("teaches".to_string()),
135 object: Term::Constant("alexander".to_string()),
136 });
137
138 engine.add_fact(RuleAtom::Triple {
139 subject: Term::Constant("alexander".to_string()),
140 predicate: Term::Constant("type".to_string()),
141 object: Term::Constant("Student".to_string()),
142 });
143
144 let goal = RuleAtom::Triple {
146 subject: Term::Constant("aristotle".to_string()),
147 predicate: Term::Constant("type".to_string()),
148 object: Term::Constant("Teacher".to_string()),
149 };
150
151 engine.backward_chain(&goal)
152 }
153
154 pub fn family_relationships_example() -> Result<Vec<RuleAtom>> {
156 let mut engine = RuleEngine::new();
157
158 let grandparent_rule = Rule {
160 name: "grandparent_rule".to_string(),
161 body: vec![
162 RuleAtom::Triple {
163 subject: Term::Variable("X".to_string()),
164 predicate: Term::Constant("parent".to_string()),
165 object: Term::Variable("Y".to_string()),
166 },
167 RuleAtom::Triple {
168 subject: Term::Variable("Y".to_string()),
169 predicate: Term::Constant("parent".to_string()),
170 object: Term::Variable("Z".to_string()),
171 },
172 ],
173 head: vec![RuleAtom::Triple {
174 subject: Term::Variable("X".to_string()),
175 predicate: Term::Constant("grandparent".to_string()),
176 object: Term::Variable("Z".to_string()),
177 }],
178 };
179
180 let child_rule = Rule {
182 name: "child_rule".to_string(),
183 body: vec![RuleAtom::Triple {
184 subject: Term::Variable("X".to_string()),
185 predicate: Term::Constant("parent".to_string()),
186 object: Term::Variable("Y".to_string()),
187 }],
188 head: vec![RuleAtom::Triple {
189 subject: Term::Variable("Y".to_string()),
190 predicate: Term::Constant("child".to_string()),
191 object: Term::Variable("X".to_string()),
192 }],
193 };
194
195 engine.add_rule(grandparent_rule);
196 engine.add_rule(child_rule);
197
198 let facts = vec![
200 RuleAtom::Triple {
201 subject: Term::Constant("alice".to_string()),
202 predicate: Term::Constant("parent".to_string()),
203 object: Term::Constant("bob".to_string()),
204 },
205 RuleAtom::Triple {
206 subject: Term::Constant("bob".to_string()),
207 predicate: Term::Constant("parent".to_string()),
208 object: Term::Constant("charlie".to_string()),
209 },
210 RuleAtom::Triple {
211 subject: Term::Constant("bob".to_string()),
212 predicate: Term::Constant("parent".to_string()),
213 object: Term::Constant("diana".to_string()),
214 },
215 ];
216
217 engine.forward_chain(&facts)
218 }
219
220 pub fn ontology_reasoning_example() -> Result<Vec<RuleAtom>> {
222 let mut engine = RuleEngine::new();
223
224 let subclass_rule = Rule {
226 name: "subclass_inheritance".to_string(),
227 body: vec![
228 RuleAtom::Triple {
229 subject: Term::Variable("X".to_string()),
230 predicate: Term::Constant("subClassOf".to_string()),
231 object: Term::Variable("Y".to_string()),
232 },
233 RuleAtom::Triple {
234 subject: Term::Variable("Z".to_string()),
235 predicate: Term::Constant("type".to_string()),
236 object: Term::Variable("X".to_string()),
237 },
238 ],
239 head: vec![RuleAtom::Triple {
240 subject: Term::Variable("Z".to_string()),
241 predicate: Term::Constant("type".to_string()),
242 object: Term::Variable("Y".to_string()),
243 }],
244 };
245
246 let subproperty_rule = Rule {
248 name: "subproperty_inheritance".to_string(),
249 body: vec![
250 RuleAtom::Triple {
251 subject: Term::Variable("P".to_string()),
252 predicate: Term::Constant("subPropertyOf".to_string()),
253 object: Term::Variable("Q".to_string()),
254 },
255 RuleAtom::Triple {
256 subject: Term::Variable("X".to_string()),
257 predicate: Term::Variable("P".to_string()),
258 object: Term::Variable("Y".to_string()),
259 },
260 ],
261 head: vec![RuleAtom::Triple {
262 subject: Term::Variable("X".to_string()),
263 predicate: Term::Variable("Q".to_string()),
264 object: Term::Variable("Y".to_string()),
265 }],
266 };
267
268 engine.add_rule(subclass_rule);
269 engine.add_rule(subproperty_rule);
270
271 let facts = vec![
273 RuleAtom::Triple {
275 subject: Term::Constant("Dog".to_string()),
276 predicate: Term::Constant("subClassOf".to_string()),
277 object: Term::Constant("Mammal".to_string()),
278 },
279 RuleAtom::Triple {
280 subject: Term::Constant("Mammal".to_string()),
281 predicate: Term::Constant("subClassOf".to_string()),
282 object: Term::Constant("Animal".to_string()),
283 },
284 RuleAtom::Triple {
286 subject: Term::Constant("owns".to_string()),
287 predicate: Term::Constant("subPropertyOf".to_string()),
288 object: Term::Constant("related".to_string()),
289 },
290 RuleAtom::Triple {
292 subject: Term::Constant("fido".to_string()),
293 predicate: Term::Constant("type".to_string()),
294 object: Term::Constant("Dog".to_string()),
295 },
296 RuleAtom::Triple {
297 subject: Term::Constant("john".to_string()),
298 predicate: Term::Constant("owns".to_string()),
299 object: Term::Constant("fido".to_string()),
300 },
301 ];
302
303 engine.forward_chain(&facts)
304 }
305}
306
307pub struct RuleAuthoringBestPractices;
311
312impl RuleAuthoringBestPractices {
313 pub fn variable_naming_guidelines() -> Vec<&'static str> {
315 vec![
316 "Use meaningful variable names (e.g., 'Person' instead of 'X')",
317 "Use consistent naming conventions across rules",
318 "Use uppercase for variables to distinguish from constants",
319 "Use descriptive names for complex patterns",
320 "Avoid single-letter variables except for simple cases",
321 "Use domain-specific prefixes (e.g., 'pers_' for person variables)",
322 ]
323 }
324
325 pub fn rule_structure_guidelines() -> Vec<&'static str> {
327 vec![
328 "Order atoms from most specific to least specific",
329 "Place constant-heavy atoms first for efficient filtering",
330 "Group related atoms together for readability",
331 "Use built-in predicates judiciously for validation",
332 "Keep rule bodies concise and focused",
333 "Avoid overly complex rules - split into multiple simpler rules",
334 ]
335 }
336
337 pub fn performance_tips() -> Vec<&'static str> {
339 vec![
340 "Place most selective atoms first in rule bodies",
341 "Use constants instead of variables when possible",
342 "Avoid rules that generate infinite loops",
343 "Use indexing hints for frequently used patterns",
344 "Consider rule ordering for optimization",
345 "Profile rule execution to identify bottlenecks",
346 "Use caching for expensive computations",
347 "Minimize variable scope and reuse",
348 ]
349 }
350
351 pub fn common_pitfalls() -> Vec<(&'static str, &'static str)> {
353 vec![
354 ("Infinite recursion", "Always ensure termination conditions"),
355 (
356 "Variable scope confusion",
357 "Use clear naming and scope management",
358 ),
359 (
360 "Performance bottlenecks",
361 "Profile and optimize critical rules",
362 ),
363 ("Rule conflicts", "Test rule interactions thoroughly"),
364 (
365 "Over-generalization",
366 "Be specific about rule applicability",
367 ),
368 ("Under-specification", "Include necessary constraints"),
369 ("Complex debugging", "Use rule tracing and debugging tools"),
370 ("Memory issues", "Monitor memory usage with large rule sets"),
371 ]
372 }
373
374 pub fn well_structured_rule_example() -> Rule {
376 Rule {
377 name: "employee_manager_hierarchy".to_string(),
378 body: vec![
379 RuleAtom::Triple {
381 subject: Term::Variable("Employee".to_string()),
382 predicate: Term::Constant("type".to_string()),
383 object: Term::Constant("Person".to_string()),
384 },
385 RuleAtom::Triple {
387 subject: Term::Variable("Employee".to_string()),
388 predicate: Term::Constant("worksFor".to_string()),
389 object: Term::Variable("Manager".to_string()),
390 },
391 RuleAtom::Triple {
393 subject: Term::Variable("Manager".to_string()),
394 predicate: Term::Constant("type".to_string()),
395 object: Term::Constant("Manager".to_string()),
396 },
397 ],
398 head: vec![RuleAtom::Triple {
399 subject: Term::Variable("Employee".to_string()),
400 predicate: Term::Constant("hasManager".to_string()),
401 object: Term::Variable("Manager".to_string()),
402 }],
403 }
404 }
405
406 pub fn validate_rule_example() -> Result<bool> {
408 let rule = Self::well_structured_rule_example();
409
410 if rule.name.is_empty() {
412 return Ok(false);
413 }
414
415 if rule.body.is_empty() || rule.head.is_empty() {
416 return Ok(false);
417 }
418
419 let mut body_vars = std::collections::HashSet::new();
421 let mut head_vars = std::collections::HashSet::new();
422
423 for atom in &rule.body {
424 Self::collect_variables(atom, &mut body_vars);
425 }
426
427 for atom in &rule.head {
428 Self::collect_variables(atom, &mut head_vars);
429 }
430
431 for var in &head_vars {
433 if !body_vars.contains(var) {
434 println!("Warning: Variable {var} in head but not in body");
435 return Ok(false);
436 }
437 }
438
439 Ok(true)
440 }
441
442 fn collect_variables(atom: &RuleAtom, vars: &mut std::collections::HashSet<String>) {
443 if let RuleAtom::Triple {
444 subject,
445 predicate,
446 object,
447 } = atom
448 {
449 if let Term::Variable(var) = subject {
450 vars.insert(var.clone());
451 }
452 if let Term::Variable(var) = predicate {
453 vars.insert(var.clone());
454 }
455 if let Term::Variable(var) = object {
456 vars.insert(var.clone());
457 }
458 } }
460}
461
462pub struct DebuggingGuide;
466
467impl DebuggingGuide {
468 pub fn enable_debugging_example() -> Result<()> {
470 use crate::debug::DebuggableRuleEngine;
471
472 let mut debug_engine = DebuggableRuleEngine::new();
473
474 debug_engine.enable_debugging(true);
476
477 debug_engine.add_breakpoint("specific_rule_name");
479
480 let facts = vec![RuleAtom::Triple {
482 subject: Term::Constant("test".to_string()),
483 predicate: Term::Constant("type".to_string()),
484 object: Term::Constant("entity".to_string()),
485 }];
486
487 let _result = debug_engine.debug_forward_chain(&facts)?;
488
489 let trace = debug_engine.get_trace();
491 let metrics = debug_engine.get_metrics();
492 let conflicts = debug_engine.get_conflicts();
493
494 println!("Execution trace: {} entries", trace.len());
495 println!("Performance metrics: {metrics:?}");
496 println!("Detected conflicts: {}", conflicts.len());
497
498 let report = debug_engine.generate_debug_report();
500 println!("{report}");
501
502 Ok(())
503 }
504
505 pub fn debugging_techniques() -> Vec<(&'static str, &'static str)> {
507 vec![
508 (
509 "Rule tracing",
510 "Enable execution tracing to see rule firing order",
511 ),
512 (
513 "Breakpoints",
514 "Set breakpoints on specific rules for step debugging",
515 ),
516 (
517 "Performance profiling",
518 "Measure rule execution times and memory usage",
519 ),
520 (
521 "Conflict detection",
522 "Identify contradictory or redundant rules",
523 ),
524 ("Derivation paths", "Trace how specific facts were derived"),
525 ("Cache analysis", "Monitor cache hit rates and performance"),
526 ("Memory monitoring", "Track memory usage during execution"),
527 (
528 "Statistics collection",
529 "Gather execution statistics for optimization",
530 ),
531 ]
532 }
533
534 pub fn troubleshooting_checklist() -> Vec<&'static str> {
536 vec![
537 "Check rule syntax and structure",
538 "Verify variable consistency between head and body",
539 "Ensure termination conditions for recursive rules",
540 "Validate input facts format and types",
541 "Check for infinite loops or cycles",
542 "Monitor memory usage for large datasets",
543 "Verify rule execution order and dependencies",
544 "Test with simplified rule sets first",
545 "Use debugging tools to trace execution",
546 "Check for rule conflicts and contradictions",
547 ]
548 }
549}
550
551pub struct IntegrationExamples;
555
556impl IntegrationExamples {
557 pub fn rdf_integration_example() -> Result<Vec<RuleAtom>> {
559 let mut engine = RuleEngine::new();
560
561 let rdfs_rule = Rule {
563 name: "rdfs_subclass".to_string(),
564 body: vec![
565 RuleAtom::Triple {
566 subject: Term::Variable("X".to_string()),
567 predicate: Term::Constant(
568 "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),
569 ),
570 object: Term::Variable("Y".to_string()),
571 },
572 RuleAtom::Triple {
573 subject: Term::Variable("Z".to_string()),
574 predicate: Term::Constant(
575 "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
576 ),
577 object: Term::Variable("X".to_string()),
578 },
579 ],
580 head: vec![RuleAtom::Triple {
581 subject: Term::Variable("Z".to_string()),
582 predicate: Term::Constant(
583 "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
584 ),
585 object: Term::Variable("Y".to_string()),
586 }],
587 };
588
589 engine.add_rule(rdfs_rule);
590
591 let facts = vec![
593 RuleAtom::Triple {
594 subject: Term::Constant("http://example.org/Dog".to_string()),
595 predicate: Term::Constant(
596 "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),
597 ),
598 object: Term::Constant("http://example.org/Animal".to_string()),
599 },
600 RuleAtom::Triple {
601 subject: Term::Constant("http://example.org/fido".to_string()),
602 predicate: Term::Constant(
603 "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
604 ),
605 object: Term::Constant("http://example.org/Dog".to_string()),
606 },
607 ];
608
609 engine.forward_chain(&facts)
610 }
611
612 pub fn caching_integration_example() -> Result<()> {
614 use crate::cache::RuleCache;
615
616 let cache = RuleCache::new();
617 let mut engine = RuleEngine::new();
618
619 engine.set_cache(Some(cache));
621
622 let rule = Rule {
624 name: "cached_rule".to_string(),
625 body: vec![RuleAtom::Triple {
626 subject: Term::Variable("X".to_string()),
627 predicate: Term::Constant("likes".to_string()),
628 object: Term::Constant("coffee".to_string()),
629 }],
630 head: vec![RuleAtom::Triple {
631 subject: Term::Variable("X".to_string()),
632 predicate: Term::Constant("drinks".to_string()),
633 object: Term::Constant("beverage".to_string()),
634 }],
635 };
636
637 engine.add_rule(rule);
638
639 let facts = vec![RuleAtom::Triple {
640 subject: Term::Constant("alice".to_string()),
641 predicate: Term::Constant("likes".to_string()),
642 object: Term::Constant("coffee".to_string()),
643 }];
644
645 let _result1 = engine.forward_chain(&facts)?;
647
648 let _result2 = engine.forward_chain(&facts)?;
650
651 if let Some(cache) = engine.get_cache() {
653 let stats = cache.get_statistics();
654 println!("Cache hit rate: {:.2}%", stats.rule_cache.hit_rate * 100.0);
655 }
656
657 Ok(())
658 }
659}
660
661#[cfg(test)]
662mod tests {
663 use super::*;
664
665 #[test]
666 fn test_basic_example() -> Result<(), Box<dyn std::error::Error>> {
667 let result = GettingStartedGuide::basic_example();
668 assert!(result.is_ok());
669 let facts = result?;
670 assert!(!facts.is_empty());
671
672 let mortal_facts: Vec<_> = facts
674 .iter()
675 .filter(|fact| match fact {
676 RuleAtom::Triple {
677 predicate, object, ..
678 } => {
679 predicate == &Term::Constant("type".to_string())
680 && object == &Term::Constant("Mortal".to_string())
681 }
682 _ => false,
683 })
684 .collect();
685
686 assert!(mortal_facts.len() >= 2);
687 Ok(())
688 }
689
690 #[test]
691 fn test_backward_chaining_example() -> Result<(), Box<dyn std::error::Error>> {
692 let result = GettingStartedGuide::backward_chaining_example();
693 assert!(result.is_ok());
694 assert!(result?); Ok(())
696 }
697
698 #[test]
699 fn test_family_relationships() -> Result<(), Box<dyn std::error::Error>> {
700 let result = GettingStartedGuide::family_relationships_example();
701 assert!(result.is_ok());
702 let facts = result?;
703
704 let grandparent_facts: Vec<_> = facts
706 .iter()
707 .filter(|fact| match fact {
708 RuleAtom::Triple { predicate, .. } => {
709 predicate == &Term::Constant("grandparent".to_string())
710 }
711 _ => false,
712 })
713 .collect();
714
715 assert!(!grandparent_facts.is_empty());
716 Ok(())
717 }
718
719 #[test]
720 fn test_rule_validation() -> Result<(), Box<dyn std::error::Error>> {
721 let result = RuleAuthoringBestPractices::validate_rule_example();
722 assert!(result.is_ok());
723 assert!(result?); Ok(())
725 }
726
727 #[test]
728 fn test_ontology_reasoning() -> Result<(), Box<dyn std::error::Error>> {
729 let result = GettingStartedGuide::ontology_reasoning_example();
730 assert!(result.is_ok());
731 let facts = result?;
732
733 assert!(!facts.is_empty());
735 Ok(())
736 }
737
738 #[test]
739 fn test_rdf_integration() -> Result<(), Box<dyn std::error::Error>> {
740 let result = IntegrationExamples::rdf_integration_example();
741 assert!(result.is_ok());
742 let facts = result?;
743
744 let animal_facts: Vec<_> = facts
746 .iter()
747 .filter(|fact| match fact {
748 RuleAtom::Triple {
749 subject, object, ..
750 } => {
751 subject == &Term::Constant("http://example.org/fido".to_string())
752 && object == &Term::Constant("http://example.org/Animal".to_string())
753 }
754 _ => false,
755 })
756 .collect();
757
758 assert!(!animal_facts.is_empty());
759 Ok(())
760 }
761}