Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor(conflicts): Remove statistics functionality and update documentation

KaifAhmad1a93700813fae
diff --git a/cookbook/introduction/17_Conflict_Detection.ipynb b/cookbook/introduction/17_Conflict_Detection.ipynb
index 75c2c1d5..c118e712 100644
--- a/cookbook/introduction/17_Conflict_Detection.ipynb
+++ b/cookbook/introduction/17_Conflict_Detection.ipynb
@@ -44,19 +44,56 @@
"outputs": [],
"source": [
"from semantica.conflicts import ConflictDetector\n",
+ "from datetime import datetime\n",
"\n",
- "conflict_detector = ConflictDetector()\n",
+ "# Initialize detector with configuration\n",
+ "detector = ConflictDetector(\n",
+ " confidence_threshold=0.7,\n",
+ " track_provenance=True,\n",
+ " conflict_fields={\"Company\": [\"name\", \"founded\", \"revenue\"]}\n",
+ ")\n",
"\n",
+ "# Sample entities from multiple sources\n",
"entities = [\n",
- " {\"id\": \"e1\", \"name\": \"Apple Inc.\", \"source\": \"source1\"},\n",
- " {\"id\": \"e1\", \"name\": \"Apple Incorporated\", \"source\": \"source2\"}\n",
+ " {\"id\": \"e1\", \"name\": \"Apple Inc.\", \"founded\": 1976, \"type\": \"Company\", \n",
+ " \"source\": \"wikipedia\", \"confidence\": 0.9},\n",
+ " {\"id\": \"e1\", \"name\": \"Apple Incorporated\", \"founded\": 1976, \"type\": \"Company\",\n",
+ " \"source\": \"official_site\", \"confidence\": 0.95},\n",
+ " {\"id\": \"e1\", \"name\": \"Apple Inc.\", \"founded\": 1977, \"type\": \"Company\",\n",
+ " \"source\": \"news\", \"confidence\": 0.7},\n",
+ " {\"id\": \"e2\", \"name\": \"Microsoft\", \"type\": \"Company\", \"founded\": 1975, \"source\": \"source1\"},\n",
+ " {\"id\": \"e2\", \"name\": \"Microsoft Corporation\", \"type\": \"Organization\", \n",
+ " \"founded\": 1975, \"source\": \"source2\"},\n",
"]\n",
"\n",
- "conflicts = conflict_detector.detect_value_conflicts(entities, \"name\")\n",
+ "# 1.1 Value Conflict Detection\n",
+ "value_conflicts = detector.detect_value_conflicts(entities, \"name\")\n",
"\n",
- "print(f\"Detected {len(conflicts)} conflicts\")\n",
- "for conflict in conflicts[:3]:\n",
- " print(f\" Conflict: {conflict.entity_id} - {conflict.conflict_type}\")\n"
+ "# 1.2 Type Conflict Detection\n",
+ "type_conflicts = detector.detect_type_conflicts(entities)\n",
+ "\n",
+ "# 1.3 Temporal Conflict Detection\n",
+ "temporal_conflicts = detector.detect_temporal_conflicts(entities)\n",
+ "\n",
+ "# 1.4 Logical Conflict Detection\n",
+ "logical_entities = [\n",
+ " {\"id\": \"e3\", \"type\": \"Person\", \"name\": \"John Doe\", \"source\": \"source1\"},\n",
+ " {\"id\": \"e3\", \"type\": \"Organization\", \"name\": \"John Doe\", \"source\": \"source2\"},\n",
+ "]\n",
+ "logical_conflicts = detector.detect_logical_conflicts(logical_entities)\n",
+ "\n",
+ "# 1.5 Relationship Conflict Detection\n",
+ "relationships = [\n",
+ " {\"id\": \"rel1\", \"source_id\": \"e1\", \"target_id\": \"e2\", \"type\": \"competes_with\", \"source\": \"source1\"},\n",
+ " {\"id\": \"rel1\", \"source_id\": \"e1\", \"target_id\": \"e2\", \"type\": \"partners_with\", \"source\": \"source2\"},\n",
+ "]\n",
+ "rel_conflicts = detector.detect_relationship_conflicts(relationships)\n",
+ "\n",
+ "# 1.6 General Conflict Detection (all types)\n",
+ "all_conflicts = detector.detect_conflicts(entities)\n",
+ "\n",
+ "# Get conflict report\n",
+ "report = detector.get_conflict_report()\n"
]
},
{
@@ -74,18 +111,54 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.conflicts import SourceTracker\n",
+ "from semantica.conflicts import SourceTracker, SourceReference\n",
+ "from datetime import datetime\n",
+ "\n",
+ "# Initialize source tracker\n",
+ "tracker = SourceTracker()\n",
+ "\n",
+ "# Create source references with metadata\n",
+ "source1 = SourceReference(\n",
+ " document=\"wikipedia\",\n",
+ " page=1,\n",
+ " section=\"Company Information\",\n",
+ " timestamp=datetime(2023, 1, 15),\n",
+ " confidence=0.9\n",
+ ")\n",
+ "\n",
+ "source2 = SourceReference(\n",
+ " document=\"official_site\",\n",
+ " section=\"About Us\",\n",
+ " timestamp=datetime(2023, 3, 20),\n",
+ " confidence=0.95\n",
+ ")\n",
+ "\n",
+ "# Track property sources\n",
+ "tracker.track_property_source(\"e1\", \"name\", \"Apple Inc.\", source1)\n",
+ "tracker.track_property_source(\"e1\", \"name\", \"Apple Incorporated\", source2)\n",
+ "tracker.track_property_source(\"e1\", \"founded\", 1976, source1)\n",
"\n",
- "source_tracker = SourceTracker()\n",
+ "# Track entity sources\n",
+ "tracker.track_entity_source(\"e1\", source1)\n",
"\n",
- "source_tracker.track_source(\"e1\", \"source1\", {\"name\": \"Apple Inc.\"})\n",
- "source_tracker.track_source(\"e1\", \"source2\", {\"name\": \"Apple Incorporated\"})\n",
+ "# Set source credibility scores\n",
+ "tracker.set_source_credibility(\"wikipedia\", 0.85)\n",
+ "tracker.set_source_credibility(\"official_site\", 0.95)\n",
"\n",
- "sources = source_tracker.get_sources(\"e1\")\n",
+ "# Retrieve property sources\n",
+ "prop_source = tracker.get_property_sources(\"e1\", \"name\")\n",
"\n",
- "print(f\"Tracked sources for e1: {len(sources)}\")\n",
- "for source in sources:\n",
- " print(f\" Source: {source.source_id}, Property: {source.property_name}\")\n"
+ "# Get entity sources\n",
+ "entity_sources = tracker.get_entity_sources(\"e1\")\n",
+ "\n",
+ "# Get all source credibilities\n",
+ "all_credibilities = tracker.get_all_source_credibilities()\n",
+ "\n",
+ "# Generate traceability chain\n",
+ "chain = tracker.generate_traceability_chain(\"e1\", \"name\")\n",
+ "\n",
+ "# Generate source report\n",
+ "report = tracker.generate_source_report(\"e1\")\n"
]
},
{
@@ -105,12 +178,31 @@
"source": [
"from semantica.conflicts import ConflictResolver\n",
"\n",
- "conflict_resolver = ConflictResolver()\n",
+ "# Initialize resolver with source tracker\n",
+ "resolver = ConflictResolver(\n",
+ " default_strategy=\"voting\",\n",
+ " source_tracker=tracker\n",
+ ")\n",
"\n",
- "if conflicts:\n",
- " resolution = conflict_resolver.resolve_conflicts(conflicts, strategy=\"most_recent\")\n",
- " print(f\"Resolved {len(resolution.resolved_conflicts)} conflicts\")\n",
- " print(f\"Resolution strategy: {resolution.strategy}\")\n"
+ "# Resolve conflicts using different strategies\n",
+ "if value_conflicts:\n",
+ " # Voting strategy\n",
+ " voting_results = resolver.resolve_conflicts(value_conflicts, strategy=\"voting\")\n",
+ " \n",
+ " # Credibility-weighted strategy\n",
+ " credibility_results = resolver.resolve_conflicts(value_conflicts, strategy=\"credibility_weighted\")\n",
+ " \n",
+ " # Most recent strategy\n",
+ " recent_results = resolver.resolve_conflicts(value_conflicts, strategy=\"most_recent\")\n",
+ " \n",
+ " # Highest confidence strategy\n",
+ " confidence_results = resolver.resolve_conflicts(value_conflicts, strategy=\"highest_confidence\")\n",
+ " \n",
+ " # First seen strategy\n",
+ " first_seen_results = resolver.resolve_conflicts(value_conflicts, strategy=\"first_seen\")\n",
+ " \n",
+ " # Manual review strategy\n",
+ " manual_results = resolver.resolve_conflicts(value_conflicts, strategy=\"manual_review\")\n"
]
},
{
@@ -127,6 +219,379 @@
"\n",
"Next: Learn about configuration in the Configuration notebook.\n"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictAnalyzer\n",
+ "\n",
+ "# Initialize analyzer\n",
+ "analyzer = ConflictAnalyzer()\n",
+ "\n",
+ "# Comprehensive analysis\n",
+ "analysis = analyzer.analyze_conflicts(all_conflicts)\n",
+ "\n",
+ "# Analysis by type, severity, and source\n",
+ "by_type = analysis['by_type']['counts']\n",
+ "by_severity = analysis['by_severity']['counts']\n",
+ "by_source = analysis['by_source']['counts']\n",
+ "\n",
+ "# Top entities and properties\n",
+ "top_entities = analysis['by_entity']['top_entities']\n",
+ "top_properties = analysis['by_property']['top_properties']\n",
+ "\n",
+ "# Patterns and recommendations\n",
+ "patterns = analysis['patterns']\n",
+ "recommendations = analysis['recommendations']\n",
+ "\n",
+ "# Trend analysis\n",
+ "trends = analyzer.analyze_trends(all_conflicts)\n",
+ "\n",
+ "# Generate insights report\n",
+ "insights = analyzer.generate_insights_report(all_conflicts)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Part 5: Investigation Guides\n",
+ "\n",
+ "`InvestigationGuideGenerator` creates guides for manual review.\n",
+ "\n",
+ "**Guide Components:**\n",
+ "- Conflict summary, investigation steps, recommended actions\n",
+ "- Source information, context, severity assessment\n",
+ "\n",
+ "**Use Cases:** High-severity conflicts, ambiguous cases, compliance, QA workflows\n",
+ "\n",
+ "**Export Formats:** Markdown checklists, detailed reports, structured context\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import InvestigationGuideGenerator\n",
+ "\n",
+ "# Initialize guide generator\n",
+ "guide_generator = InvestigationGuideGenerator(source_tracker=tracker)\n",
+ "\n",
+ "# Generate guide for a conflict\n",
+ "if value_conflicts:\n",
+ " guide = guide_generator.generate_guide(value_conflicts[0])\n",
+ "\n",
+ "# Generate guides for multiple conflicts\n",
+ "guides = guide_generator.generate_guides(value_conflicts[:3])\n",
+ "\n",
+ "# Export checklist\n",
+ "checklist = guide_generator.export_investigation_checklist(guide, format=\"markdown\")\n",
+ "\n",
+ "# Generate conflict report\n",
+ "conflict_report = guide_generator.generate_conflict_report(value_conflicts, format=\"detailed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Part 6: Methods Module\n",
+ "\n",
+ "`semantica.conflicts.methods` provides convenience functions for functional-style access.\n",
+ "\n",
+ "**Functions:**\n",
+ "- `detect_conflicts()`: Methods: `value`, `type`, `temporal`, `logical`, `relationship`\n",
+ "- `resolve_conflicts()`: Methods: `voting`, `credibility_weighted`, `most_recent`, `highest_confidence`, `first_seen`, `manual_review`\n",
+ "- `analyze_conflicts()`: Methods: `pattern`, `type`, `severity`, `source`, `trend`\n",
+ "- `track_sources()`: Methods: `property`, `entity`, `relationship`\n",
+ "- `generate_investigation_guide()`: Methods: `guide`, `checklist`, `context`\n",
+ "- `list_available_methods()`: List all methods by task type\n",
+ "- `get_conflict_method()`: Retrieve specific method function\n",
+ "\n",
+ "**Benefits:** Simpler API, method discovery, consistent interface, extensible\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts.methods import (\n",
+ " detect_conflicts,\n",
+ " resolve_conflicts,\n",
+ " analyze_conflicts,\n",
+ " track_sources,\n",
+ " generate_investigation_guide,\n",
+ " list_available_methods,\n",
+ " get_conflict_method\n",
+ ")\n",
+ "\n",
+ "# Detection methods\n",
+ "value_conflicts_method = detect_conflicts(entities, method=\"value\", property_name=\"name\")\n",
+ "type_conflicts_method = detect_conflicts(entities, method=\"type\")\n",
+ "temporal_conflicts_method = detect_conflicts(entities, method=\"temporal\")\n",
+ "logical_conflicts_method = detect_conflicts(logical_entities, method=\"logical\")\n",
+ "\n",
+ "# Resolution methods\n",
+ "if value_conflicts_method:\n",
+ " voting_results = resolve_conflicts(value_conflicts_method, method=\"voting\")\n",
+ " credibility_results = resolve_conflicts(value_conflicts_method, method=\"credibility_weighted\")\n",
+ "\n",
+ "# Analysis methods\n",
+ "pattern_analysis = analyze_conflicts(all_conflicts, method=\"pattern\")\n",
+ "type_analysis = analyze_conflicts(all_conflicts, method=\"type\")\n",
+ "severity_analysis = analyze_conflicts(all_conflicts, method=\"severity\")\n",
+ "source_analysis = analyze_conflicts(all_conflicts, method=\"source\")\n",
+ "trend_analysis = analyze_conflicts(all_conflicts, method=\"trend\")\n",
+ "\n",
+ "# Source tracking methods\n",
+ "source_ref = SourceReference(document=\"test_source\", confidence=0.9)\n",
+ "track_sources(\"e1\", method=\"property\", property_name=\"name\", value=\"Test\", source=source_ref)\n",
+ "track_sources(\"e1\", method=\"entity\", source=source_ref)\n",
+ "\n",
+ "# Investigation guide methods\n",
+ "if value_conflicts_method:\n",
+ " guide_method = generate_investigation_guide(value_conflicts_method[0], method=\"guide\")\n",
+ " checklist_method = generate_investigation_guide(value_conflicts_method[0], method=\"checklist\")\n",
+ " context_method = generate_investigation_guide(value_conflicts_method[0], method=\"context\")\n",
+ "\n",
+ "# List available methods\n",
+ "all_methods = list_available_methods()\n",
+ "\n",
+ "# Get specific method\n",
+ "voting_method = get_conflict_method(\"resolution\", \"voting\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Part 7: Method Registry\n",
+ "\n",
+ "`method_registry` provides a plugin system for custom methods.\n",
+ "\n",
+ "**Registration:** Task type (`detection`, `resolution`, `analysis`, `tracking`, `investigation`), method name, function\n",
+ "\n",
+ "**Use Cases:**\n",
+ "- Domain-specific resolution logic\n",
+ "- External system integration\n",
+ "- A/B testing strategies\n",
+ "- ML model integration\n",
+ "- Hybrid resolution approaches\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import method_registry, ResolutionResult\n",
+ "\n",
+ "# Register custom resolution method\n",
+ "def custom_resolution(conflicts, **kwargs):\n",
+ " \"\"\"Custom resolution that always picks the first value.\"\"\"\n",
+ " results = []\n",
+ " for conflict in conflicts:\n",
+ " if conflict.conflicting_values:\n",
+ " result = ResolutionResult(\n",
+ " conflict_id=conflict.conflict_id,\n",
+ " resolved=True,\n",
+ " resolved_value=conflict.conflicting_values[0],\n",
+ " resolution_strategy=\"custom_first\",\n",
+ " confidence=0.8,\n",
+ " resolution_notes=\"Custom: Always use first value\"\n",
+ " )\n",
+ " results.append(result)\n",
+ " return results\n",
+ "\n",
+ "# Register the custom method\n",
+ "method_registry.register(\"resolution\", \"custom_first\", custom_resolution)\n",
+ "\n",
+ "# List registered methods\n",
+ "registered = method_registry.list_all(\"resolution\")\n",
+ "\n",
+ "# Use custom method\n",
+ "if value_conflicts:\n",
+ " custom_results = resolve_conflicts(value_conflicts, method=\"custom_first\")\n",
+ "\n",
+ "# Unregister method\n",
+ "method_registry.unregister(\"resolution\", \"custom_first\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Part 8: Configuration\n",
+ "\n",
+ "`ConflictsConfig` manages settings programmatically, via environment variables, or method-specific.\n",
+ "\n",
+ "**Global Settings:**\n",
+ "- `confidence_threshold`, `default_strategy`, `auto_resolve`, `track_provenance`\n",
+ "\n",
+ "**Method-Specific:** Voting (`min_sources`, `tie_breaker`), credibility-weighted (`min_credibility`), most_recent (`time_field`), etc.\n",
+ "\n",
+ "**Priority:** Method-specific → Global → Environment variables → Defaults\n",
+ "\n",
+ "**Best Practices:** Set source credibility early, configure conflict fields, use method-specific configs\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictsConfig, conflicts_config\n",
+ "\n",
+ "# Using global config instance\n",
+ "conflicts_config.set(\"confidence_threshold\", 0.8)\n",
+ "conflicts_config.set(\"default_strategy\", \"credibility_weighted\")\n",
+ "threshold = conflicts_config.get(\"confidence_threshold\", default=0.7)\n",
+ "\n",
+ "# Method-specific configuration\n",
+ "conflicts_config.set_method_config(\"voting\", min_sources=2, tie_breaker=\"confidence\")\n",
+ "conflicts_config.set_method_config(\"credibility_weighted\", min_credibility=0.5)\n",
+ "voting_config = conflicts_config.get_method_config(\"voting\")\n",
+ "\n",
+ "# Create custom config instance\n",
+ "custom_config = ConflictsConfig()\n",
+ "custom_config.set(\"confidence_threshold\", 0.9)\n",
+ "custom_config.set(\"auto_resolve\", True)\n",
+ "all_config = custom_config.get_all()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Part 9: Complete Workflow\n",
+ "\n",
+ "End-to-end example: integrating company data from multiple sources.\n",
+ "\n",
+ "**Workflow:** Initialize → Track Sources → Detect → Resolve → Analyze → Generate Guides → Build Final Entity\n",
+ "\n",
+ "**Scenario:** Three sources (Wikipedia, Official Site, Financial DB) with conflicts in name, founding year, and type classifications.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Complete workflow: Company data integration from multiple sources\n",
+ "from semantica.conflicts import (\n",
+ " ConflictDetector, ConflictResolver, ConflictAnalyzer,\n",
+ " SourceTracker, InvestigationGuideGenerator, SourceReference\n",
+ ")\n",
+ "\n",
+ "# Sample company data from multiple sources\n",
+ "company_data = [\n",
+ " {\"id\": \"company_1\", \"name\": \"Apple Inc.\", \"founded\": 1976, \"revenue\": 394328000000,\n",
+ " \"headquarters\": \"Cupertino, California\", \"type\": \"Company\",\n",
+ " \"source\": \"wikipedia\", \"confidence\": 0.85, \"timestamp\": datetime(2023, 1, 15)},\n",
+ " {\"id\": \"company_1\", \"name\": \"Apple Inc.\", \"founded\": 1976, \"revenue\": 394328000000,\n",
+ " \"headquarters\": \"Cupertino, CA\", \"type\": \"Company\",\n",
+ " \"source\": \"official_site\", \"confidence\": 0.95, \"timestamp\": datetime(2023, 3, 20)},\n",
+ " {\"id\": \"company_1\", \"name\": \"Apple Incorporated\", \"founded\": 1977, \"revenue\": 394328000000,\n",
+ " \"headquarters\": \"Cupertino\", \"type\": \"Organization\",\n",
+ " \"source\": \"financial_db\", \"confidence\": 0.80, \"timestamp\": datetime(2023, 2, 10)},\n",
+ "]\n",
+ "\n",
+ "# Initialize all components\n",
+ "detector = ConflictDetector(\n",
+ " confidence_threshold=0.7,\n",
+ " track_provenance=True,\n",
+ " conflict_fields={\"Company\": [\"name\", \"founded\", \"revenue\", \"headquarters\"]}\n",
+ ")\n",
+ "\n",
+ "tracker = SourceTracker()\n",
+ "tracker.set_source_credibility(\"wikipedia\", 0.85)\n",
+ "tracker.set_source_credibility(\"official_site\", 0.95)\n",
+ "tracker.set_source_credibility(\"financial_db\", 0.80)\n",
+ "\n",
+ "resolver = ConflictResolver(default_strategy=\"credibility_weighted\", source_tracker=tracker)\n",
+ "analyzer = ConflictAnalyzer()\n",
+ "guide_generator = InvestigationGuideGenerator(source_tracker=tracker)\n",
+ "\n",
+ "# Step 1: Track sources\n",
+ "for entity in company_data:\n",
+ " source_ref = SourceReference(\n",
+ " document=entity[\"source\"],\n",
+ " confidence=entity[\"confidence\"],\n",
+ " timestamp=entity[\"timestamp\"]\n",
+ " )\n",
+ " tracker.track_property_source(entity[\"id\"], \"name\", entity[\"name\"], source_ref)\n",
+ " tracker.track_property_source(entity[\"id\"], \"founded\", entity[\"founded\"], source_ref)\n",
+ "\n",
+ "# Step 2: Detect conflicts\n",
+ "detected_conflicts = detector.detect_entity_conflicts(company_data, entity_type=\"Company\")\n",
+ "\n",
+ "# Step 3: Resolve conflicts\n",
+ "resolved_data = {}\n",
+ "for conflict in detected_conflicts:\n",
+ " results = resolver.resolve_conflicts([conflict], strategy=\"credibility_weighted\")\n",
+ " if results[0].resolved:\n",
+ " resolved_data[conflict.property_name] = results[0].resolved_value\n",
+ "\n",
+ "# Step 4: Analyze\n",
+ "analysis = analyzer.analyze_conflicts(detected_conflicts)\n",
+ "\n",
+ "# Step 5: Generate guides for unresolved conflicts\n",
+ "unresolved = [c for c in detected_conflicts if c.property_name not in resolved_data]\n",
+ "if unresolved:\n",
+ " guides = guide_generator.generate_guides(unresolved)\n",
+ "\n",
+ "# Final resolved entity\n",
+ "final_entity = {\"id\": \"company_1\", \"type\": \"Company\", **resolved_data}\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Summary\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "✅ **Detection**: Value, type, temporal, logical, relationship conflicts \n",
+ "✅ **Resolution**: 6 strategies (voting, credibility-weighted, most_recent, first_seen, highest_confidence, manual_review) \n",
+ "✅ **Source Tracking**: Provenance, credibility, traceability chains \n",
+ "✅ **Analysis**: Patterns, trends, recommendations \n",
+ "✅ **Investigation Guides**: Automated guides and checklists \n",
+ "✅ **Methods Module**: Convenience functions for all operations \n",
+ "✅ **Method Registry**: Custom method registration \n",
+ "✅ **Configuration**: Global and method-specific settings\n",
+ "\n",
+ "### Best Practices\n",
+ "\n",
+ "1. Set source credibility before detection\n",
+ "2. Choose strategies based on data characteristics\n",
+ "3. Enable provenance tracking for audits\n",
+ "4. Analyze patterns before resolving\n",
+ "5. Use guides for high-severity conflicts\n",
+ "6. Configure conflict fields to focus on critical properties\n",
+ "\n",
+ "### Common Patterns\n",
+ "\n",
+ "- **Integration**: Track → Detect → Resolve → Analyze\n",
+ "- **QA**: Detect → Analyze → Generate guides → Review\n",
+ "- **Auto**: Detect → Resolve → Analyze\n",
+ "- **Assessment**: Track → Analyze → Adjust credibility\n",
+ "\n",
+ "### Next Steps\n",
+ "\n",
+ "- `04_Conflict_Resolution_Strategies.ipynb` - Advanced strategies\n",
+ "- `06_Multi_Source_Data_Integration.ipynb` - Integration workflows\n",
+ "- [API Reference](https://semantica.readthedocs.io/reference/conflicts/)\n",
+ "- [Usage Guide](../semantica/conflicts/conflicts_usage.md)\n"
+ ]
}
],
"metadata": {
diff --git a/docs/reference/conflicts.md b/docs/reference/conflicts.md
index 437e0137..b203b02c 100644
--- a/docs/reference/conflicts.md
+++ b/docs/reference/conflicts.md
@@ -89,10 +89,14 @@ Detects conflicts across entities and properties.
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `detect_conflicts(entities)` | Detect all conflicts | Multi-pass detection |
-| `detect_value_conflicts(entities, prop)` | Check specific property | Value comparison |
+| `detect_conflicts(entities, entity_type)` | Detect all conflicts | Multi-pass detection |
+| `detect_value_conflicts(entities, property_name, entity_type)` | Check specific property | Value comparison |
| `detect_type_conflicts(entities)` | Check entity types | Hierarchy validation |
| `detect_temporal_conflicts(entities)` | Check timestamps | Time-series analysis |
+| `detect_logical_conflicts(entities)` | Check logical inconsistencies | Rule validation |
+| `detect_relationship_conflicts(relationships)` | Check relationship conflicts | Relationship comparison |
+| `detect_entity_conflicts(entities, entity_type)` | Detect all conflicts for entity | Multi-property detection |
+| `get_conflict_report()` | Generate conflict report | Report generation |
**Example:**
@@ -106,7 +110,7 @@ conflicts = detector.detect_conflicts([
])
for conflict in conflicts:
- print(f"Conflict on {conflict.property_name}: {conflict.values}")
+ print(f"Conflict on {conflict.property_name}: {conflict.conflicting_values}")
```
### ConflictResolver
@@ -117,10 +121,8 @@ Resolves detected conflicts using configured strategies.
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `resolve_conflicts(conflicts)` | Resolve list of conflicts | Strategy pattern |
-| `resolve_by_voting(conflict)` | Majority vote | Frequency counting |
-| `resolve_by_credibility(conflict)` | Source credibility | Weighted average |
-| `resolve_by_recency(conflict)` | Newest value | Timestamp comparison |
+| `resolve_conflicts(conflicts, strategy)` | Resolve list of conflicts | Strategy pattern |
+| Strategies: `voting`, `credibility_weighted`, `most_recent`, `first_seen`, `highest_confidence`, `manual_review` | Various resolution strategies | See algorithm descriptions |
**Example:**
@@ -131,8 +133,9 @@ resolver = ConflictResolver(default_strategy="credibility_weighted")
results = resolver.resolve_conflicts(conflicts)
for result in results:
- print(f"Resolved {result.property}: {result.resolved_value}")
- print(f"Strategy used: {result.strategy}")
+ if result.resolved:
+ print(f"Resolved conflict {result.conflict_id}: {result.resolved_value}")
+ print(f"Strategy used: {result.resolution_strategy}")
```
### SourceTracker
@@ -143,18 +146,28 @@ Tracks source information and credibility scores.
| Method | Description |
|--------|-------------|
-| `track_source(entity, source)` | Register source for entity |
-| `get_source_credibility(source_id)` | Get current credibility score |
-| `update_credibility(source_id, score)` | Update source score |
+| `track_property_source(entity_id, property_name, value, source)` | Track source for property value |
+| `track_entity_source(entity_id, source)` | Track source for entity |
+| `track_relationship_source(relationship_id, source)` | Track source for relationship |
+| `get_source_credibility(document)` | Get current credibility score |
+| `set_source_credibility(document, score)` | Set source credibility score |
+| `get_property_sources(entity_id, property_name)` | Get sources for a property |
+| `get_entity_sources(entity_id)` | Get all sources for an entity |
+| `generate_traceability_chain(entity_id, property_name)` | Generate traceability chain |
+| `generate_source_report(entity_id)` | Generate source analysis report |
**Example:**
```python
-from semantica.conflicts import SourceTracker
+from semantica.conflicts import SourceTracker, SourceReference
tracker = SourceTracker()
-tracker.update_credibility("reliable_source", 0.9)
-tracker.update_credibility("noisy_source", 0.4)
+tracker.set_source_credibility("reliable_source", 0.9)
+tracker.set_source_credibility("noisy_source", 0.4)
+
+# Track property sources
+source = SourceReference(document="doc1", confidence=0.9)
+tracker.track_property_source("entity_1", "name", "Apple Inc.", source)
```
### InvestigationGuideGenerator
@@ -165,22 +178,42 @@ Generates human-readable guides for manual resolution.
| Method | Description |
|--------|-------------|
-| `generate_guide(conflict)` | Create investigation steps |
-| `generate_checklist(conflicts)` | Create bulk checklist |
+| `generate_guide(conflict, additional_context)` | Create investigation guide for a conflict |
+| `generate_guides(conflicts, additional_context)` | Create investigation guides for multiple conflicts |
+| `export_investigation_checklist(guide, format)` | Export guide as checklist (text/markdown) |
+| `generate_conflict_report(conflicts, format)` | Generate comprehensive conflict report |
----
+**Example:**
+
+```python
+from semantica.conflicts import InvestigationGuideGenerator
+
+generator = InvestigationGuideGenerator()
+guide = generator.generate_guide(conflict)
+checklist = generator.export_investigation_checklist(guide, format="markdown")
+```
+
+### ConflictAnalyzer
+
+Analyzes conflict patterns, trends, and provides recommendations.
-## Convenience Functions
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `analyze_conflicts(conflicts)` | Comprehensive conflict analysis |
+| `analyze_trends(conflicts)` | Temporal trend analysis |
+| `generate_insights_report(conflicts)` | Generate insights report |
+
+**Example:**
```python
-from semantica.conflicts import detect_and_resolve
+from semantica.conflicts import ConflictAnalyzer
-# One-line detection and resolution
-conflicts, results = detect_and_resolve(
- entities,
- property_name="revenue",
- resolution_strategy="credibility_weighted"
-)
+analyzer = ConflictAnalyzer()
+analysis = analyzer.analyze_conflicts(conflicts)
+trends = analyzer.analyze_trends(conflicts)
+insights = analyzer.generate_insights_report(conflicts)
```
---
@@ -221,7 +254,7 @@ conflicts:
### Pipeline Integration
```python
-from semantica.conflicts import detect_and_resolve
+from semantica.conflicts import ConflictDetector, ConflictResolver
from semantica.ingest import Ingestor
# 1. Ingest from multiple sources
@@ -232,19 +265,21 @@ data2 = ingestor.ingest("source2.html")
# 2. Combine entities (assuming same IDs)
combined_entities = data1.entities + data2.entities
-# 3. Resolve conflicts
-conflicts, resolutions = detect_and_resolve(
- combined_entities,
- resolution_strategy="credibility_weighted",
- source_credibility={
- "source1.pdf": 0.9,
- "source2.html": 0.6
- }
+# 3. Detect conflicts
+detector = ConflictDetector()
+conflicts = detector.detect_value_conflicts(combined_entities, "revenue")
+
+# 4. Resolve conflicts
+resolver = ConflictResolver()
+resolutions = resolver.resolve_conflicts(
+ conflicts,
+ strategy="credibility_weighted"
)
-# 4. Apply resolutions
+# 5. Apply resolutions
for resolution in resolutions:
- print(f"Final value for {resolution.entity_id}: {resolution.resolved_value}")
+ if resolution.resolved:
+ print(f"Final value for {resolution.conflict_id}: {resolution.resolved_value}")
```
---
@@ -274,7 +309,7 @@ detector = ConflictDetector(
**Solution**: Check and adjust source credibility scores.
```python
-tracker.update_credibility("bad_source", 0.1)
+tracker.set_source_credibility("bad_source", 0.1)
```
---
diff --git a/semantica/conflicts/__init__.py b/semantica/conflicts/__init__.py
index 39d3b513..81745d2c 100644
--- a/semantica/conflicts/__init__.py
+++ b/semantica/conflicts/__init__.py
@@ -27,10 +27,9 @@ Conflict Resolution:
Conflict Analysis:
- Pattern Identification: Frequency-based pattern detection using Counter and defaultdict
- Type Classification: Conflict type categorization and grouping
- - Severity Analysis: Severity-based grouping and statistical analysis
+ - Severity Analysis: Severity-based grouping and analysis
- Source Analysis: Source-based conflict aggregation and analysis
- Trend Analysis: Temporal trend identification using time-series analysis
- - Statistical Analysis: Conflict statistics calculation (mean, median, distribution)
Source Tracking:
- Property Source Tracking: Dictionary-based property-to-source mapping
@@ -52,7 +51,7 @@ Key Features:
- Multiple resolution strategies (voting, credibility-weighted, recency, confidence)
- Investigation guide generation
- Source credibility scoring
- - Conflict reporting and statistics
+ - Conflict reporting
- Method registry for custom conflict methods
- Configuration management with environment variables and config files
@@ -65,13 +64,8 @@ Main Classes:
- MethodRegistry: Registry for custom conflict methods
- ConflictsConfig: Configuration manager for conflicts module
-Convenience Functions:
- - detect_and_resolve: Detect and resolve conflicts in one call
-
Example Usage:
- >>> from semantica.conflicts import detect_and_resolve, ConflictDetector, ConflictResolver
- >>> # Using convenience function
- >>> results = detect_and_resolve(entities, property_name="name", resolution_strategy="voting")
+ >>> from semantica.conflicts import ConflictDetector, ConflictResolver
>>> # Using classes directly
>>> detector = ConflictDetector()
>>> conflicts = detector.detect_value_conflicts(entities, "name")
@@ -104,58 +98,6 @@ from .registry import MethodRegistry, method_registry
from .source_tracker import PropertySource, SourceReference, SourceTracker
-def detect_and_resolve(
- entities,
- property_name: str = None,
- entity_type: str = None,
- detection_method: str = "value",
- resolution_strategy: str = "voting",
- **kwargs,
-):
- """
- Detect and resolve conflicts in entities (convenience function).
-
- This is a user-friendly wrapper that detects and resolves conflicts in one call.
-
- Args:
- entities: List of entity dictionaries to check for conflicts
- property_name: Property name to check (required for value conflicts)
- entity_type: Optional entity type filter
- detection_method: Detection method (default: "value")
- resolution_strategy: Resolution strategy (default: "voting")
- **kwargs: Additional options passed to detector and resolver
-
- Returns:
- Tuple of (conflicts, resolution_results)
-
- Examples:
- >>> from semantica.conflicts import detect_and_resolve
- >>> entities = [
- ... {"id": "1", "name": "Apple Inc.", "source": "doc1"},
- ... {"id": "1", "name": "Apple", "source": "doc2"}
- ... ]
- >>> conflicts, results = detect_and_resolve(
- ... entities,
- ... property_name="name",
- ... resolution_strategy="voting"
- ... )
- """
- conflicts = detect_conflicts(
- entities,
- method=detection_method,
- property_name=property_name,
- entity_type=entity_type,
- **kwargs,
- )
-
- if not conflicts:
- return conflicts, []
-
- results = resolve_conflicts(conflicts, method=resolution_strategy, **kwargs)
-
- return conflicts, results
-
-
__all__ = [
# Core Classes
"ConflictDetector",
@@ -185,6 +127,4 @@ __all__ = [
# Configuration
"ConflictsConfig",
"conflicts_config",
- # Convenience Functions
- "detect_and_resolve",
]
diff --git a/semantica/conflicts/conflict_analyzer.py b/semantica/conflicts/conflict_analyzer.py
index cb23b2fc..d2830142 100644
--- a/semantica/conflicts/conflict_analyzer.py
+++ b/semantica/conflicts/conflict_analyzer.py
@@ -136,11 +136,11 @@ class ConflictAnalyzer:
"total_conflicts": len(conflicts),
"by_type": self._analyze_by_type(conflicts),
"by_severity": self._analyze_by_severity(conflicts),
+ "by_source": self._analyze_by_source(conflicts),
"by_entity": self._analyze_by_entity(conflicts),
"by_property": self._analyze_by_property(conflicts),
"patterns": self._identify_patterns(conflicts),
"recommendations": self._generate_recommendations(conflicts),
- "statistics": self._calculate_statistics(conflicts),
}
self.progress_tracker.stop_tracking(
@@ -222,6 +222,38 @@ class ConflictAnalyzer:
"details": dict(entity_conflicts),
}
+ def _analyze_by_source(self, conflicts: List[Conflict]) -> Dict[str, Any]:
+ """Analyze conflicts by source."""
+ by_source = defaultdict(int)
+ source_conflicts = defaultdict(list)
+
+ for conflict in conflicts:
+ for source in conflict.sources:
+ if isinstance(source, dict):
+ document = source.get("document", "unknown")
+ by_source[document] += 1
+ source_conflicts[document].append(
+ {
+ "conflict_id": conflict.conflict_id,
+ "entity_id": conflict.entity_id,
+ "property_name": conflict.property_name,
+ "type": conflict.conflict_type.value,
+ "severity": conflict.severity,
+ }
+ )
+
+ # Get top sources with most conflicts
+ top_sources = sorted(by_source.items(), key=lambda x: x[1], reverse=True)[:10]
+
+ return {
+ "counts": dict(by_source),
+ "top_sources": [
+ {"source": source, "conflict_count": count}
+ for source, count in top_sources
+ ],
+ "details": dict(source_conflicts),
+ }
+
def _analyze_by_property(self, conflicts: List[Conflict]) -> Dict[str, Any]:
"""Analyze conflicts by property."""
by_property = defaultdict(int)
@@ -369,40 +401,6 @@ class ConflictAnalyzer:
return recommendations
- def _calculate_statistics(self, conflicts: List[Conflict]) -> Dict[str, Any]:
- """Calculate conflict statistics."""
- if not conflicts:
- return {
- "total_conflicts": 0,
- "average_confidence": 0.0,
- "conflict_rate": 0.0,
- }
-
- total_conflicts = len(conflicts)
- avg_confidence = sum(c.confidence for c in conflicts) / total_conflicts
-
- # Count unique entities and properties
- unique_entities = len(set(c.entity_id for c in conflicts if c.entity_id))
- unique_properties = len(
- set(c.property_name for c in conflicts if c.property_name)
- )
-
- # Count by source
- source_counts = Counter()
- for conflict in conflicts:
- for source in conflict.sources:
- source_counts[source.get("document", "unknown")] += 1
-
- return {
- "total_conflicts": total_conflicts,
- "average_confidence": avg_confidence,
- "unique_entities_affected": unique_entities,
- "unique_properties_affected": unique_properties,
- "top_sources": dict(source_counts.most_common(5)),
- "conflict_rate": total_conflicts
- / max(unique_entities, 1), # Conflicts per entity
- }
-
def generate_insights_report(self, conflicts: List[Conflict]) -> Dict[str, Any]:
"""
Generate comprehensive insights report.
@@ -439,3 +437,95 @@ class ConflictAnalyzer:
}
return report
+
+ def analyze_trends(self, conflicts: List[Conflict]) -> List[Dict[str, Any]]:
+ """
+ Analyze temporal trends in conflicts.
+
+ Args:
+ conflicts: List of conflicts to analyze
+
+ Returns:
+ List of trend analysis dictionaries
+ """
+ if not conflicts:
+ return []
+
+ # Group conflicts by time period
+ from collections import defaultdict
+ from datetime import datetime, timedelta
+
+ trends = []
+ conflict_by_period = defaultdict(list)
+
+ # Extract timestamps from conflicts
+ for conflict in conflicts:
+ # Try to get timestamp from sources or metadata
+ timestamp = None
+ for source in conflict.sources:
+ if isinstance(source, dict):
+ metadata = source.get("metadata", {})
+ if "timestamp" in metadata:
+ timestamp = metadata["timestamp"]
+ break
+
+ if not timestamp and conflict.metadata:
+ timestamp = conflict.metadata.get("timestamp")
+
+ if timestamp:
+ if isinstance(timestamp, str):
+ try:
+ timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
+ except (ValueError, AttributeError):
+ try:
+ timestamp = datetime.strptime(timestamp, "%Y-%m-%d")
+ except ValueError:
+ timestamp = None
+
+ if timestamp:
+ # Group by month
+ period_key = timestamp.strftime("%Y-%m")
+ conflict_by_period[period_key].append(conflict)
+ else:
+ # If no timestamp, use current period
+ period_key = datetime.now().strftime("%Y-%m")
+ conflict_by_period[period_key].append(conflict)
+
+ # Analyze trends
+ sorted_periods = sorted(conflict_by_period.keys())
+ if len(sorted_periods) < 2:
+ # Not enough data for trend analysis
+ return [
+ {
+ "period": sorted_periods[0] if sorted_periods else "unknown",
+ "conflict_count": len(conflicts),
+ "trend": "insufficient_data",
+ "trend_direction": "stable",
+ }
+ ]
+
+ for i, period in enumerate(sorted_periods):
+ conflict_count = len(conflict_by_period[period])
+ trend = "stable"
+
+ if i > 0:
+ prev_count = len(conflict_by_period[sorted_periods[i - 1]])
+ if conflict_count > prev_count * 1.1: # 10% increase
+ trend = "increasing"
+ elif conflict_count < prev_count * 0.9: # 10% decrease
+ trend = "decreasing"
+ else:
+ trend = "stable"
+
+ trends.append(
+ {
+ "period": period,
+ "conflict_count": conflict_count,
+ "trend": trend,
+ "trend_direction": "up"
+ if trend == "increasing"
+ else "down" if trend == "decreasing" else "stable",
+ }
+ )
+
+ return trends
\ No newline at end of file
diff --git a/semantica/conflicts/conflict_detector.py b/semantica/conflicts/conflict_detector.py
index 6f165d22..d38e314a 100644
--- a/semantica/conflicts/conflict_detector.py
+++ b/semantica/conflicts/conflict_detector.py
@@ -432,6 +432,437 @@ class ConflictDetector:
return report
+ def detect_type_conflicts(
+ self, entities: List[Dict[str, Any]]
+ ) -> List[Conflict]:
+ """
+ Detect entity type conflicts.
+
+ Args:
+ entities: List of entity dictionaries
+
+ Returns:
+ List of detected conflicts
+ """
+ tracking_id = self.progress_tracker.start_tracking(
+ file=None,
+ module="conflicts",
+ submodule="ConflictDetector",
+ message="Detecting type conflicts",
+ )
+
+ try:
+ conflicts = []
+
+ # Group entities by ID
+ entity_groups: Dict[str, List[Dict[str, Any]]] = {}
+
+ for entity in entities:
+ entity_id = entity.get("id") or entity.get("entity_id")
+ if not entity_id:
+ continue
+
+ if entity_id not in entity_groups:
+ entity_groups[entity_id] = []
+ entity_groups[entity_id].append(entity)
+
+ # Check each entity group for type conflicts
+ for entity_id, entity_list in entity_groups.items():
+ if len(entity_list) < 2:
+ continue # Need at least 2 sources to have conflict
+
+ types = []
+ sources = []
+
+ for entity in entity_list:
+ entity_type = entity.get("type") or entity.get("entity_type")
+ if entity_type:
+ types.append(entity_type)
+
+ if self.track_provenance:
+ source_ref = SourceReference(
+ document=entity.get("source", "unknown"),
+ page=entity.get("page"),
+ section=entity.get("section"),
+ confidence=entity.get("confidence", 1.0),
+ metadata=entity.get("metadata", {}),
+ )
+ self.source_tracker.track_entity_source(
+ entity_id, source_ref
+ )
+ sources.append(
+ {
+ "document": source_ref.document,
+ "page": source_ref.page,
+ "confidence": source_ref.confidence,
+ }
+ )
+
+ # Check for type conflicts
+ unique_types = list(set(str(t) for t in types if t is not None))
+
+ if len(unique_types) > 1:
+ conflict = Conflict(
+ conflict_id=f"{entity_id}_type_conflict",
+ conflict_type=ConflictType.TYPE_CONFLICT,
+ entity_id=entity_id,
+ property_name="type",
+ conflicting_values=types,
+ sources=sources,
+ confidence=self._calculate_conflict_confidence(types, sources),
+ severity=self._calculate_severity("type", types),
+ recommended_action="Review entity type definitions and classification",
+ )
+ conflicts.append(conflict)
+ self.detected_conflicts[conflict.conflict_id] = conflict
+
+ self.logger.warning(
+ f"Type conflict detected: {entity_id} has conflicting types: {unique_types}"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Detected {len(conflicts)} type conflicts",
+ )
+ return conflicts
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ def detect_temporal_conflicts(
+ self, entities: List[Dict[str, Any]]
+ ) -> List[Conflict]:
+ """
+ Detect temporal conflicts (e.g., founded year conflicts).
+
+ Args:
+ entities: List of entity dictionaries
+
+ Returns:
+ List of detected conflicts
+ """
+ tracking_id = self.progress_tracker.start_tracking(
+ file=None,
+ module="conflicts",
+ submodule="ConflictDetector",
+ message="Detecting temporal conflicts",
+ )
+
+ try:
+ conflicts = []
+
+ # Temporal property patterns
+ temporal_properties = [
+ "founded",
+ "founded_year",
+ "established",
+ "created",
+ "timestamp",
+ "date",
+ "start_date",
+ "end_date",
+ ]
+
+ # Group entities by ID
+ entity_groups: Dict[str, List[Dict[str, Any]]] = {}
+
+ for entity in entities:
+ entity_id = entity.get("id") or entity.get("entity_id")
+ if not entity_id:
+ continue
+
+ if entity_id not in entity_groups:
+ entity_groups[entity_id] = []
+ entity_groups[entity_id].append(entity)
+
+ # Check each entity group for temporal conflicts
+ for entity_id, entity_list in entity_groups.items():
+ if len(entity_list) < 2:
+ continue
+
+ # Check each temporal property
+ for prop_name in temporal_properties:
+ values = []
+ sources = []
+
+ for entity in entity_list:
+ if prop_name in entity:
+ value = entity[prop_name]
+ values.append(value)
+
+ if self.track_provenance:
+ source_ref = SourceReference(
+ document=entity.get("source", "unknown"),
+ page=entity.get("page"),
+ section=entity.get("section"),
+ confidence=entity.get("confidence", 1.0),
+ metadata=entity.get("metadata", {}),
+ )
+ self.source_tracker.track_property_source(
+ entity_id, prop_name, value, source_ref
+ )
+ sources.append(
+ {
+ "document": source_ref.document,
+ "page": source_ref.page,
+ "confidence": source_ref.confidence,
+ }
+ )
+
+ # Check for temporal conflicts
+ if len(values) > 1:
+ # Normalize values for comparison
+ normalized_values = []
+ for v in values:
+ try:
+ # Try to convert to comparable format
+ if isinstance(v, str):
+ # Try to extract year from string
+ import re
+
+ year_match = re.search(r"\b(19|20)\d{2}\b", v)
+ if year_match:
+ normalized_values.append(int(year_match.group()))
+ else:
+ normalized_values.append(v)
+ else:
+ normalized_values.append(v)
+ except (ValueError, TypeError):
+ normalized_values.append(v)
+
+ unique_values = list(
+ set(str(v) for v in normalized_values if v is not None)
+ )
+
+ if len(unique_values) > 1:
+ conflict = Conflict(
+ conflict_id=f"{entity_id}_{prop_name}_temporal_conflict",
+ conflict_type=ConflictType.TEMPORAL_CONFLICT,
+ entity_id=entity_id,
+ property_name=prop_name,
+ conflicting_values=values,
+ sources=sources,
+ confidence=self._calculate_conflict_confidence(
+ values, sources
+ ),
+ severity=self._calculate_severity(prop_name, values),
+ recommended_action="Check temporal context and determine correct time period",
+ )
+ conflicts.append(conflict)
+ self.detected_conflicts[conflict.conflict_id] = conflict
+
+ self.logger.warning(
+ f"Temporal conflict detected: {entity_id}.{prop_name} "
+ f"has conflicting values: {unique_values}"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Detected {len(conflicts)} temporal conflicts",
+ )
+ return conflicts
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ def detect_logical_conflicts(
+ self, entities: List[Dict[str, Any]]
+ ) -> List[Conflict]:
+ """
+ Detect logical conflicts (e.g., Person cannot be Organization).
+
+ Args:
+ entities: List of entity dictionaries
+
+ Returns:
+ List of detected conflicts
+ """
+ tracking_id = self.progress_tracker.start_tracking(
+ file=None,
+ module="conflicts",
+ submodule="ConflictDetector",
+ message="Detecting logical conflicts",
+ )
+
+ try:
+ conflicts = []
+
+ # Logical rules: incompatible type combinations
+ incompatible_types = {
+ "Person": ["Organization", "Company", "Institution"],
+ "Organization": ["Person"],
+ "Company": ["Person"],
+ "Location": ["Person", "Organization"],
+ }
+
+ # Group entities by ID
+ entity_groups: Dict[str, List[Dict[str, Any]]] = {}
+
+ for entity in entities:
+ entity_id = entity.get("id") or entity.get("entity_id")
+ if not entity_id:
+ continue
+
+ if entity_id not in entity_groups:
+ entity_groups[entity_id] = []
+ entity_groups[entity_id].append(entity)
+
+ # Check each entity group for logical conflicts
+ for entity_id, entity_list in entity_groups.items():
+ if len(entity_list) < 2:
+ continue
+
+ types = []
+ sources = []
+
+ for entity in entity_list:
+ entity_type = entity.get("type") or entity.get("entity_type")
+ if entity_type:
+ types.append(entity_type)
+
+ if self.track_provenance:
+ source_ref = SourceReference(
+ document=entity.get("source", "unknown"),
+ page=entity.get("page"),
+ section=entity.get("section"),
+ confidence=entity.get("confidence", 1.0),
+ metadata=entity.get("metadata", {}),
+ )
+ sources.append(
+ {
+ "document": source_ref.document,
+ "page": source_ref.page,
+ "confidence": source_ref.confidence,
+ }
+ )
+
+ # Check for logical conflicts
+ if len(types) > 1:
+ for i, type1 in enumerate(types):
+ for type2 in types[i + 1 :]:
+ type1_str = str(type1)
+ type2_str = str(type2)
+
+ # Check if types are incompatible
+ if type1_str in incompatible_types:
+ if type2_str in incompatible_types[type1_str]:
+ conflict = Conflict(
+ conflict_id=f"{entity_id}_logical_conflict",
+ conflict_type=ConflictType.LOGICAL_CONFLICT,
+ entity_id=entity_id,
+ property_name="type",
+ conflicting_values=[type1, type2],
+ sources=sources,
+ confidence=1.0, # High confidence for logical conflicts
+ severity="critical",
+ recommended_action=f"Entity cannot be both {type1_str} and {type2_str}. Review classification.",
+ )
+ conflicts.append(conflict)
+ self.detected_conflicts[
+ conflict.conflict_id
+ ] = conflict
+
+ self.logger.warning(
+ f"Logical conflict detected: {entity_id} cannot be both "
+ f"{type1_str} and {type2_str}"
+ )
+ break
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Detected {len(conflicts)} logical conflicts",
+ )
+ return conflicts
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
+ def detect_conflicts(
+ self, entities: List[Dict[str, Any]], entity_type: Optional[str] = None
+ ) -> List[Conflict]:
+ """
+ Detect all conflicts for entities (general method).
+
+ This method detects all types of conflicts: value, type, relationship,
+ temporal, and logical conflicts.
+
+ Args:
+ entities: List of entity dictionaries
+ entity_type: Optional entity type filter
+
+ Returns:
+ List of all detected conflicts
+ """
+ tracking_id = self.progress_tracker.start_tracking(
+ file=None,
+ module="conflicts",
+ submodule="ConflictDetector",
+ message="Detecting all conflicts",
+ )
+
+ try:
+ all_conflicts = []
+
+ # Filter by entity type if specified
+ filtered_entities = entities
+ if entity_type:
+ filtered_entities = [
+ e
+ for e in entities
+ if (e.get("type") or e.get("entity_type")) == entity_type
+ ]
+
+ # Detect value conflicts (for common properties)
+ if self.conflict_fields:
+ for entity_type_key, fields in self.conflict_fields.items():
+ if not entity_type or entity_type_key == entity_type:
+ for field in fields:
+ conflicts = self.detect_value_conflicts(
+ filtered_entities, field, entity_type
+ )
+ all_conflicts.extend(conflicts)
+ else:
+ # Detect entity-wide conflicts
+ conflicts = self.detect_entity_conflicts(filtered_entities, entity_type)
+ all_conflicts.extend(conflicts)
+
+ # Detect type conflicts
+ type_conflicts = self.detect_type_conflicts(filtered_entities)
+ all_conflicts.extend(type_conflicts)
+
+ # Detect temporal conflicts
+ temporal_conflicts = self.detect_temporal_conflicts(filtered_entities)
+ all_conflicts.extend(temporal_conflicts)
+
+ # Detect logical conflicts
+ logical_conflicts = self.detect_logical_conflicts(filtered_entities)
+ all_conflicts.extend(logical_conflicts)
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Detected {len(all_conflicts)} total conflicts",
+ )
+ return all_conflicts
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
+
def clear_conflicts(self) -> None:
"""Clear all detected conflicts."""
self.detected_conflicts.clear()
diff --git a/semantica/conflicts/conflict_resolver.py b/semantica/conflicts/conflict_resolver.py
index e48453bd..22fb7e7e 100644
--- a/semantica/conflicts/conflict_resolver.py
+++ b/semantica/conflicts/conflict_resolver.py
@@ -491,26 +491,3 @@ class ConflictResolver:
List of resolution results
"""
return self.resolution_history.copy()
-
- def get_resolution_statistics(self) -> Dict[str, Any]:
- """
- Get resolution statistics.
-
- Returns:
- Statistics dictionary
- """
- total = len(self.resolution_history)
- resolved = sum(1 for r in self.resolution_history if r.resolved)
-
- by_strategy = {}
- for result in self.resolution_history:
- strategy = result.resolution_strategy or "unknown"
- by_strategy[strategy] = by_strategy.get(strategy, 0) + 1
-
- return {
- "total_resolutions": total,
- "resolved_count": resolved,
- "unresolved_count": total - resolved,
- "resolution_rate": resolved / total if total > 0 else 0.0,
- "by_strategy": by_strategy,
- }
diff --git a/semantica/conflicts/conflicts_usage.md b/semantica/conflicts/conflicts_usage.md
index bd346cf3..eea02cd7 100644
--- a/semantica/conflicts/conflicts_usage.md
+++ b/semantica/conflicts/conflicts_usage.md
@@ -17,30 +17,6 @@ This guide demonstrates how to use the conflicts module for detecting, resolving
## Basic Usage
-### Using the Convenience Function
-
-```python
-from semantica.conflicts import detect_and_resolve
-
-# Sample entities with potential conflicts from multiple sources
-entities = [
- {"id": "1", "name": "Apple Inc.", "founded": 1976, "source": "doc1"},
- {"id": "1", "name": "Apple", "founded": 1976, "source": "doc2"},
- {"id": "1", "name": "Apple Inc.", "founded": 1977, "source": "doc3"},
-]
-
-# Detect and resolve conflicts in one call
-conflicts, results = detect_and_resolve(
- entities,
- property_name="name",
- detection_method="value",
- resolution_strategy="voting"
-)
-
-print(f"Found {len(conflicts)} conflicts")
-print(f"Resolved {sum(1 for r in results if r.resolved)} conflicts")
-```
-
### Using Main Classes
```python
@@ -429,9 +405,6 @@ analysis = analyze_conflicts(conflicts, method="source")
# Trend analysis
analysis = analyze_conflicts(conflicts, method="trend")
-
-# Statistical analysis
-analysis = analyze_conflicts(conflicts, method="statistics")
```
## Source Tracking
@@ -831,7 +804,7 @@ print(f"Detected {len(conflicts)} conflicts")
# Analyze conflicts
analysis = analyzer.analyze_conflicts(conflicts)
-print(f"Analysis: {analysis['statistics']}")
+print(f"Analysis: {analysis['total_conflicts']} conflicts found")
# Resolve conflicts - using string strategy
results = resolver.resolve_conflicts(
@@ -890,19 +863,18 @@ results = resolver.resolve_conflicts(conflicts)
### Batch Conflict Processing
```python
-from semantica.conflicts import detect_and_resolve
+from semantica.conflicts import ConflictDetector, ConflictResolver
# Process multiple properties
properties_to_check = ["name", "founded", "revenue", "headquarters"]
+detector = ConflictDetector()
+resolver = ConflictResolver()
+
all_results = {}
for property_name in properties_to_check:
- conflicts, results = detect_and_resolve(
- entities,
- property_name=property_name,
- detection_method="value",
- resolution_strategy="voting"
- )
+ conflicts = detector.detect_value_conflicts(entities, property_name)
+ results = resolver.resolve_conflicts(conflicts, strategy="voting")
all_results[property_name] = {
"conflicts": conflicts,
"results": results
diff --git a/semantica/conflicts/methods.py b/semantica/conflicts/methods.py
index b01e79a0..4486485a 100644
--- a/semantica/conflicts/methods.py
+++ b/semantica/conflicts/methods.py
@@ -31,7 +31,6 @@ Conflict Analysis:
- "severity": Severity-based analysis
- "source": Source-based conflict analysis
- "trend": Temporal trend identification
- - "statistics": Statistical analysis
Source Tracking:
- "property": Track sources for property values
@@ -65,10 +64,9 @@ Conflict Resolution:
Conflict Analysis:
- Pattern Identification: Frequency-based pattern detection using Counter and defaultdict
- Type Classification: Conflict type categorization and grouping
- - Severity Analysis: Severity-based grouping and statistical analysis
+ - Severity Analysis: Severity-based grouping and analysis
- Source Analysis: Source-based conflict aggregation and analysis
- Trend Analysis: Temporal trend identification using time-series analysis
- - Statistical Analysis: Conflict statistics calculation (mean, median, distribution)
Source Tracking:
- Property Source Tracking: Dictionary-based property-to-source mapping
@@ -275,7 +273,6 @@ def analyze_conflicts(
- "severity": Severity-based analysis
- "source": Source-based conflict analysis
- "trend": Temporal trend identification
- - "statistics": Statistical analysis
**kwargs: Additional options passed to ConflictAnalyzer
Returns:
@@ -308,10 +305,7 @@ def analyze_conflicts(
analysis = analyzer.analyze_conflicts(conflicts)
return {"by_source": analysis.get("by_source", {})}
elif method == "trend":
- return analyzer.analyze_trends(conflicts)
- elif method == "statistics":
- analysis = analyzer.analyze_conflicts(conflicts)
- return {"statistics": analysis.get("statistics", {})}
+ return {"trends": analyzer.analyze_trends(conflicts)}
else:
# Default to full analysis
return analyzer.analyze_conflicts(conflicts)
@@ -612,7 +606,7 @@ def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:
"manual_review",
"expert_review",
],
- "analysis": ["pattern", "type", "severity", "source", "trend", "statistics"],
+ "analysis": ["pattern", "type", "severity", "source", "trend"],
"tracking": ["property", "entity", "relationship"],
"investigation": ["guide", "checklist", "context"],
}
diff --git a/semantica/conflicts/source_tracker.py b/semantica/conflicts/source_tracker.py
index 5614c19f..bd4e33b0 100644
--- a/semantica/conflicts/source_tracker.py
+++ b/semantica/conflicts/source_tracker.py
@@ -496,3 +496,27 @@ class SourceTracker:
)
return chain
+
+ def get_all_source_credibilities(self) -> Dict[str, float]:
+ """
+ Get all source credibility scores.
+
+ Returns:
+ Dictionary mapping source document IDs to credibility scores
+ """
+ return self.source_credibility.copy()
+
+ def generate_traceability_chain(
+ self, entity_id: str, property_name: Optional[str] = None
+ ) -> List[Dict[str, Any]]:
+ """
+ Generate traceability chain for an entity or property (alias for get_traceability_chain).
+
+ Args:
+ entity_id: Entity identifier
+ property_name: Optional property name
+
+ Returns:
+ List of traceability records
+ """
+ return self.get_traceability_chain(entity_id, property_name)
\ No newline at end of file