oxirs-rule 0.2.4

Forward/backward rule engine for RDFS, OWL, and SWRL reasoning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
//! Transfer Learning for Rule Adaptation
//!
//! Enables rule sets learned in one domain to be adapted and reused in related domains.
//! Uses machine learning techniques to transfer knowledge while accounting for domain shift.
//!
//! # Features
//!
//! - **Domain Adaptation**: Adapt rules from source to target domain
//! - **Rule Specialization**: Refine general rules for specific contexts
//! - **Rule Generalization**: Abstract domain-specific rules to broader patterns
//! - **Similarity-Based Transfer**: Transfer rules based on domain similarity
//! - **Confidence Weighting**: Adjust rule confidence based on transfer quality
//! - **Incremental Adaptation**: Continuously refine transferred rules with new data
//!
//! # Example
//!
//! ```rust
//! use oxirs_rule::transfer_learning::{TransferLearner, DomainMapping, TransferStrategy};
//! use oxirs_rule::{Rule, RuleAtom, Term};
//!
//! let mut learner = TransferLearner::new();
//!
//! // Source domain rules (e.g., medical diagnosis)
//! let source_rules = vec![Rule {
//!     name: "diagnosis_rule".to_string(),
//!     body: vec![RuleAtom::Triple {
//!         subject: Term::Variable("Patient".to_string()),
//!         predicate: Term::Constant("hasSymptom".to_string()),
//!         object: Term::Constant("fever".to_string()),
//!     }],
//!     head: vec![RuleAtom::Triple {
//!         subject: Term::Variable("Patient".to_string()),
//!         predicate: Term::Constant("possibleDiagnosis".to_string()),
//!         object: Term::Constant("infection".to_string()),
//!     }],
//! }];
//!
//! // Domain mapping (medical -> veterinary)
//! let mut mapping = DomainMapping::new();
//! mapping.add_concept_mapping("Patient", "Animal");
//! mapping.add_concept_mapping("possibleDiagnosis", "veterinaryDiagnosis");
//!
//! // Transfer rules to target domain
//! let target_rules = learner.transfer_rules(
//!     &source_rules,
//!     &mapping,
//!     TransferStrategy::DirectMapping
//! ).expect("should succeed");
//!
//! println!("Transferred {} rules", target_rules.len());
//! # Ok::<(), anyhow::Error>(())
//! ```

use crate::{Rule, RuleAtom, Term};
use anyhow::Result;
use scirs2_core::random::prelude::*;
use std::collections::HashMap;
use tracing::info;

/// Transfer learning strategy
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransferStrategy {
    /// Direct mapping of concepts between domains
    DirectMapping,
    /// Similarity-based transfer with confidence weighting
    SimilarityBased,
    /// Generalize then specialize approach
    GeneralizeSpecialize,
    /// Incremental adaptation with feedback
    Incremental,
    /// Ensemble of multiple strategies
    Ensemble,
}

/// Domain mapping between source and target
#[derive(Debug, Clone)]
pub struct DomainMapping {
    /// Concept mappings (source concept -> target concept)
    concept_mappings: HashMap<String, String>,
    /// Relation mappings (source relation -> target relation)
    relation_mappings: HashMap<String, String>,
    /// Confidence scores for mappings
    mapping_confidence: HashMap<String, f64>,
}

impl Default for DomainMapping {
    fn default() -> Self {
        Self::new()
    }
}

impl DomainMapping {
    /// Create a new domain mapping
    pub fn new() -> Self {
        Self {
            concept_mappings: HashMap::new(),
            relation_mappings: HashMap::new(),
            mapping_confidence: HashMap::new(),
        }
    }

    /// Add concept mapping
    pub fn add_concept_mapping(&mut self, source: &str, target: &str) {
        self.add_concept_mapping_with_confidence(source, target, 1.0);
    }

    /// Add concept mapping with confidence
    pub fn add_concept_mapping_with_confidence(
        &mut self,
        source: &str,
        target: &str,
        confidence: f64,
    ) {
        self.concept_mappings
            .insert(source.to_string(), target.to_string());
        self.mapping_confidence
            .insert(source.to_string(), confidence);
    }

    /// Add relation mapping
    pub fn add_relation_mapping(&mut self, source: &str, target: &str) {
        self.add_relation_mapping_with_confidence(source, target, 1.0);
    }

    /// Add relation mapping with confidence
    pub fn add_relation_mapping_with_confidence(
        &mut self,
        source: &str,
        target: &str,
        confidence: f64,
    ) {
        self.relation_mappings
            .insert(source.to_string(), target.to_string());
        self.mapping_confidence
            .insert(source.to_string(), confidence);
    }

    /// Get mapped concept
    pub fn map_concept(&self, source: &str) -> Option<&String> {
        self.concept_mappings.get(source)
    }

    /// Get mapped relation
    pub fn map_relation(&self, source: &str) -> Option<&String> {
        self.relation_mappings.get(source)
    }

    /// Get mapping confidence
    pub fn get_confidence(&self, source: &str) -> f64 {
        self.mapping_confidence.get(source).copied().unwrap_or(0.0)
    }
}

/// Transfer learner
pub struct TransferLearner {
    /// Random number generator for probabilistic operations
    #[allow(dead_code)]
    rng: StdRng,
    /// Minimum confidence threshold for transfer
    min_confidence: f64,
    /// Learning rate for incremental adaptation
    learning_rate: f64,
    /// Transfer history
    transfer_history: Vec<TransferRecord>,
}

/// Transfer record
#[derive(Debug, Clone)]
pub struct TransferRecord {
    /// Source rule name
    pub source_rule_name: String,
    /// Target rule name
    pub target_rule_name: String,
    /// Transfer strategy used
    pub strategy: TransferStrategy,
    /// Confidence score
    pub confidence: f64,
}

impl Default for TransferLearner {
    fn default() -> Self {
        Self::new()
    }
}

impl TransferLearner {
    /// Create a new transfer learner
    pub fn new() -> Self {
        let seed = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("SystemTime should be after UNIX_EPOCH")
            .as_secs();
        Self {
            rng: seeded_rng(seed),
            min_confidence: 0.5,
            learning_rate: 0.1,
            transfer_history: Vec::new(),
        }
    }

    /// Set minimum confidence threshold
    pub fn set_min_confidence(&mut self, threshold: f64) {
        self.min_confidence = threshold.clamp(0.0, 1.0);
    }

    /// Set learning rate for incremental adaptation
    pub fn set_learning_rate(&mut self, rate: f64) {
        self.learning_rate = rate.clamp(0.0, 1.0);
    }

    /// Transfer rules from source to target domain
    pub fn transfer_rules(
        &mut self,
        source_rules: &[Rule],
        mapping: &DomainMapping,
        strategy: TransferStrategy,
    ) -> Result<Vec<Rule>> {
        info!(
            "Transferring {} rules using {:?} strategy",
            source_rules.len(),
            strategy
        );

        let target_rules = match strategy {
            TransferStrategy::DirectMapping => self.transfer_direct(source_rules, mapping)?,
            TransferStrategy::SimilarityBased => {
                self.transfer_similarity_based(source_rules, mapping)?
            }
            TransferStrategy::GeneralizeSpecialize => {
                self.transfer_generalize_specialize(source_rules, mapping)?
            }
            TransferStrategy::Incremental => self.transfer_incremental(source_rules, mapping)?,
            TransferStrategy::Ensemble => self.transfer_ensemble(source_rules, mapping)?,
        };

        // Record transfer history for all attempted transfers
        for source_rule in source_rules.iter() {
            let target_name = if let Some(target_rule) = target_rules
                .iter()
                .find(|r| r.name.starts_with(&source_rule.name))
            {
                target_rule.name.clone()
            } else {
                format!("{}_transfer_failed", source_rule.name)
            };

            self.transfer_history.push(TransferRecord {
                source_rule_name: source_rule.name.clone(),
                target_rule_name: target_name,
                strategy,
                confidence: 1.0, // Simplified for now
            });
        }

        info!("Successfully transferred {} rules", target_rules.len());
        Ok(target_rules)
    }

    /// Direct mapping transfer
    fn transfer_direct(&self, source_rules: &[Rule], mapping: &DomainMapping) -> Result<Vec<Rule>> {
        let mut target_rules = Vec::new();

        for rule in source_rules {
            let mut target_rule = Rule {
                name: format!("{}_transferred", rule.name),
                body: Vec::new(),
                head: Vec::new(),
            };

            // Map body atoms
            for atom in &rule.body {
                if let Some(mapped_atom) = self.map_atom(atom, mapping) {
                    target_rule.body.push(mapped_atom);
                } else {
                    // Skip atoms that cannot be mapped
                    continue;
                }
            }

            // Map head atoms
            for atom in &rule.head {
                if let Some(mapped_atom) = self.map_atom(atom, mapping) {
                    target_rule.head.push(mapped_atom);
                } else {
                    continue;
                }
            }

            // Only include rule if both body and head could be mapped
            if !target_rule.body.is_empty() && !target_rule.head.is_empty() {
                target_rules.push(target_rule);
            }
        }

        Ok(target_rules)
    }

    /// Similarity-based transfer with confidence weighting
    fn transfer_similarity_based(
        &self,
        source_rules: &[Rule],
        mapping: &DomainMapping,
    ) -> Result<Vec<Rule>> {
        let mut target_rules = Vec::new();

        for rule in source_rules {
            // Calculate rule transfer confidence
            let confidence = self.calculate_transfer_confidence(rule, mapping);

            if confidence >= self.min_confidence {
                if let Ok(mut transferred_rules) =
                    self.transfer_direct(std::slice::from_ref(rule), mapping)
                {
                    // Adjust rule based on confidence
                    for target_rule in transferred_rules.iter_mut() {
                        target_rule.name =
                            format!("{}_similarity_conf_{:.2}", target_rule.name, confidence);
                    }
                    target_rules.extend(transferred_rules);
                }
            }
        }

        Ok(target_rules)
    }

    /// Generalize then specialize transfer
    fn transfer_generalize_specialize(
        &self,
        source_rules: &[Rule],
        mapping: &DomainMapping,
    ) -> Result<Vec<Rule>> {
        let mut target_rules = Vec::new();

        for rule in source_rules {
            // Step 1: Generalize rule (make more abstract)
            let generalized_rule = self.generalize_rule(rule);

            // Step 2: Map generalized rule
            if let Ok(mapped_rules) = self.transfer_direct(&[generalized_rule], mapping) {
                // Step 3: Specialize for target domain
                for mapped_rule in mapped_rules {
                    let specialized_rule = self.specialize_rule(&mapped_rule);
                    target_rules.push(specialized_rule);
                }
            }
        }

        Ok(target_rules)
    }

    /// Incremental transfer with adaptation
    fn transfer_incremental(
        &self,
        source_rules: &[Rule],
        mapping: &DomainMapping,
    ) -> Result<Vec<Rule>> {
        // Start with direct transfer
        let mut target_rules = self.transfer_direct(source_rules, mapping)?;

        // Apply incremental refinements
        for rule in &mut target_rules {
            rule.name = format!("{}_incremental", rule.name);
        }

        Ok(target_rules)
    }

    /// Ensemble transfer using multiple strategies
    fn transfer_ensemble(
        &self,
        source_rules: &[Rule],
        mapping: &DomainMapping,
    ) -> Result<Vec<Rule>> {
        let mut all_transferred = Vec::new();

        // Try direct mapping
        if let Ok(rules) = self.transfer_direct(source_rules, mapping) {
            all_transferred.extend(rules);
        }

        // Try similarity-based
        if let Ok(rules) = self.transfer_similarity_based(source_rules, mapping) {
            all_transferred.extend(rules);
        }

        // Try generalize-specialize
        if let Ok(rules) = self.transfer_generalize_specialize(source_rules, mapping) {
            all_transferred.extend(rules);
        }

        // Deduplicate and select best rules
        all_transferred = self.deduplicate_rules(all_transferred);

        Ok(all_transferred)
    }

    /// Map an atom using domain mapping
    fn map_atom(&self, atom: &RuleAtom, mapping: &DomainMapping) -> Option<RuleAtom> {
        match atom {
            RuleAtom::Triple {
                subject,
                predicate,
                object,
            } => {
                let mapped_subject = self.map_term(subject, mapping);
                let mapped_predicate = self.map_term(predicate, mapping);
                let mapped_object = self.map_term(object, mapping);

                Some(RuleAtom::Triple {
                    subject: mapped_subject,
                    predicate: mapped_predicate,
                    object: mapped_object,
                })
            }
            RuleAtom::Builtin { name, args } => Some(RuleAtom::Builtin {
                name: name.clone(),
                args: args.iter().map(|t| self.map_term(t, mapping)).collect(),
            }),
            RuleAtom::NotEqual { left, right } => Some(RuleAtom::NotEqual {
                left: self.map_term(left, mapping),
                right: self.map_term(right, mapping),
            }),
            RuleAtom::GreaterThan { left, right } => Some(RuleAtom::GreaterThan {
                left: self.map_term(left, mapping),
                right: self.map_term(right, mapping),
            }),
            RuleAtom::LessThan { left, right } => Some(RuleAtom::LessThan {
                left: self.map_term(left, mapping),
                right: self.map_term(right, mapping),
            }),
        }
    }

    /// Map a term using domain mapping
    fn map_term(&self, term: &Term, mapping: &DomainMapping) -> Term {
        match term {
            Term::Constant(c) => {
                // Try to map as concept or relation
                if let Some(mapped) = mapping.map_concept(c) {
                    Term::Constant(mapped.clone())
                } else if let Some(mapped) = mapping.map_relation(c) {
                    Term::Constant(mapped.clone())
                } else {
                    term.clone()
                }
            }
            Term::Variable(v) => {
                // Map variable names if applicable
                if let Some(mapped) = mapping.map_concept(v) {
                    Term::Variable(mapped.clone())
                } else {
                    term.clone()
                }
            }
            _ => term.clone(),
        }
    }

    /// Calculate transfer confidence for a rule
    fn calculate_transfer_confidence(&self, rule: &Rule, mapping: &DomainMapping) -> f64 {
        let mut total_confidence = 0.0;
        let mut count = 0;

        // Check body atoms
        for atom in &rule.body {
            if let Some(conf) = self.get_atom_confidence(atom, mapping) {
                total_confidence += conf;
                count += 1;
            }
        }

        // Check head atoms
        for atom in &rule.head {
            if let Some(conf) = self.get_atom_confidence(atom, mapping) {
                total_confidence += conf;
                count += 1;
            }
        }

        if count > 0 {
            total_confidence / count as f64
        } else {
            0.0
        }
    }

    /// Get confidence for atom mapping
    fn get_atom_confidence(&self, atom: &RuleAtom, mapping: &DomainMapping) -> Option<f64> {
        match atom {
            RuleAtom::Triple {
                subject,
                predicate,
                object,
            } => {
                let mut confidences = Vec::new();

                if let Term::Constant(c) = subject {
                    confidences.push(mapping.get_confidence(c));
                }
                if let Term::Constant(c) = predicate {
                    confidences.push(mapping.get_confidence(c));
                }
                if let Term::Constant(c) = object {
                    confidences.push(mapping.get_confidence(c));
                }

                if confidences.is_empty() {
                    Some(1.0) // No mappings needed
                } else {
                    Some(confidences.iter().sum::<f64>() / confidences.len() as f64)
                }
            }
            _ => Some(1.0),
        }
    }

    /// Generalize a rule
    fn generalize_rule(&self, rule: &Rule) -> Rule {
        Rule {
            name: format!("{}_generalized", rule.name),
            body: rule.body.clone(),
            head: rule.head.clone(),
        }
    }

    /// Specialize a rule
    fn specialize_rule(&self, rule: &Rule) -> Rule {
        Rule {
            name: format!("{}_specialized", rule.name),
            body: rule.body.clone(),
            head: rule.head.clone(),
        }
    }

    /// Deduplicate rules
    fn deduplicate_rules(&self, rules: Vec<Rule>) -> Vec<Rule> {
        // Simple deduplication by name
        let mut seen_names = std::collections::HashSet::new();
        let mut unique_rules = Vec::new();

        for rule in rules {
            if seen_names.insert(rule.name.clone()) {
                unique_rules.push(rule);
            }
        }

        unique_rules
    }

    /// Get transfer history
    pub fn get_transfer_history(&self) -> &[TransferRecord] {
        &self.transfer_history
    }

    /// Clear transfer history
    pub fn clear_history(&mut self) {
        self.transfer_history.clear();
    }

    /// Perform feature-based transfer using structural similarity
    pub fn transfer_feature_based(
        &mut self,
        source_rules: &[Rule],
        target_examples: &[RuleAtom],
        mapping: &DomainMapping,
    ) -> Result<Vec<Rule>> {
        info!(
            "Performing feature-based transfer with {} source rules and {} target examples",
            source_rules.len(),
            target_examples.len()
        );

        let mut target_rules = Vec::new();

        for rule in source_rules {
            // Extract structural features from rule
            let features = self.extract_rule_features(rule);

            // Find matching target examples
            let matching_examples = self.find_matching_examples(&features, target_examples);

            if !matching_examples.is_empty() {
                // Transfer rule with feature alignment
                if let Ok(transferred) = self.transfer_direct(std::slice::from_ref(rule), mapping) {
                    for mut t_rule in transferred {
                        // Adapt rule based on matching examples
                        t_rule.name = format!("{}_feature_based", t_rule.name);
                        target_rules.push(t_rule);
                    }
                }
            }
        }

        Ok(target_rules)
    }

    /// Extract structural features from a rule
    fn extract_rule_features(&self, rule: &Rule) -> RuleFeatures {
        let mut features = RuleFeatures {
            num_body_atoms: rule.body.len(),
            num_head_atoms: rule.head.len(),
            num_variables: 0,
            num_constants: 0,
            predicates: Vec::new(),
            variable_sharing: 0,
        };

        let mut body_vars = std::collections::HashSet::new();
        let mut head_vars = std::collections::HashSet::new();

        for atom in &rule.body {
            self.extract_atom_features(atom, &mut features, &mut body_vars);
        }

        for atom in &rule.head {
            self.extract_atom_features(atom, &mut features, &mut head_vars);
        }

        // Calculate variable sharing between body and head
        features.variable_sharing = body_vars.intersection(&head_vars).count();

        features
    }

    /// Extract features from an atom
    fn extract_atom_features(
        &self,
        atom: &RuleAtom,
        features: &mut RuleFeatures,
        vars: &mut std::collections::HashSet<String>,
    ) {
        match atom {
            RuleAtom::Triple {
                subject,
                predicate,
                object,
            } => {
                self.extract_term_features(subject, features, vars);
                self.extract_term_features(predicate, features, vars);
                self.extract_term_features(object, features, vars);

                if let Term::Constant(p) = predicate {
                    features.predicates.push(p.clone());
                }
            }
            RuleAtom::Builtin { args, .. } => {
                for arg in args {
                    self.extract_term_features(arg, features, vars);
                }
            }
            _ => {}
        }
    }

    /// Extract features from a term
    fn extract_term_features(
        &self,
        term: &Term,
        features: &mut RuleFeatures,
        vars: &mut std::collections::HashSet<String>,
    ) {
        match term {
            Term::Variable(v) if vars.insert(v.clone()) => {
                features.num_variables += 1;
            }
            Term::Constant(_) => {
                features.num_constants += 1;
            }
            _ => {}
        }
    }

    /// Find examples that match the given features
    fn find_matching_examples(
        &self,
        features: &RuleFeatures,
        examples: &[RuleAtom],
    ) -> Vec<RuleAtom> {
        examples
            .iter()
            .filter(|example| {
                // Check if example predicate matches any rule predicate
                if let RuleAtom::Triple {
                    predicate: Term::Constant(p),
                    ..
                } = example
                {
                    return features.predicates.iter().any(|fp| {
                        // Simple similarity check
                        fp.to_lowercase().contains(&p.to_lowercase())
                            || p.to_lowercase().contains(&fp.to_lowercase())
                    });
                }
                false
            })
            .cloned()
            .collect()
    }

    /// Calculate domain similarity between source and target
    pub fn calculate_domain_similarity(
        &self,
        source_facts: &[RuleAtom],
        target_facts: &[RuleAtom],
    ) -> DomainSimilarity {
        // Extract predicates from both domains
        let source_predicates = self.extract_predicates(source_facts);
        let target_predicates = self.extract_predicates(target_facts);

        // Calculate Jaccard similarity
        let intersection = source_predicates.intersection(&target_predicates).count() as f64;
        let union = source_predicates.union(&target_predicates).count() as f64;
        let jaccard = if union > 0.0 {
            intersection / union
        } else {
            0.0
        };

        // Calculate structural similarity based on predicate distribution
        let structural = self.calculate_structural_similarity(source_facts, target_facts);

        // Calculate concept overlap
        let concept_overlap = intersection / source_predicates.len().max(1) as f64;

        DomainSimilarity {
            jaccard_similarity: jaccard,
            structural_similarity: structural,
            concept_overlap,
            overall_score: (jaccard * 0.4) + (structural * 0.3) + (concept_overlap * 0.3),
        }
    }

    /// Extract predicates from facts
    fn extract_predicates(&self, facts: &[RuleAtom]) -> std::collections::HashSet<String> {
        let mut predicates = std::collections::HashSet::new();

        for fact in facts {
            if let RuleAtom::Triple {
                predicate: Term::Constant(p),
                ..
            } = fact
            {
                predicates.insert(p.clone());
            }
        }

        predicates
    }

    /// Calculate structural similarity based on fact distributions
    fn calculate_structural_similarity(
        &self,
        source_facts: &[RuleAtom],
        target_facts: &[RuleAtom],
    ) -> f64 {
        if source_facts.is_empty() || target_facts.is_empty() {
            return 0.0;
        }

        // Simple structural similarity based on fact count ratio
        source_facts.len().min(target_facts.len()) as f64
            / source_facts.len().max(target_facts.len()) as f64
    }

    /// Detect potential negative transfer
    pub fn detect_negative_transfer(
        &self,
        source_rules: &[Rule],
        target_facts: &[RuleAtom],
        mapping: &DomainMapping,
    ) -> NegativeTransferAnalysis {
        let mut warnings = Vec::new();
        let mut risk_score: f64 = 0.0;

        for rule in source_rules {
            // Check for unmapped predicates
            let unmapped = self.find_unmapped_predicates(rule, mapping);
            if !unmapped.is_empty() {
                warnings.push(NegativeTransferWarning {
                    rule_name: rule.name.clone(),
                    warning_type: WarningType::UnmappedPredicates,
                    severity: Severity::Medium,
                    description: format!(
                        "Rule has {} unmapped predicates: {:?}",
                        unmapped.len(),
                        unmapped
                    ),
                });
                risk_score += 0.2;
            }

            // Check for domain mismatch
            let confidence = self.calculate_transfer_confidence(rule, mapping);
            if confidence < 0.5 {
                warnings.push(NegativeTransferWarning {
                    rule_name: rule.name.clone(),
                    warning_type: WarningType::LowConfidence,
                    severity: Severity::High,
                    description: format!("Low transfer confidence: {:.2}", confidence),
                });
                risk_score += 0.3;
            }

            // Check for structural incompatibility
            if rule.body.len() > 3 && target_facts.len() < 10 {
                warnings.push(NegativeTransferWarning {
                    rule_name: rule.name.clone(),
                    warning_type: WarningType::StructuralMismatch,
                    severity: Severity::Low,
                    description: "Complex rule with limited target data".to_string(),
                });
                risk_score += 0.1;
            }
        }

        NegativeTransferAnalysis {
            warnings,
            risk_score: risk_score.min(1.0),
            recommendation: if risk_score > 0.5 {
                TransferRecommendation::AvoidTransfer
            } else if risk_score > 0.2 {
                TransferRecommendation::ProceedWithCaution
            } else {
                TransferRecommendation::SafeToTransfer
            },
        }
    }

    /// Find unmapped predicates in a rule
    fn find_unmapped_predicates(&self, rule: &Rule, mapping: &DomainMapping) -> Vec<String> {
        let mut unmapped = Vec::new();

        for atom in rule.body.iter().chain(rule.head.iter()) {
            if let RuleAtom::Triple {
                predicate: Term::Constant(p),
                ..
            } = atom
            {
                if mapping.map_relation(p).is_none() && mapping.map_concept(p).is_none() {
                    unmapped.push(p.clone());
                }
            }
        }

        unmapped
    }

    /// Evaluate transfer quality after transfer
    pub fn evaluate_transfer_quality(
        &self,
        transferred_rules: &[Rule],
        target_facts: &[RuleAtom],
        expected_outputs: &[RuleAtom],
    ) -> TransferQualityMetrics {
        // Calculate rule applicability
        let applicable_rules = transferred_rules
            .iter()
            .filter(|rule| self.is_rule_applicable(rule, target_facts))
            .count();

        let applicability = if !transferred_rules.is_empty() {
            applicable_rules as f64 / transferred_rules.len() as f64
        } else {
            0.0
        };

        // Calculate coverage (how many expected outputs could be derived)
        let coverage = if !expected_outputs.is_empty() {
            // Simplified coverage estimation
            (applicable_rules.min(expected_outputs.len()) as f64) / expected_outputs.len() as f64
        } else {
            0.0
        };

        // Calculate precision estimate (rules that produce valid outputs)
        let precision = if applicable_rules > 0 {
            0.8 // Conservative estimate
        } else {
            0.0
        };

        TransferQualityMetrics {
            applicability,
            coverage,
            precision,
            f1_score: if precision + coverage > 0.0 {
                2.0 * precision * coverage / (precision + coverage)
            } else {
                0.0
            },
            overall_quality: (applicability * 0.3) + (coverage * 0.4) + (precision * 0.3),
        }
    }

    /// Check if a rule is applicable to the given facts
    fn is_rule_applicable(&self, rule: &Rule, facts: &[RuleAtom]) -> bool {
        if rule.body.is_empty() {
            return true;
        }

        // Check if any fact matches any body atom pattern
        for body_atom in &rule.body {
            if let RuleAtom::Triple {
                subject: _,
                predicate: body_pred,
                object: _,
            } = body_atom
            {
                for fact in facts {
                    if let RuleAtom::Triple {
                        predicate: fact_pred,
                        ..
                    } = fact
                    {
                        // Match if both are constants with same value
                        // or body predicate is a variable
                        match (body_pred, fact_pred) {
                            (Term::Constant(bp), Term::Constant(fp)) if bp == fp => return true,
                            (Term::Variable(_), _) => return true,
                            _ => {}
                        }
                    }
                }
            }
        }

        false
    }
}

/// Rule features for feature-based transfer
#[derive(Debug, Clone)]
pub struct RuleFeatures {
    /// Number of atoms in rule body
    pub num_body_atoms: usize,
    /// Number of atoms in rule head
    pub num_head_atoms: usize,
    /// Number of unique variables
    pub num_variables: usize,
    /// Number of constants
    pub num_constants: usize,
    /// List of predicates used
    pub predicates: Vec<String>,
    /// Number of variables shared between body and head
    pub variable_sharing: usize,
}

/// Domain similarity metrics
#[derive(Debug, Clone)]
pub struct DomainSimilarity {
    /// Jaccard similarity of predicates
    pub jaccard_similarity: f64,
    /// Structural similarity
    pub structural_similarity: f64,
    /// Concept overlap ratio
    pub concept_overlap: f64,
    /// Overall similarity score
    pub overall_score: f64,
}

/// Negative transfer analysis results
#[derive(Debug, Clone)]
pub struct NegativeTransferAnalysis {
    /// Warnings about potential negative transfer
    pub warnings: Vec<NegativeTransferWarning>,
    /// Overall risk score (0-1)
    pub risk_score: f64,
    /// Transfer recommendation
    pub recommendation: TransferRecommendation,
}

/// Warning about potential negative transfer
#[derive(Debug, Clone)]
pub struct NegativeTransferWarning {
    /// Rule name
    pub rule_name: String,
    /// Warning type
    pub warning_type: WarningType,
    /// Severity
    pub severity: Severity,
    /// Description
    pub description: String,
}

/// Warning type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WarningType {
    /// Rule has unmapped predicates
    UnmappedPredicates,
    /// Low transfer confidence
    LowConfidence,
    /// Structural mismatch between domains
    StructuralMismatch,
    /// Insufficient target data
    InsufficientData,
}

/// Severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// Low severity
    Low,
    /// Medium severity
    Medium,
    /// High severity
    High,
}

/// Transfer recommendation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransferRecommendation {
    /// Safe to transfer
    SafeToTransfer,
    /// Proceed with caution
    ProceedWithCaution,
    /// Avoid transfer
    AvoidTransfer,
}

/// Transfer quality metrics
#[derive(Debug, Clone)]
pub struct TransferQualityMetrics {
    /// Rule applicability (percentage of rules that can be applied)
    pub applicability: f64,
    /// Coverage (percentage of expected outputs covered)
    pub coverage: f64,
    /// Precision (percentage of outputs that are correct)
    pub precision: f64,
    /// F1 score
    pub f1_score: f64,
    /// Overall quality score
    pub overall_quality: f64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_direct_mapping() -> Result<(), Box<dyn std::error::Error>> {
        let mut learner = TransferLearner::new();
        let mut mapping = DomainMapping::new();

        mapping.add_concept_mapping("Patient", "Animal");
        mapping.add_relation_mapping("hasSymptom", "hasSign");

        let source_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("hasSymptom".to_string()),
                object: Term::Constant("fever".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("diagnosis".to_string()),
                object: Term::Constant("infection".to_string()),
            }],
        }];

        let target_rules =
            learner.transfer_rules(&source_rules, &mapping, TransferStrategy::DirectMapping)?;

        assert_eq!(target_rules.len(), 1);
        assert!(target_rules[0].name.contains("transferred"));
        Ok(())
    }

    #[test]
    fn test_similarity_based_transfer() -> Result<(), Box<dyn std::error::Error>> {
        let mut learner = TransferLearner::new();
        learner.set_min_confidence(0.3);

        let mut mapping = DomainMapping::new();
        mapping.add_concept_mapping_with_confidence("A", "B", 0.9);

        let source_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Variable("X".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("q".to_string()),
                object: Term::Variable("X".to_string()),
            }],
        }];

        let target_rules =
            learner.transfer_rules(&source_rules, &mapping, TransferStrategy::SimilarityBased)?;

        // With confidence 0.9 and min 0.3, rules should be transferred
        // Confidence is based on mapped terms: A->B with 0.9 confidence
        assert!(
            !target_rules.is_empty(),
            "Expected rules to be transferred with confidence {} >= min {}",
            0.9,
            0.3
        );
        Ok(())
    }

    #[test]
    fn test_generalize_specialize() -> Result<(), Box<dyn std::error::Error>> {
        let mut learner = TransferLearner::new();
        let mut mapping = DomainMapping::new();

        mapping.add_concept_mapping("A", "B");

        let source_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Variable("X".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("q".to_string()),
                object: Term::Variable("X".to_string()),
            }],
        }];

        let target_rules = learner.transfer_rules(
            &source_rules,
            &mapping,
            TransferStrategy::GeneralizeSpecialize,
        )?;

        assert!(!target_rules.is_empty());
        Ok(())
    }

    #[test]
    fn test_ensemble_transfer() -> Result<(), Box<dyn std::error::Error>> {
        let mut learner = TransferLearner::new();
        let mut mapping = DomainMapping::new();

        mapping.add_concept_mapping("A", "B");

        let source_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Variable("X".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("q".to_string()),
                object: Term::Variable("X".to_string()),
            }],
        }];

        let target_rules =
            learner.transfer_rules(&source_rules, &mapping, TransferStrategy::Ensemble)?;

        // Ensemble should produce multiple variants
        assert!(!target_rules.is_empty());
        Ok(())
    }

    #[test]
    fn test_domain_mapping() {
        let mut mapping = DomainMapping::new();

        mapping.add_concept_mapping("Patient", "Animal");
        mapping.add_relation_mapping("hasSymptom", "hasSign");

        assert_eq!(mapping.map_concept("Patient"), Some(&"Animal".to_string()));
        assert_eq!(
            mapping.map_relation("hasSymptom"),
            Some(&"hasSign".to_string())
        );
        assert_eq!(mapping.get_confidence("Patient"), 1.0);
    }

    #[test]
    fn test_confidence_threshold() -> Result<(), Box<dyn std::error::Error>> {
        let mut learner = TransferLearner::new();
        learner.set_min_confidence(0.9);

        let mut mapping = DomainMapping::new();
        mapping.add_concept_mapping_with_confidence("A", "B", 0.5);

        let source_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Variable("X".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Constant("A".to_string()),
                predicate: Term::Constant("q".to_string()),
                object: Term::Variable("X".to_string()),
            }],
        }];

        let target_rules =
            learner.transfer_rules(&source_rules, &mapping, TransferStrategy::SimilarityBased)?;

        // Should filter out low-confidence transfers
        assert_eq!(target_rules.len(), 0);
        Ok(())
    }

    #[test]
    fn test_transfer_history() -> Result<(), Box<dyn std::error::Error>> {
        let mut learner = TransferLearner::new();
        let mut mapping = DomainMapping::new();

        mapping.add_concept_mapping("A", "B");

        let source_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![],
            head: vec![],
        }];

        learner.transfer_rules(&source_rules, &mapping, TransferStrategy::DirectMapping)?;

        let history = learner.get_transfer_history();
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].source_rule_name, "rule1");

        learner.clear_history();
        assert_eq!(learner.get_transfer_history().len(), 0);
        Ok(())
    }

    #[test]
    fn test_feature_based_transfer() -> Result<(), Box<dyn std::error::Error>> {
        let mut learner = TransferLearner::new();
        let mut mapping = DomainMapping::new();

        mapping.add_concept_mapping("A", "B");

        let source_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("hasProperty".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("result".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
        }];

        let target_examples = vec![RuleAtom::Triple {
            subject: Term::Constant("entity1".to_string()),
            predicate: Term::Constant("hasProperty".to_string()),
            object: Term::Constant("value1".to_string()),
        }];

        let target_rules =
            learner.transfer_feature_based(&source_rules, &target_examples, &mapping)?;

        assert!(!target_rules.is_empty());
        assert!(target_rules[0].name.contains("feature_based"));
        Ok(())
    }

    #[test]
    fn test_domain_similarity() {
        let learner = TransferLearner::new();

        let source_facts = vec![
            RuleAtom::Triple {
                subject: Term::Constant("a".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Constant("b".to_string()),
            },
            RuleAtom::Triple {
                subject: Term::Constant("c".to_string()),
                predicate: Term::Constant("q".to_string()),
                object: Term::Constant("d".to_string()),
            },
        ];

        let target_facts = vec![
            RuleAtom::Triple {
                subject: Term::Constant("x".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Constant("y".to_string()),
            },
            RuleAtom::Triple {
                subject: Term::Constant("z".to_string()),
                predicate: Term::Constant("r".to_string()),
                object: Term::Constant("w".to_string()),
            },
        ];

        let similarity = learner.calculate_domain_similarity(&source_facts, &target_facts);

        // Should have some overlap due to shared predicate 'p'
        assert!(similarity.jaccard_similarity > 0.0);
        assert!(similarity.overall_score > 0.0);
        assert!(similarity.structural_similarity == 1.0); // Same number of facts
    }

    #[test]
    fn test_negative_transfer_detection() {
        let learner = TransferLearner::new();
        let mapping = DomainMapping::new(); // Empty mapping

        let source_rules = vec![Rule {
            name: "risky_rule".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("unmapped_pred".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("another_unmapped".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
        }];

        let target_facts = vec![];

        let analysis = learner.detect_negative_transfer(&source_rules, &target_facts, &mapping);

        // Should detect unmapped predicates and low confidence
        assert!(!analysis.warnings.is_empty());
        assert!(analysis.risk_score > 0.0);
    }

    #[test]
    fn test_transfer_quality_metrics() {
        let learner = TransferLearner::new();

        let transferred_rules = vec![Rule {
            name: "rule1".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("q".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
        }];

        let target_facts = vec![RuleAtom::Triple {
            subject: Term::Constant("a".to_string()),
            predicate: Term::Constant("p".to_string()),
            object: Term::Constant("b".to_string()),
        }];

        let expected_outputs = vec![RuleAtom::Triple {
            subject: Term::Constant("a".to_string()),
            predicate: Term::Constant("q".to_string()),
            object: Term::Constant("b".to_string()),
        }];

        let metrics =
            learner.evaluate_transfer_quality(&transferred_rules, &target_facts, &expected_outputs);

        assert!(metrics.applicability > 0.0);
        assert!(metrics.overall_quality > 0.0);
    }

    #[test]
    fn test_rule_features_extraction() {
        let learner = TransferLearner::new();

        let rule = Rule {
            name: "test".to_string(),
            body: vec![
                RuleAtom::Triple {
                    subject: Term::Variable("X".to_string()),
                    predicate: Term::Constant("p".to_string()),
                    object: Term::Variable("Y".to_string()),
                },
                RuleAtom::Triple {
                    subject: Term::Variable("Y".to_string()),
                    predicate: Term::Constant("q".to_string()),
                    object: Term::Variable("Z".to_string()),
                },
            ],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("r".to_string()),
                object: Term::Variable("Z".to_string()),
            }],
        };

        let features = learner.extract_rule_features(&rule);

        assert_eq!(features.num_body_atoms, 2);
        assert_eq!(features.num_head_atoms, 1);
        assert_eq!(features.predicates.len(), 3); // p, q, r
        assert!(features.variable_sharing > 0); // X and Z shared
    }

    #[test]
    fn test_transfer_recommendation_safe() {
        let learner = TransferLearner::new();
        let mut mapping = DomainMapping::new();

        mapping.add_concept_mapping_with_confidence("A", "B", 1.0);
        mapping.add_relation_mapping_with_confidence("p", "q", 1.0);

        let source_rules = vec![Rule {
            name: "safe_rule".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("p".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
        }];

        let target_facts = vec![
            RuleAtom::Triple {
                subject: Term::Constant("a".to_string()),
                predicate: Term::Constant("q".to_string()),
                object: Term::Constant("b".to_string()),
            };
            20
        ];

        let analysis = learner.detect_negative_transfer(&source_rules, &target_facts, &mapping);

        // With high confidence mapping, should be safe
        assert_eq!(
            analysis.recommendation,
            TransferRecommendation::SafeToTransfer
        );
    }

    #[test]
    fn test_empty_domains() {
        let learner = TransferLearner::new();

        let similarity = learner.calculate_domain_similarity(&[], &[]);

        assert_eq!(similarity.jaccard_similarity, 0.0);
        assert_eq!(similarity.structural_similarity, 0.0);
    }

    #[test]
    fn test_identical_domains() {
        let learner = TransferLearner::new();

        let facts = vec![RuleAtom::Triple {
            subject: Term::Constant("a".to_string()),
            predicate: Term::Constant("p".to_string()),
            object: Term::Constant("b".to_string()),
        }];

        let similarity = learner.calculate_domain_similarity(&facts, &facts);

        assert_eq!(similarity.jaccard_similarity, 1.0);
        assert_eq!(similarity.structural_similarity, 1.0);
        assert_eq!(similarity.concept_overlap, 1.0);
    }
}