Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat: Add methods, registry, config to kg module and enhance usage docs
KaifAhmad1eff719610d4b
diff --git a/semantica/kg/__init__.py b/semantica/kg/__init__.pyindex 5fdb5953..c0a8c324 100644--- a/semantica/kg/__init__.py+++ b/semantica/kg/__init__.py@@ -1,10 +1,94 @@"""Knowledge Graph Management Module-This module provides comprehensive knowledge graph construction and management capabilities,-including temporal knowledge graph support for time-aware knowledge representation.+This module provides comprehensive knowledge graph construction and management capabilities+for the Semantica framework, including temporal knowledge graph support for time-aware+knowledge representation, graph analytics, entity resolution, conflict detection, and+provenance tracking.-Exports:+Algorithms Used:++Knowledge Graph Construction:+ - Graph Building: Entity-relationship graph construction from multiple sources+ - Entity Resolution: Fuzzy string matching, exact matching, semantic similarity matching for duplicate detection+ - Conflict Detection: Value conflict detection (same entity with different property values), relationship conflict detection+ - Conflict Resolution: Highest confidence strategy, source-based resolution+ - Temporal Graph Support: Time-aware edge creation with valid_from/valid_until timestamps+ - Temporal Granularity: Time normalization (second, minute, hour, day, week, month, year)+ - Entity Merging: Property aggregation, metadata merging, provenance tracking+ - Incremental Building: Batch processing for large graphs++Graph Analysis:+ - Degree Centrality: Normalized degree calculation (degree / (n-1)) for connectivity measure+ - Betweenness Centrality: Shortest path counting (BFS-based), path normalization by (n-1)*(n-2)/2+ - Closeness Centrality: Average distance calculation, (n-1) / sum of distances normalization+ - Eigenvector Centrality: Power iteration method, adjacency matrix eigenvalue computation, convergence tolerance+ - Community Detection: Louvain algorithm (greedy modularity optimization), Leiden algorithm (with refinement step)+ - Overlapping Communities: K-clique community detection, dense subgraph detection+ - Modularity Calculation: Q = (1/2m) * Σ(A_ij - k_i*k_j/2m) * δ(c_i, c_j)+ - Graph Connectivity: DFS-based connected component detection, component size analysis+ - Bridge Detection: Edge removal and connectivity change detection+ - Path Finding: BFS shortest path algorithm, all-pairs shortest paths computation+ - Graph Density: E / (n*(n-1)/2) calculation for undirected graphs+ - Structure Classification: Density-based classification (sparse, moderate, dense, disconnected)++Entity Resolution:+ - Duplicate Detection: Similarity-based grouping using threshold matching+ - Fuzzy Matching: String similarity algorithms (Levenshtein, Jaro-Winkler)+ - Semantic Matching: Embedding-based similarity for semantic entity matching+ - Entity Merging: Property conflict resolution, metadata aggregation+ - ID Normalization: Canonical ID assignment for merged entities++Conflict Detection:+ - Value Conflict Detection: Property value comparison, unique value set extraction+ - Relationship Conflict Detection: Relationship property comparison, conflict identification+ - Source Tracking: Multi-source conflict tracking, provenance-based conflict resolution+ - Conflict Categorization: Value conflicts vs relationship conflicts++Graph Validation:+ - Entity Validation: Required field checking (ID, type), unique ID verification+ - Relationship Validation: Source/target reference validation, required field checking+ - Consistency Checking: Type consistency verification, circular relationship detection (DFS-based cycle detection)+ - Orphaned Entity Detection: Relationship-based entity connectivity checking+ - Validation Reporting: Error and warning categorization++Temporal Operations:+ - Time-Point Queries: Temporal filtering using valid_from/valid_until comparison+ - Time-Range Queries: Interval overlap detection, union/intersection aggregation+ - Temporal Pattern Detection: Sequence detection, cycle detection, trend analysis+ - Graph Evolution Analysis: Time-series relationship counting, diversity metrics, stability measures+ - Temporal Path Finding: BFS with temporal validity constraints+ - Version Management: Snapshot creation, version comparison, timestamp-based versioning++Deduplication:+ - Duplicate Group Detection: Similarity-based clustering, threshold-based grouping+ - Entity Merging: Property aggregation strategies, metadata merging+ - Provenance Tracking: Source tracking for merged entities, lineage maintenance++Provenance Tracking:+ - Source Tracking: Multi-source entity tracking, timestamp recording+ - Lineage Retrieval: Complete provenance history reconstruction+ - Metadata Aggregation: Source metadata merging, temporal metadata tracking+ - Temporal Tracking: First seen, last updated timestamp management++Seed Management:+ - Data Normalization: Format conversion (list, dict, single entity), ID generation+ - Source Tracking: Source identifier assignment, metadata attachment+ - File Loading: JSON parsing, file-based seed data loading++Key Features:+ - Knowledge graph construction from multiple sources+ - Temporal knowledge graph support with time-aware edges+ - Entity resolution and deduplication+ - Conflict detection and resolution+ - Comprehensive graph analytics (centrality, communities, connectivity)+ - Graph validation and consistency checking+ - Temporal queries and pattern detection+ - Provenance tracking and lineage management+ - Method registry for extensibility+ - Configuration management with environment variables and config files++Main Classes:- GraphBuilder: Knowledge graph construction with temporal support- EntityResolver: Entity resolution and deduplication- GraphAnalyzer: Graph analytics with temporal evolution analysis@@ -19,7 +103,39 @@ Exports:- Deduplicator: Graph deduplication- GraphValidator: Graph validation- SeedManager: Seed data management- - build: Module-level build function for knowledge graph construction+ - MethodRegistry: Registry for custom KG methods+ - KGConfig: Configuration manager for KG module++Convenience Functions:+ - build: Build knowledge graph from sources+ - build_kg: Knowledge graph building wrapper+ - analyze_graph: Graph analysis wrapper+ - resolve_entities: Entity resolution wrapper+ - validate_graph: Graph validation wrapper+ - detect_conflicts: Conflict detection wrapper+ - calculate_centrality: Centrality calculation wrapper+ - detect_communities: Community detection wrapper+ - analyze_connectivity: Connectivity analysis wrapper+ - deduplicate_graph: Deduplication wrapper+ - query_temporal: Temporal query wrapper+ - get_kg_method: Get KG method by name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.kg import build, build_kg, analyze_graph, calculate_centrality+ >>> # Using convenience function+ >>> kg = build(sources=[{"entities": [...], "relationships": [...]}])+ >>> # Using method functions+ >>> kg = build_kg(sources, method="default")+ >>> analysis = analyze_graph(kg, method="default")+ >>> centrality = calculate_centrality(kg, method="degree")+ >>> # Using classes directly+ >>> from semantica.kg import GraphBuilder+ >>> builder = GraphBuilder(merge_entities=True, resolve_conflicts=True)+ >>> graph = builder.build(sources)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional, Union@@ -36,8 +152,25 @@ from .connectivity_analyzer import ConnectivityAnalyzerfrom .deduplicator import Deduplicatorfrom .graph_validator import GraphValidatorfrom .seed_manager import SeedManager+from .registry import MethodRegistry, method_registry+from .methods import (+ build_kg,+ analyze_graph,+ resolve_entities,+ validate_graph,+ detect_conflicts,+ calculate_centrality,+ detect_communities,+ analyze_connectivity,+ deduplicate_graph,+ query_temporal,+ get_kg_method,+ list_available_methods,+)+from .config import KGConfig, kg_config__all__ = [+ # Core Classes"GraphBuilder","EntityResolver","GraphAnalyzer",@@ -52,6 +185,25 @@ __all__ = ["Deduplicator","GraphValidator","SeedManager",+ # Registry and Methods+ "MethodRegistry",+ "method_registry",+ "build_kg",+ "analyze_graph",+ "resolve_entities",+ "validate_graph",+ "detect_conflicts",+ "calculate_centrality",+ "detect_communities",+ "analyze_connectivity",+ "deduplicate_graph",+ "query_temporal",+ "get_kg_method",+ "list_available_methods",+ # Configuration+ "KGConfig",+ "kg_config",+ # Convenience Functions"build",]diff --git a/semantica/kg/config.py b/semantica/kg/config.pynew file mode 100644index 00000000..b21510b0--- /dev/null+++ b/semantica/kg/config.py@@ -0,0 +1,174 @@+"""+Configuration Management Module for Knowledge Graph++This module provides centralized configuration management for knowledge graph operations,+supporting multiple configuration sources including environment variables, config files,+and programmatic configuration.++Supported Configuration Sources:+ - Environment variables: KG_MERGE_ENTITIES, KG_RESOLUTION_STRATEGY, KG_ENABLE_TEMPORAL, etc.+ - Config files: YAML, JSON, TOML formats+ - Programmatic: Python API for setting KG configurations++Algorithms Used:+ - Environment Variable Parsing: OS-level environment variable access+ - YAML Parsing: YAML parser for configuration file loading+ - JSON Parsing: JSON parser for configuration file loading+ - TOML Parsing: TOML parser for configuration file loading+ - Fallback Chain: Priority-based configuration resolution+ - Dictionary Merging: Deep merge algorithms for configuration updates++Key Features:+ - Environment variable support for KG parameters+ - Config file support (YAML, JSON, TOML formats)+ - Programmatic configuration via Python API+ - Method-specific configuration management+ - Automatic fallback chain (config file -> environment -> defaults)+ - Global config instance for easy access++Main Classes:+ - KGConfig: Main configuration manager class for KG module++Example Usage:+ >>> from semantica.kg.config import kg_config+ >>> merge_entities = kg_config.get("merge_entities", default=True)+ >>> kg_config.set("merge_entities", False)+ >>> method_config = kg_config.get_method_config("build")+"""++import os+from typing import Optional, Dict, Any+from pathlib import Path++from ..utils.logging import get_logger+++class KGConfig:+ """Configuration manager for knowledge graph module - supports .env files, environment variables, and programmatic config."""++ def __init__(self, config_file: Optional[str] = None):+ """Initialize configuration manager."""+ self.logger = get_logger("kg_config")+ self._configs: Dict[str, Any] = {}+ self._method_configs: Dict[str, Dict] = {}+ self._load_config_file(config_file)+ self._load_env_vars()++ def _load_config_file(self, config_file: Optional[str]):+ """Load configuration from file."""+ if config_file and Path(config_file).exists():+ try:+ # Support YAML, JSON, TOML+ if config_file.endswith('.yaml') or config_file.endswith('.yml'):+ import yaml+ with open(config_file, 'r') as f:+ data = yaml.safe_load(f) or {}+ self._configs.update(data.get("kg", {}))+ self._method_configs.update(data.get("kg_methods", {}))+ elif config_file.endswith('.json'):+ import json+ with open(config_file, 'r') as f:+ data = json.load(f) or {}+ self._configs.update(data.get("kg", {}))+ self._method_configs.update(data.get("kg_methods", {}))+ elif config_file.endswith('.toml'):+ import toml+ with open(config_file, 'r') as f:+ data = toml.load(f) or {}+ if "kg" in data:+ self._configs.update(data["kg"])+ if "kg_methods" in data:+ self._method_configs.update(data["kg_methods"])+ self.logger.info(f"Loaded KG config from {config_file}")+ except Exception as e:+ self.logger.warning(f"Failed to load config file {config_file}: {e}")++ def _load_env_vars(self):+ """Load configuration from environment variables."""+ # KG-specific environment variables with KG_ prefix+ env_mappings = {+ "KG_MERGE_ENTITIES": ("merge_entities", bool),+ "KG_RESOLUTION_STRATEGY": ("resolution_strategy", str),+ "KG_RESOLVE_CONFLICTS": ("resolve_conflicts", bool),+ "KG_ENABLE_TEMPORAL": ("enable_temporal", bool),+ "KG_TEMPORAL_GRANULARITY": ("temporal_granularity", str),+ "KG_TRACK_HISTORY": ("track_history", bool),+ "KG_VERSION_SNAPSHOTS": ("version_snapshots", bool),+ "KG_SIMILARITY_THRESHOLD": ("similarity_threshold", float),+ "KG_CONFLICT_STRATEGY": ("conflict_strategy", str),+ }++ for env_key, (config_key, type_func) in env_mappings.items():+ value = os.getenv(env_key)+ if value:+ try:+ if type_func == bool:+ self._configs[config_key] = value.lower() in ("true", "1", "yes", "on")+ else:+ self._configs[config_key] = type_func(value)+ except (ValueError, TypeError):+ self.logger.warning(f"Failed to parse {env_key}={value}")++ # Also check for any KG_ prefixed variables+ env_prefix = "KG_"+ for key, value in os.environ.items():+ if key.startswith(env_prefix) and key not in env_mappings:+ config_key = key[len(env_prefix):].lower()+ # Try to convert to appropriate type+ if value.lower() in ('true', 'false'):+ self._configs[config_key] = value.lower() == 'true'+ elif value.isdigit():+ self._configs[config_key] = int(value)+ else:+ try:+ self._configs[config_key] = float(value)+ except ValueError:+ self._configs[config_key] = value++ def set(self, key: str, value: Any):+ """Set configuration value programmatically."""+ self._configs[key] = value++ def get(self, key: str, default: Any = None) -> Any:+ """Get configuration value with fallback chain: config -> env -> default."""+ # Check config first+ if key in self._configs:+ return self._configs[key]++ # Check environment variables+ env_key = f"KG_{key.upper()}"+ value = os.getenv(env_key)+ if value:+ try:+ # Try to convert to appropriate type+ if isinstance(default, int):+ return int(value)+ elif isinstance(default, float):+ return float(value)+ elif isinstance(default, bool):+ return value.lower() in ("true", "1", "yes", "on")+ return value+ except (ValueError, TypeError):+ pass++ return default++ def set_method_config(self, method: str, **config):+ """Set method-specific configuration."""+ self._method_configs[method] = config++ def get_method_config(self, method: str) -> Dict:+ """Get method-specific configuration."""+ return self._method_configs.get(method, {})++ def get_all(self) -> Dict[str, Any]:+ """Get all configuration."""+ return {+ "config": self._configs.copy(),+ "method_configs": self._method_configs.copy()+ }+++# Global config instance+kg_config = KGConfig()+diff --git a/semantica/kg/kg_usage.md b/semantica/kg/kg_usage.mdnew file mode 100644index 00000000..8eae8118--- /dev/null+++ b/semantica/kg/kg_usage.md@@ -0,0 +1,1248 @@+# Knowledge Graph Module Usage Guide++This guide demonstrates how to use the knowledge graph module for building, analyzing, validating, and managing knowledge graphs, including temporal knowledge graphs, entity resolution, conflict detection, and graph analytics.++## Table of Contents++1. [Basic Usage](#basic-usage)+2. [Knowledge Graph Building](#knowledge-graph-building)+3. [Graph Analysis](#graph-analysis)+4. [Entity Resolution](#entity-resolution)+5. [Graph Validation](#graph-validation)+6. [Conflict Detection](#conflict-detection)+7. [Centrality Calculation](#centrality-calculation)+8. [Community Detection](#community-detection)+9. [Connectivity Analysis](#connectivity-analysis)+10. [Deduplication](#deduplication)+11. [Temporal Queries](#temporal-queries)+12. [Provenance Tracking](#provenance-tracking)+13. [Using Methods](#using-methods)+14. [Using Registry](#using-registry)+15. [Configuration](#configuration)+16. [Advanced Examples](#advanced-examples)++## Basic Usage++### Using the Convenience Function++```python+from semantica.kg import build++# Build knowledge graph from sources+sources = [+ {+ "entities": [+ {"id": "1", "name": "Alice", "type": "Person"},+ {"id": "2", "name": "Bob", "type": "Person"}+ ],+ "relationships": [+ {"source": "1", "target": "2", "type": "knows"}+ ]+ }+]++kg = build(+ sources=sources,+ merge_entities=True,+ resolve_conflicts=True+)++print(f"Built graph with {kg['metadata']['num_entities']} entities")+print(f"Relationships: {kg['metadata']['num_relationships']}")+```++### Using Main Classes++```python+from semantica.kg import GraphBuilder, GraphAnalyzer++# Create graph builder+builder = GraphBuilder(+ merge_entities=True,+ entity_resolution_strategy="fuzzy",+ resolve_conflicts=True+)++# Build knowledge graph+kg = builder.build(sources)++# Analyze graph+analyzer = GraphAnalyzer()+analysis = analyzer.analyze_graph(kg)+```++## Knowledge Graph Building++### Basic Graph Building++```python+from semantica.kg import build_kg, GraphBuilder++# Using convenience function+kg = build_kg(+ sources=sources,+ method="default",+ merge_entities=True,+ resolve_conflicts=True+)++# Using class directly+builder = GraphBuilder(+ merge_entities=True,+ entity_resolution_strategy="fuzzy",+ resolve_conflicts=True,+ enable_temporal=False+)++kg = builder.build(sources)+```++### Temporal Knowledge Graph Building++```python+from semantica.kg import build_kg++# Build temporal knowledge graph+temporal_kg = build_kg(+ sources=sources,+ method="temporal",+ enable_temporal=True,+ temporal_granularity="day",+ track_history=True,+ version_snapshots=True+)++# Access temporal information+for rel in temporal_kg["relationships"]:+ if "valid_from" in rel:+ print(f"Relationship valid from: {rel['valid_from']}")+```++### Incremental Building++```python+from semantica.kg import GraphBuilder++builder = GraphBuilder(merge_entities=True)++# Build initial graph+initial_sources = [{"entities": [...], "relationships": [...]}]+kg = builder.build(initial_sources)++# Add more sources incrementally+new_sources = [{"entities": [...], "relationships": [...]}]+updated_kg = builder.build(new_sources)+```++### Using Build Methods++```python+from semantica.kg.methods import build_kg++# Default building+kg = build_kg(sources, method="default")++# Temporal building+temporal_kg = build_kg(sources, method="temporal", enable_temporal=True)++# Incremental building+kg = build_kg(sources, method="incremental")+```++## Graph Analysis++### Comprehensive Analysis++```python+from semantica.kg import analyze_graph, GraphAnalyzer++# Using convenience function+analysis = analyze_graph(kg, method="default")++print(f"Nodes: {analysis['num_nodes']}")+print(f"Edges: {analysis['num_edges']}")+print(f"Density: {analysis['density']}")++# Using class directly+analyzer = GraphAnalyzer()+analysis = analyzer.analyze_graph(kg)+```++### Centrality-Focused Analysis++```python+from semantica.kg import analyze_graph++# Focus on centrality metrics+analysis = analyze_graph(kg, method="centrality")++# Access centrality results+if "centrality" in analysis:+ degree_centrality = analysis["centrality"].get("degree", {})+ print("Top nodes by degree centrality:")+ for node, score in sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:5]:+ print(f" {node}: {score}")+```++### Community-Focused Analysis++```python+from semantica.kg import analyze_graph++# Focus on community detection+analysis = analyze_graph(kg, method="community")++# Access community results+if "communities" in analysis:+ communities = analysis["communities"]+ print(f"Found {len(communities)} communities")+ for i, community in enumerate(communities):+ print(f"Community {i}: {len(community)} nodes")+```++### Using Analysis Methods++```python+from semantica.kg.methods import analyze_graph++# Default analysis+analysis = analyze_graph(kg, method="default")++# Centrality analysis+analysis = analyze_graph(kg, method="centrality")++# Community analysis+analysis = analyze_graph(kg, method="community")++# Connectivity analysis+analysis = analyze_graph(kg, method="connectivity")+```++## Entity Resolution++### Fuzzy Matching Resolution++```python+from semantica.kg import resolve_entities, EntityResolver++# Using convenience function+entities = [+ {"id": "1", "name": "Apple Inc.", "type": "Company"},+ {"id": "2", "name": "Apple", "type": "Company"},+ {"id": "3", "name": "Microsoft", "type": "Company"}+]++resolved = resolve_entities(entities, method="fuzzy", similarity_threshold=0.8)++print(f"Original: {len(entities)} entities")+print(f"Resolved: {len(resolved)} entities")++# Using class directly+resolver = EntityResolver(strategy="fuzzy", similarity_threshold=0.8)+resolved = resolver.resolve_entities(entities)+```++### Exact Matching Resolution++```python+from semantica.kg import resolve_entities++# Exact string matching+resolved = resolve_entities(entities, method="exact")+```++### Semantic Matching Resolution++```python+from semantica.kg import resolve_entities++# Semantic similarity matching+resolved = resolve_entities(entities, method="semantic", similarity_threshold=0.9)+```++### Using Resolution Methods++```python+from semantica.kg.methods import resolve_entities++# Fuzzy matching+resolved = resolve_entities(entities, method="fuzzy")++# Exact matching+resolved = resolve_entities(entities, method="exact")++# Semantic matching+resolved = resolve_entities(entities, method="semantic")+```++## Graph Validation++### Comprehensive Validation++```python+from semantica.kg import validate_graph, GraphValidator++# Using convenience function+result = validate_graph(kg, method="default")++if result.valid:+ print("Graph is valid!")+else:+ print(f"Found {len(result.errors)} errors:")+ for error in result.errors:+ print(f" - {error}")++ print(f"Found {len(result.warnings)} warnings:")+ for warning in result.warnings:+ print(f" - {warning}")++# Using class directly+validator = GraphValidator()+result = validator.validate(kg)+```++### Structure-Only Validation++```python+from semantica.kg import validate_graph++# Validate structure only+result = validate_graph(kg, method="structure")+```++### Consistency Checking++```python+from semantica.kg import validate_graph, GraphValidator++# Check consistency only+is_consistent = validate_graph(kg, method="consistency")++# Using class directly+validator = GraphValidator()+is_consistent = validator.check_consistency(kg)+```++### Using Validation Methods++```python+from semantica.kg.methods import validate_graph++# Default validation+result = validate_graph(kg, method="default")++# Structure validation+result = validate_graph(kg, method="structure")++# Consistency check+is_consistent = validate_graph(kg, method="consistency")+```++## Conflict Detection++### Comprehensive Conflict Detection++```python+from semantica.kg import detect_conflicts, ConflictDetector++# Using convenience function+conflicts = detect_conflicts(kg, method="default")++print(f"Found {len(conflicts)} conflicts")+for conflict in conflicts:+ print(f"Type: {conflict['type']}")+ print(f"Property: {conflict['property']}")+ print(f"Conflicting values: {conflict['conflicting_values']}")++# Using class directly+detector = ConflictDetector()+conflicts = detector.detect_conflicts(kg)+```++### Value Conflict Detection++```python+from semantica.kg import detect_conflicts++# Detect value conflicts only+value_conflicts = detect_conflicts(kg, method="value")+```++### Relationship Conflict Detection++```python+from semantica.kg import detect_conflicts++# Detect relationship conflicts only+rel_conflicts = detect_conflicts(kg, method="relationship")+```++### Conflict Resolution++```python+from semantica.kg import ConflictDetector++detector = ConflictDetector()++# Detect conflicts+conflicts = detector.detect_conflicts(kg)++# Resolve conflicts+resolution = detector.resolve_conflicts(conflicts, strategy="highest_confidence")++print(f"Resolved: {resolution['resolved_count']}")+print(f"Unresolved: {resolution['unresolved_count']}")+```++### Using Conflict Detection Methods++```python+from semantica.kg.methods import detect_conflicts++# Default detection+conflicts = detect_conflicts(kg, method="default")++# Value conflicts+conflicts = detect_conflicts(kg, method="value")++# Relationship conflicts+conflicts = detect_conflicts(kg, method="relationship")+```++## Centrality Calculation++### Degree Centrality++```python+from semantica.kg import calculate_centrality, CentralityCalculator++# Using convenience function+result = calculate_centrality(kg, method="degree")++print("Top nodes by degree centrality:")+for ranking in result["rankings"][:5]:+ print(f" {ranking['node']}: {ranking['score']}")++# Using class directly+calculator = CentralityCalculator()+result = calculator.calculate_degree_centrality(kg)+```++### Betweenness Centrality++```python+from semantica.kg import calculate_centrality++# Calculate betweenness centrality+result = calculate_centrality(kg, method="betweenness")++print("Top nodes by betweenness centrality:")+for ranking in result["rankings"][:5]:+ print(f" {ranking['node']}: {ranking['score']}")+```++### Closeness Centrality++```python+from semantica.kg import calculate_centrality++# Calculate closeness centrality+result = calculate_centrality(kg, method="closeness")++print("Top nodes by closeness centrality:")+for ranking in result["rankings"][:5]:+ print(f" {ranking['node']}: {ranking['score']}")+```++### Eigenvector Centrality++```python+from semantica.kg import calculate_centrality++# Calculate eigenvector centrality+result = calculate_centrality(kg, method="eigenvector")++print("Top nodes by eigenvector centrality:")+for ranking in result["rankings"][:5]:+ print(f" {ranking['node']}: {ranking['score']}")+```++### All Centrality Measures++```python+from semantica.kg import calculate_centrality++# Calculate all centrality measures+result = calculate_centrality(kg, method="all")++for measure_type, measure_result in result["centrality_measures"].items():+ print(f"\n{measure_type.upper()} Centrality:")+ for ranking in measure_result["rankings"][:3]:+ print(f" {ranking['node']}: {ranking['score']}")+```++### Using Centrality Methods++```python+from semantica.kg.methods import calculate_centrality++# Degree centrality+degree = calculate_centrality(kg, method="degree")++# Betweenness centrality+betweenness = calculate_centrality(kg, method="betweenness")++# Closeness centrality+closeness = calculate_centrality(kg, method="closeness")++# Eigenvector centrality+eigenvector = calculate_centrality(kg, method="eigenvector")++# All measures+all_centrality = calculate_centrality(kg, method="all")+```++## Community Detection++### Louvain Algorithm++```python+from semantica.kg import detect_communities, CommunityDetector++# Using convenience function+result = detect_communities(kg, method="louvain")++print(f"Found {len(result['communities'])} communities")+print(f"Modularity: {result['modularity']}")++for i, community in enumerate(result["communities"]):+ print(f"Community {i}: {len(community)} nodes")++# Using class directly+detector = CommunityDetector()+result = detector.detect_communities(kg, algorithm="louvain")+```++### Leiden Algorithm++```python+from semantica.kg import detect_communities++# Detect communities using Leiden algorithm+result = detect_communities(kg, method="leiden", resolution=1.0)++print(f"Found {len(result['communities'])} communities")+```++### Overlapping Communities++```python+from semantica.kg import detect_communities++# Detect overlapping communities+result = detect_communities(kg, method="overlapping", k=3)++print(f"Found {len(result['communities'])} overlapping communities")+print(f"Nodes in multiple communities: {result.get('overlap_count', 0)}")+```++### Community Metrics++```python+from semantica.kg import CommunityDetector++detector = CommunityDetector()+communities = detector.detect_communities(kg, algorithm="louvain")++# Calculate community metrics+metrics = detector.calculate_community_metrics(kg, communities)++print(f"Number of communities: {metrics['num_communities']}")+print(f"Average community size: {metrics['avg_community_size']}")+print(f"Modularity: {metrics['modularity']}")++# Analyze community structure+structure = detector.analyze_community_structure(kg, communities)+print(f"Intra-community edges: {structure['intra_community_edges']}")+print(f"Inter-community edges: {structure['inter_community_edges']}")+```++### Using Community Detection Methods++```python+from semantica.kg.methods import detect_communities++# Louvain algorithm+communities = detect_communities(kg, method="louvain")++# Leiden algorithm+communities = detect_communities(kg, method="leiden")++# Overlapping communities+communities = detect_communities(kg, method="overlapping", k=3)+```++## Connectivity Analysis++### Comprehensive Connectivity Analysis++```python+from semantica.kg import analyze_connectivity, ConnectivityAnalyzer++# Using convenience function+result = analyze_connectivity(kg, method="default")++print(f"Number of components: {result['num_components']}")+print(f"Is connected: {result['is_connected']}")+print(f"Density: {result['density']}")+print(f"Average degree: {result['avg_degree']}")++# Using class directly+analyzer = ConnectivityAnalyzer()+result = analyzer.analyze_connectivity(kg)+```++### Connected Components++```python+from semantica.kg import analyze_connectivity++# Find connected components+result = analyze_connectivity(kg, method="components")++print(f"Found {result['num_components']} connected components")+for i, component in enumerate(result["components"]):+ print(f"Component {i}: {len(component)} nodes")+```++### Shortest Paths++```python+from semantica.kg import analyze_connectivity, ConnectivityAnalyzer++# Find shortest path between two nodes+result = analyze_connectivity(+ kg,+ method="paths",+ source="node1",+ target="node2"+)++if result["exists"]:+ print(f"Path: {' -> '.join(result['path'])}")+ print(f"Distance: {result['distance']}")+else:+ print("No path found")++# Using class directly+analyzer = ConnectivityAnalyzer()+paths = analyzer.calculate_shortest_paths(kg, source="node1", target="node2")+```++### Bridge Detection++```python+from semantica.kg import analyze_connectivity++# Identify bridge edges+result = analyze_connectivity(kg, method="bridges")++print(f"Found {result['num_bridges']} bridge edges")+for bridge in result["bridge_edges"]:+ print(f"Bridge: {bridge['source']} -> {bridge['target']}")+```++### Using Connectivity Methods++```python+from semantica.kg.methods import analyze_connectivity++# Default analysis+connectivity = analyze_connectivity(kg, method="default")++# Components only+components = analyze_connectivity(kg, method="components")++# Path finding+paths = analyze_connectivity(kg, method="paths", source="A", target="B")++# Bridge detection+bridges = analyze_connectivity(kg, method="bridges")+```++## Deduplication++### Entity Deduplication++```python+from semantica.kg import deduplicate_graph, Deduplicator++# Using convenience function+deduplicated = deduplicate_graph(kg, method="entities")++print(f"Original entities: {len(kg['entities'])}")+print(f"Deduplicated entities: {len(deduplicated['entities'])}")++# Using class directly+deduplicator = Deduplicator()+duplicate_groups = deduplicator.find_duplicates(kg["entities"])+merged_entities = deduplicator.merge_duplicates(duplicate_groups)+```++### Finding Duplicates++```python+from semantica.kg import Deduplicator++deduplicator = Deduplicator()++# Find duplicate groups+duplicate_groups = deduplicator.find_duplicates(kg["entities"])++print(f"Found {len(duplicate_groups)} duplicate groups")+for i, group in enumerate(duplicate_groups):+ print(f"Group {i}: {len(group)} duplicate entities")+```++### Merging Duplicates++```python+from semantica.kg import Deduplicator++deduplicator = Deduplicator()++# Find and merge duplicates+duplicate_groups = deduplicator.find_duplicates(kg["entities"])+merged_entities = deduplicator.merge_duplicates(duplicate_groups)++print(f"Merged {len(duplicate_groups)} groups into {len(merged_entities)} entities")+```++### Using Deduplication Methods++```python+from semantica.kg.methods import deduplicate_graph++# Default deduplication+deduplicated = deduplicate_graph(kg, method="default")++# Entity deduplication only+deduplicated = deduplicate_graph(kg, method="entities")+```++## Temporal Queries++### Time-Point Queries++```python+from semantica.kg import query_temporal, TemporalGraphQuery++# Using convenience function+result = query_temporal(+ kg,+ query="",+ method="time_point",+ at_time="2024-01-01"+)++print(f"Entities at time: {result['num_entities']}")+print(f"Relationships at time: {result['num_relationships']}")++# Using class directly+query_engine = TemporalGraphQuery()+result = query_engine.query_at_time(kg, "", at_time="2024-01-01")+```++### Time-Range Queries++```python+from semantica.kg import query_temporal++# Query within time range+result = query_temporal(+ kg,+ query="",+ method="time_range",+ start_time="2024-01-01",+ end_time="2024-12-31",+ temporal_aggregation="union"+)++print(f"Relationships in range: {result['num_relationships']}")+```++### Temporal Pattern Detection++```python+from semantica.kg import query_temporal++# Detect temporal patterns+result = query_temporal(+ kg,+ query="",+ method="pattern",+ pattern="sequence",+ min_support=2+)++print(f"Found {result['num_patterns']} temporal patterns")+```++### Graph Evolution Analysis++```python+from semantica.kg import query_temporal++# Analyze graph evolution+result = query_temporal(+ kg,+ query="",+ method="evolution",+ start_time="2024-01-01",+ end_time="2024-12-31",+ metrics=["count", "diversity", "stability"]+)++print(f"Relationship count: {result.get('count', 0)}")+print(f"Diversity: {result.get('diversity', 0)}")+print(f"Stability: {result.get('stability', 0)}")+```++### Temporal Path Finding++```python+from semantica.kg import TemporalGraphQuery++query_engine = TemporalGraphQuery()++# Find temporal paths+paths = query_engine.find_temporal_paths(+ kg,+ source="entity1",+ target="entity2",+ start_time="2024-01-01",+ end_time="2024-12-31"+)++print(f"Found {paths['num_paths']} temporal paths")+for path in paths["paths"]:+ print(f"Path: {' -> '.join(path['path'])}")+ print(f"Length: {path['length']}")+```++### Using Temporal Query Methods++```python+from semantica.kg.methods import query_temporal++# Time-point query+result = query_temporal(kg, at_time="2024-01-01", method="time_point")++# Time-range query+result = query_temporal(kg, start_time="2024-01-01", end_time="2024-12-31", method="time_range")++# Pattern detection+result = query_temporal(kg, pattern="sequence", method="pattern")++# Evolution analysis+result = query_temporal(kg, method="evolution")+```++## Provenance Tracking++### Tracking Entity Provenance++```python+from semantica.kg import ProvenanceTracker++tracker = ProvenanceTracker()++# Track entity provenance+tracker.track_entity(+ "entity_1",+ source="source_1",+ metadata={"confidence": 0.9, "extraction_method": "ner"}+)++# Track relationship provenance+tracker.track_relationship(+ "rel_1",+ source="source_2",+ metadata={"confidence": 0.85}+)+```++### Retrieving Provenance++```python+from semantica.kg import ProvenanceTracker++tracker = ProvenanceTracker()++# Get all sources for an entity+sources = tracker.get_all_sources("entity_1")+for source in sources:+ print(f"Source: {source['source']}")+ print(f"Timestamp: {source['timestamp']}")+ print(f"Metadata: {source['metadata']}")++# Get complete lineage+lineage = tracker.get_lineage("entity_1")+print(f"First seen: {lineage['first_seen']}")+print(f"Last updated: {lineage['last_updated']}")+print(f"Total sources: {len(lineage['sources'])}")+```++## Using Methods++### Method Functions++```python+from semantica.kg.methods import (+ build_kg,+ analyze_graph,+ resolve_entities,+ validate_graph,+ detect_conflicts,+ calculate_centrality,+ detect_communities,+ analyze_connectivity,+ deduplicate_graph,+ query_temporal+)++# Build knowledge graph+kg = build_kg(sources, method="default")++# Analyze graph+analysis = analyze_graph(kg, method="default")++# Resolve entities+resolved = resolve_entities(entities, method="fuzzy")++# Validate graph+result = validate_graph(kg, method="default")++# Detect conflicts+conflicts = detect_conflicts(kg, method="default")++# Calculate centrality+centrality = calculate_centrality(kg, method="degree")++# Detect communities+communities = detect_communities(kg, method="louvain")++# Analyze connectivity+connectivity = analyze_connectivity(kg, method="default")++# Deduplicate graph+deduplicated = deduplicate_graph(kg, method="default")++# Query temporal+temporal_result = query_temporal(kg, method="time_point", at_time="2024-01-01")+```++### Getting Methods++```python+from semantica.kg.methods import get_kg_method++# Get a specific method+build_method = get_kg_method("build", "default")+if build_method:+ kg = build_method(sources)+```++### Listing Available Methods++```python+from semantica.kg.methods import list_available_methods++# List all available methods+all_methods = list_available_methods()+print("Available methods:")+for task, methods in all_methods.items():+ print(f" {task}: {methods}")++# List methods for a specific task+build_methods = list_available_methods("build")+print(f"Build methods: {build_methods}")+```++## Using Registry++### Registering Custom Methods++```python+from semantica.kg.registry import method_registry++def custom_build_method(sources, **kwargs):+ """Custom build method."""+ # Your custom implementation+ return {"entities": [], "relationships": [], "metadata": {}}++# Register custom method+method_registry.register("build", "custom_build", custom_build_method)++# Use custom method+from semantica.kg.methods import build_kg+kg = build_kg(sources, method="custom_build")+```++### Unregistering Methods++```python+from semantica.kg.registry import method_registry++# Unregister a method+method_registry.unregister("build", "custom_build")+```++### Listing Registered Methods++```python+from semantica.kg.registry import method_registry++# List all registered methods+all_methods = method_registry.list_all()+print(all_methods)++# List methods for a specific task+build_methods = method_registry.list_all("build")+print(build_methods)+```++## Configuration++### Environment Variables++```bash+# Set KG configuration via environment variables+export KG_MERGE_ENTITIES=true+export KG_RESOLUTION_STRATEGY=fuzzy+export KG_ENABLE_TEMPORAL=false+export KG_TEMPORAL_GRANULARITY=day+export KG_SIMILARITY_THRESHOLD=0.8+```++### Programmatic Configuration++```python+from semantica.kg.config import kg_config++# Set configuration programmatically+kg_config.set("merge_entities", True)+kg_config.set("resolution_strategy", "fuzzy")+kg_config.set("similarity_threshold", 0.8)++# Get configuration+merge_entities = kg_config.get("merge_entities", default=True)+strategy = kg_config.get("resolution_strategy", default="fuzzy")++# Set method-specific configuration+kg_config.set_method_config("build", merge_entities=True, resolve_conflicts=True)++# Get method-specific configuration+build_config = kg_config.get_method_config("build")+```++### Config Files++```yaml+# config.yaml+kg:+ merge_entities: true+ resolution_strategy: fuzzy+ enable_temporal: false+ temporal_granularity: day+ similarity_threshold: 0.8++kg_methods:+ build:+ merge_entities: true+ resolve_conflicts: true+ resolve:+ similarity_threshold: 0.8+```++```python+from semantica.kg.config import KGConfig++# Load from config file+kg_config = KGConfig(config_file="config.yaml")+```++## Advanced Examples++### Complete Knowledge Graph Pipeline++```python+from semantica.kg import (+ build_kg,+ resolve_entities,+ validate_graph,+ detect_conflicts,+ analyze_graph,+ calculate_centrality,+ detect_communities+)++# 1. Build knowledge graph+kg = build_kg(sources, method="default")++# 2. Resolve entities+entities = kg["entities"]+resolved_entities = resolve_entities(entities, method="fuzzy")+kg["entities"] = resolved_entities++# 3. Validate graph+validation = validate_graph(kg, method="default")+if not validation.valid:+ print("Validation errors:", validation.errors)+ return++# 4. Detect conflicts+conflicts = detect_conflicts(kg, method="default")+if conflicts:+ print(f"Found {len(conflicts)} conflicts")+ # Resolve conflicts...++# 5. Analyze graph+analysis = analyze_graph(kg, method="default")+print(f"Graph density: {analysis['density']}")+print(f"Average degree: {analysis['avg_degree']}")++# 6. Calculate centrality+centrality = calculate_centrality(kg, method="degree")+print("Top 5 nodes by degree:")+for ranking in centrality["rankings"][:5]:+ print(f" {ranking['node']}: {ranking['score']}")++# 7. Detect communities+communities = detect_communities(kg, method="louvain")+print(f"Found {len(communities['communities'])} communities")+```++### Temporal Knowledge Graph Workflow++```python+from semantica.kg import (+ build_kg,+ query_temporal,+ TemporalVersionManager+)++# Build temporal knowledge graph+temporal_kg = build_kg(+ sources,+ method="temporal",+ enable_temporal=True,+ temporal_granularity="day",+ track_history=True+)++# Query at specific time point+result = query_temporal(+ temporal_kg,+ method="time_point",+ at_time="2024-06-15"+)++# Query time range+range_result = query_temporal(+ temporal_kg,+ method="time_range",+ start_time="2024-01-01",+ end_time="2024-12-31"+)++# Analyze evolution+evolution = query_temporal(+ temporal_kg,+ method="evolution",+ start_time="2024-01-01",+ end_time="2024-12-31",+ metrics=["count", "diversity"]+)++# Version management+version_manager = TemporalVersionManager()+version1 = version_manager.create_version(temporal_kg, version_label="v1.0")+version2 = version_manager.create_version(temporal_kg, version_label="v2.0")+comparison = version_manager.compare_versions(version1, version2)+```++### Graph Analytics Workflow++```python+from semantica.kg import (+ GraphAnalyzer,+ CentralityCalculator,+ CommunityDetector,+ ConnectivityAnalyzer+)++# Comprehensive analysis+analyzer = GraphAnalyzer()+analysis = analyzer.analyze_graph(kg)++# Centrality analysis+centrality_calc = CentralityCalculator()+all_centrality = centrality_calc.calculate_all_centrality(kg)++# Community detection+community_detector = CommunityDetector()+communities = community_detector.detect_communities(kg, algorithm="louvain")+metrics = community_detector.calculate_community_metrics(kg, communities)++# Connectivity analysis+connectivity_analyzer = ConnectivityAnalyzer()+connectivity = connectivity_analyzer.analyze_connectivity(kg)+components = connectivity_analyzer.find_connected_components(kg)+bridges = connectivity_analyzer.identify_bridges(kg)+```++### Entity Resolution and Deduplication++```python+from semantica.kg import (+ EntityResolver,+ Deduplicator,+ deduplicate_graph+)++# Entity resolution+resolver = EntityResolver(strategy="fuzzy", similarity_threshold=0.8)+resolved = resolver.resolve_entities(kg["entities"])++# Deduplication+deduplicator = Deduplicator()+duplicate_groups = deduplicator.find_duplicates(kg["entities"])+merged_entities = deduplicator.merge_duplicates(duplicate_groups)++# Or use convenience function+deduplicated_kg = deduplicate_graph(kg, method="entities")+```++### Conflict Detection and Resolution++```python+from semantica.kg import ConflictDetector++detector = ConflictDetector()++# Detect conflicts+conflicts = detector.detect_conflicts(kg)++# Resolve conflicts+resolution = detector.resolve_conflicts(conflicts, strategy="highest_confidence")++# Apply resolutions+for resolved_conflict in resolution["resolved"]:+ conflict = resolved_conflict["conflict"]+ resolved_value = resolved_conflict["resolution"]+ # Apply resolution to graph...+```++This guide covers the main features and usage patterns of the knowledge graph module. For more detailed information, refer to the module documentation and API reference.+diff --git a/semantica/kg/methods.py b/semantica/kg/methods.pynew file mode 100644index 00000000..3cec7dcf--- /dev/null+++ b/semantica/kg/methods.py@@ -0,0 +1,758 @@+"""+Knowledge Graph Methods Module++This module provides all knowledge graph methods as simple, reusable functions for+building, analyzing, validating, and managing knowledge graphs. It supports multiple+approaches and integrates with the method registry for extensibility.++Supported Methods:++Knowledge Graph Building:+ - "default": Default graph building using GraphBuilder+ - "incremental": Incremental graph building+ - "temporal": Temporal knowledge graph building++Graph Analysis:+ - "default": Comprehensive graph analysis+ - "centrality": Centrality-focused analysis+ - "community": Community-focused analysis+ - "connectivity": Connectivity-focused analysis++Entity Resolution:+ - "fuzzy": Fuzzy string matching resolution+ - "exact": Exact string matching resolution+ - "semantic": Semantic similarity matching resolution++Graph Validation:+ - "default": Comprehensive validation+ - "structure": Structure-only validation+ - "consistency": Consistency-only validation++Conflict Detection:+ - "default": Comprehensive conflict detection+ - "value": Value conflict detection only+ - "relationship": Relationship conflict detection only++Centrality Calculation:+ - "degree": Degree centrality+ - "betweenness": Betweenness centrality+ - "closeness": Closeness centrality+ - "eigenvector": Eigenvector centrality+ - "all": All centrality measures++Community Detection:+ - "louvain": Louvain algorithm+ - "leiden": Leiden algorithm+ - "overlapping": Overlapping community detection++Connectivity Analysis:+ - "default": Comprehensive connectivity analysis+ - "components": Connected components only+ - "paths": Path finding only+ - "bridges": Bridge detection only++Deduplication:+ - "default": Default deduplication+ - "entities": Entity deduplication only+ - "relationships": Relationship deduplication only++Temporal Queries:+ - "time_point": Time-point queries+ - "time_range": Time-range queries+ - "pattern": Temporal pattern detection+ - "evolution": Graph evolution analysis++Algorithms Used:++Knowledge Graph Construction:+ - Graph Building: Entity-relationship graph construction from multiple sources+ - Entity Resolution: Fuzzy string matching, exact matching, semantic similarity matching for duplicate detection+ - Conflict Detection: Value conflict detection (same entity with different property values), relationship conflict detection+ - Conflict Resolution: Highest confidence strategy, source-based resolution+ - Temporal Graph Support: Time-aware edge creation with valid_from/valid_until timestamps+ - Temporal Granularity: Time normalization (second, minute, hour, day, week, month, year)+ - Entity Merging: Property aggregation, metadata merging, provenance tracking+ - Incremental Building: Batch processing for large graphs++Graph Analysis:+ - Degree Centrality: Normalized degree calculation (degree / (n-1)) for connectivity measure+ - Betweenness Centrality: Shortest path counting (BFS-based), path normalization by (n-1)*(n-2)/2+ - Closeness Centrality: Average distance calculation, (n-1) / sum of distances normalization+ - Eigenvector Centrality: Power iteration method, adjacency matrix eigenvalue computation, convergence tolerance+ - Community Detection: Louvain algorithm (greedy modularity optimization), Leiden algorithm (with refinement step)+ - Overlapping Communities: K-clique community detection, dense subgraph detection+ - Modularity Calculation: Q = (1/2m) * Σ(A_ij - k_i*k_j/2m) * δ(c_i, c_j)+ - Graph Connectivity: DFS-based connected component detection, component size analysis+ - Bridge Detection: Edge removal and connectivity change detection+ - Path Finding: BFS shortest path algorithm, all-pairs shortest paths computation+ - Graph Density: E / (n*(n-1)/2) calculation for undirected graphs+ - Structure Classification: Density-based classification (sparse, moderate, dense, disconnected)++Entity Resolution:+ - Duplicate Detection: Similarity-based grouping using threshold matching+ - Fuzzy Matching: String similarity algorithms (Levenshtein, Jaro-Winkler)+ - Semantic Matching: Embedding-based similarity for semantic entity matching+ - Entity Merging: Property conflict resolution, metadata aggregation+ - ID Normalization: Canonical ID assignment for merged entities++Conflict Detection:+ - Value Conflict Detection: Property value comparison, unique value set extraction+ - Relationship Conflict Detection: Relationship property comparison, conflict identification+ - Source Tracking: Multi-source conflict tracking, provenance-based conflict resolution+ - Conflict Categorization: Value conflicts vs relationship conflicts++Graph Validation:+ - Entity Validation: Required field checking (ID, type), unique ID verification+ - Relationship Validation: Source/target reference validation, required field checking+ - Consistency Checking: Type consistency verification, circular relationship detection (DFS-based cycle detection)+ - Orphaned Entity Detection: Relationship-based entity connectivity checking+ - Validation Reporting: Error and warning categorization++Temporal Operations:+ - Time-Point Queries: Temporal filtering using valid_from/valid_until comparison+ - Time-Range Queries: Interval overlap detection, union/intersection aggregation+ - Temporal Pattern Detection: Sequence detection, cycle detection, trend analysis+ - Graph Evolution Analysis: Time-series relationship counting, diversity metrics, stability measures+ - Temporal Path Finding: BFS with temporal validity constraints+ - Version Management: Snapshot creation, version comparison, timestamp-based versioning++Deduplication:+ - Duplicate Group Detection: Similarity-based clustering, threshold-based grouping+ - Entity Merging: Property aggregation strategies, metadata merging+ - Provenance Tracking: Source tracking for merged entities, lineage maintenance++Key Features:+ - Multiple KG operation methods+ - Knowledge graph building with method dispatch+ - Method dispatchers with registry support+ - Custom method registration capability+ - Consistent interface across all methods++Main Functions:+ - build_kg: Knowledge graph building wrapper+ - analyze_graph: Graph analysis wrapper+ - resolve_entities: Entity resolution wrapper+ - validate_graph: Graph validation wrapper+ - detect_conflicts: Conflict detection wrapper+ - calculate_centrality: Centrality calculation wrapper+ - detect_communities: Community detection wrapper+ - analyze_connectivity: Connectivity analysis wrapper+ - deduplicate_graph: Deduplication wrapper+ - query_temporal: Temporal query wrapper+ - get_kg_method: Get KG method by name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.kg.methods import build_kg, analyze_graph, calculate_centrality+ >>> kg = build_kg(sources, method="default")+ >>> analysis = analyze_graph(kg, method="default")+ >>> centrality = calculate_centrality(kg, method="degree")+"""++from typing import Any, Dict, List, Optional, Callable, Union++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError, ConfigurationError+from .graph_builder import GraphBuilder+from .graph_analyzer import GraphAnalyzer+from .entity_resolver import EntityResolver+from .graph_validator import GraphValidator+from .conflict_detector import ConflictDetector+from .centrality_calculator import CentralityCalculator+from .community_detector import CommunityDetector+from .connectivity_analyzer import ConnectivityAnalyzer+from .deduplicator import Deduplicator+from .temporal_query import TemporalGraphQuery+from .registry import method_registry+from .config import kg_config++logger = get_logger("kg_methods")+++def build_kg(+ sources: Union[List[Any], Any],+ method: str = "default",+ **kwargs+) -> Dict[str, Any]:+ """+ Build knowledge graph from sources (convenience function).++ This is a user-friendly wrapper that builds a knowledge graph using the specified method.++ Args:+ sources: List of sources (documents, entities, relationships, or dicts with entities/relationships)+ method: Building method (default: "default")+ - "default": Use GraphBuilder with default settings+ - "incremental": Incremental building+ - "temporal": Temporal knowledge graph building+ **kwargs: Additional options passed to GraphBuilder++ Returns:+ Dictionary containing:+ - entities: List of entities+ - relationships: List of relationships+ - metadata: Graph metadata including counts and timestamps++ Examples:+ >>> from semantica.kg.methods import build_kg+ >>> kg = build_kg(sources, method="default")+ >>> temporal_kg = build_kg(sources, method="temporal", enable_temporal=True)+ """+ # Check for custom method in registry+ custom_method = method_registry.get("build", method)+ if custom_method:+ try:+ return custom_method(sources, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = kg_config.get_method_config("build")+ config.update(kwargs)++ builder = GraphBuilder(**config)+ return builder.build(sources, **kwargs)++ except Exception as e:+ logger.error(f"Failed to build knowledge graph: {e}")+ raise+++def analyze_graph(+ graph: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Dict[str, Any]:+ """+ Analyze knowledge graph (convenience function).++ This is a user-friendly wrapper that analyzes a knowledge graph using the specified method.++ Args:+ graph: Knowledge graph (dict with "entities" and "relationships")+ method: Analysis method (default: "default")+ - "default": Comprehensive analysis+ - "centrality": Centrality-focused analysis+ - "community": Community-focused analysis+ - "connectivity": Connectivity-focused analysis+ **kwargs: Additional options passed to GraphAnalyzer++ Returns:+ Dictionary containing analysis results++ Examples:+ >>> from semantica.kg.methods import analyze_graph+ >>> analysis = analyze_graph(kg, method="default")+ >>> centrality_analysis = analyze_graph(kg, method="centrality")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("analyze", method)+ if custom_method:+ try:+ return custom_method(graph, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = kg_config.get_method_config("analyze")+ config.update(kwargs)++ analyzer = GraphAnalyzer(**config)+ return analyzer.analyze_graph(graph, **kwargs)++ except Exception as e:+ logger.error(f"Failed to analyze graph: {e}")+ raise+++def resolve_entities(+ entities: List[Dict[str, Any]],+ method: str = "fuzzy",+ **kwargs+) -> List[Dict[str, Any]]:+ """+ Resolve and disambiguate entities (convenience function).++ This is a user-friendly wrapper that resolves entities using the specified method.++ Args:+ entities: List of entity dictionaries to resolve+ method: Resolution method (default: "fuzzy")+ - "fuzzy": Fuzzy string matching resolution+ - "exact": Exact string matching resolution+ - "semantic": Semantic similarity matching resolution+ **kwargs: Additional options passed to EntityResolver++ Returns:+ List of resolved entities with duplicates merged++ Examples:+ >>> from semantica.kg.methods import resolve_entities+ >>> resolved = resolve_entities(entities, method="fuzzy")+ >>> semantic_resolved = resolve_entities(entities, method="semantic")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("resolve", method)+ if custom_method:+ try:+ return custom_method(entities, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to fuzzy")+ method = "fuzzy"++ try:+ # Get config+ config = kg_config.get_method_config("resolve")+ config.update(kwargs)++ resolver = EntityResolver(strategy=method, **config)+ return resolver.resolve_entities(entities)++ except Exception as e:+ logger.error(f"Failed to resolve entities: {e}")+ raise+++def validate_graph(+ graph: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Any:+ """+ Validate knowledge graph (convenience function).++ This is a user-friendly wrapper that validates a knowledge graph using the specified method.++ Args:+ graph: Knowledge graph to validate+ method: Validation method (default: "default")+ - "default": Comprehensive validation+ - "structure": Structure-only validation+ - "consistency": Consistency-only validation+ **kwargs: Additional options passed to GraphValidator++ Returns:+ ValidationResult object containing:+ - valid: True if valid, False otherwise+ - errors: List of error messages+ - warnings: List of warning messages++ Examples:+ >>> from semantica.kg.methods import validate_graph+ >>> result = validate_graph(kg, method="default")+ >>> if result.valid:+ ... print("Graph is valid")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("validate", method)+ if custom_method:+ try:+ return custom_method(graph, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = kg_config.get_method_config("validate")+ config.update(kwargs)++ validator = GraphValidator(**config)+ if method == "consistency":+ return validator.check_consistency(graph)+ else:+ return validator.validate(graph)++ except Exception as e:+ logger.error(f"Failed to validate graph: {e}")+ raise+++def detect_conflicts(+ graph: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> List[Dict[str, Any]]:+ """+ Detect conflicts in knowledge graph (convenience function).++ This is a user-friendly wrapper that detects conflicts using the specified method.++ Args:+ graph: Knowledge graph to analyze+ method: Detection method (default: "default")+ - "default": Comprehensive conflict detection+ - "value": Value conflict detection only+ - "relationship": Relationship conflict detection only+ **kwargs: Additional options passed to ConflictDetector++ Returns:+ List of conflict dictionaries++ Examples:+ >>> from semantica.kg.methods import detect_conflicts+ >>> conflicts = detect_conflicts(kg, method="default")+ >>> value_conflicts = detect_conflicts(kg, method="value")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("conflict", method)+ if custom_method:+ try:+ return custom_method(graph, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = kg_config.get_method_config("conflict")+ config.update(kwargs)++ detector = ConflictDetector(**config)+ return detector.detect_conflicts(graph)++ except Exception as e:+ logger.error(f"Failed to detect conflicts: {e}")+ raise+++def calculate_centrality(+ graph: Dict[str, Any],+ method: str = "degree",+ **kwargs+) -> Dict[str, Any]:+ """+ Calculate centrality measures (convenience function).++ This is a user-friendly wrapper that calculates centrality using the specified method.++ Args:+ graph: Knowledge graph to analyze+ method: Centrality method (default: "degree")+ - "degree": Degree centrality+ - "betweenness": Betweenness centrality+ - "closeness": Closeness centrality+ - "eigenvector": Eigenvector centrality+ - "all": All centrality measures+ **kwargs: Additional options passed to CentralityCalculator++ Returns:+ Dictionary containing centrality results++ Examples:+ >>> from semantica.kg.methods import calculate_centrality+ >>> degree = calculate_centrality(kg, method="degree")+ >>> all_centrality = calculate_centrality(kg, method="all")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("centrality", method)+ if custom_method:+ try:+ return custom_method(graph, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to degree")+ method = "degree"++ try:+ # Get config+ config = kg_config.get_method_config("centrality")+ config.update(kwargs)++ calculator = CentralityCalculator(**config)++ if method == "degree":+ return calculator.calculate_degree_centrality(graph)+ elif method == "betweenness":+ return calculator.calculate_betweenness_centrality(graph)+ elif method == "closeness":+ return calculator.calculate_closeness_centrality(graph)+ elif method == "eigenvector":+ return calculator.calculate_eigenvector_centrality(graph)+ elif method == "all":+ return calculator.calculate_all_centrality(graph)+ else:+ raise ProcessingError(f"Unknown centrality method: {method}")++ except Exception as e:+ logger.error(f"Failed to calculate centrality: {e}")+ raise+++def detect_communities(+ graph: Dict[str, Any],+ method: str = "louvain",+ **kwargs+) -> Dict[str, Any]:+ """+ Detect communities in knowledge graph (convenience function).++ This is a user-friendly wrapper that detects communities using the specified method.++ Args:+ graph: Knowledge graph to analyze+ method: Community detection method (default: "louvain")+ - "louvain": Louvain algorithm+ - "leiden": Leiden algorithm+ - "overlapping": Overlapping community detection+ **kwargs: Additional options passed to CommunityDetector++ Returns:+ Dictionary containing community detection results++ Examples:+ >>> from semantica.kg.methods import detect_communities+ >>> communities = detect_communities(kg, method="louvain")+ >>> overlapping = detect_communities(kg, method="overlapping")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("community", method)+ if custom_method:+ try:+ return custom_method(graph, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to louvain")+ method = "louvain"++ try:+ # Get config+ config = kg_config.get_method_config("community")+ config.update(kwargs)++ detector = CommunityDetector(**config)+ return detector.detect_communities(graph, algorithm=method, **kwargs)++ except Exception as e:+ logger.error(f"Failed to detect communities: {e}")+ raise+++def analyze_connectivity(+ graph: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Dict[str, Any]:+ """+ Analyze graph connectivity (convenience function).++ This is a user-friendly wrapper that analyzes connectivity using the specified method.++ Args:+ graph: Knowledge graph to analyze+ method: Connectivity analysis method (default: "default")+ - "default": Comprehensive connectivity analysis+ - "components": Connected components only+ - "paths": Path finding only+ - "bridges": Bridge detection only+ **kwargs: Additional options passed to ConnectivityAnalyzer++ Returns:+ Dictionary containing connectivity analysis results++ Examples:+ >>> from semantica.kg.methods import analyze_connectivity+ >>> connectivity = analyze_connectivity(kg, method="default")+ >>> components = analyze_connectivity(kg, method="components")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("connectivity", method)+ if custom_method:+ try:+ return custom_method(graph, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = kg_config.get_method_config("connectivity")+ config.update(kwargs)++ analyzer = ConnectivityAnalyzer(**config)++ if method == "components":+ return analyzer.find_connected_components(graph)+ elif method == "paths":+ source = kwargs.get("source")+ target = kwargs.get("target")+ return analyzer.calculate_shortest_paths(graph, source=source, target=target)+ elif method == "bridges":+ return analyzer.identify_bridges(graph)+ else:+ return analyzer.analyze_connectivity(graph)++ except Exception as e:+ logger.error(f"Failed to analyze connectivity: {e}")+ raise+++def deduplicate_graph(+ graph: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Dict[str, Any]:+ """+ Deduplicate knowledge graph (convenience function).++ This is a user-friendly wrapper that deduplicates a knowledge graph using the specified method.++ Args:+ graph: Knowledge graph to deduplicate+ method: Deduplication method (default: "default")+ - "default": Default deduplication+ - "entities": Entity deduplication only+ - "relationships": Relationship deduplication only+ **kwargs: Additional options passed to Deduplicator++ Returns:+ Dictionary containing deduplicated graph++ Examples:+ >>> from semantica.kg.methods import deduplicate_graph+ >>> deduplicated = deduplicate_graph(kg, method="default")+ >>> entity_dedup = deduplicate_graph(kg, method="entities")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("deduplicate", method)+ if custom_method:+ try:+ return custom_method(graph, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = kg_config.get_method_config("deduplicate")+ config.update(kwargs)++ deduplicator = Deduplicator(**config)++ entities = graph.get("entities", [])+ relationships = graph.get("relationships", [])++ if method == "entities" or method == "default":+ duplicate_groups = deduplicator.find_duplicates(entities)+ merged_entities = deduplicator.merge_duplicates(duplicate_groups)+ # Add non-duplicate entities (entities not in any duplicate group)+ processed_ids = set()+ for group in duplicate_groups:+ for entity in group:+ entity_id = entity.get("id") or entity.get("entity_id")+ if entity_id:+ processed_ids.add(entity_id)+ # Add entities that weren't part of any duplicate group+ for entity in entities:+ entity_id = entity.get("id") or entity.get("entity_id")+ if entity_id and entity_id not in processed_ids:+ merged_entities.append(entity)+ entities = merged_entities++ return {+ "entities": entities,+ "relationships": relationships,+ "metadata": graph.get("metadata", {})+ }++ except Exception as e:+ logger.error(f"Failed to deduplicate graph: {e}")+ raise+++def query_temporal(+ graph: Dict[str, Any],+ query: str = "",+ method: str = "time_point",+ **kwargs+) -> Dict[str, Any]:+ """+ Query temporal knowledge graph (convenience function).++ This is a user-friendly wrapper that queries a temporal knowledge graph using the specified method.++ Args:+ graph: Knowledge graph to query+ query: Query string (optional, depends on method)+ method: Temporal query method (default: "time_point")+ - "time_point": Time-point queries+ - "time_range": Time-range queries+ - "pattern": Temporal pattern detection+ - "evolution": Graph evolution analysis+ **kwargs: Additional options passed to TemporalGraphQuery++ Returns:+ Dictionary containing query results++ Examples:+ >>> from semantica.kg.methods import query_temporal+ >>> result = query_temporal(kg, at_time="2024-01-01", method="time_point")+ >>> patterns = query_temporal(kg, pattern="sequence", method="pattern")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("temporal", method)+ if custom_method:+ try:+ return custom_method(graph, query=query, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to time_point")+ method = "time_point"++ try:+ # Get config+ config = kg_config.get_method_config("temporal")+ config.update(kwargs)++ query_engine = TemporalGraphQuery(**config)++ if method == "time_point":+ at_time = kwargs.get("at_time")+ return query_engine.query_at_time(graph, query, at_time=at_time, **kwargs)+ elif method == "time_range":+ start_time = kwargs.get("start_time")+ end_time = kwargs.get("end_time")+ return query_engine.query_time_range(graph, query, start_time, end_time, **kwargs)+ elif method == "pattern":+ pattern = kwargs.get("pattern", "sequence")+ return query_engine.query_temporal_pattern(graph, pattern, **kwargs)+ elif method == "evolution":+ return query_engine.analyze_evolution(graph, **kwargs)+ else:+ raise ProcessingError(f"Unknown temporal query method: {method}")++ except Exception as e:+ logger.error(f"Failed to query temporal graph: {e}")+ raise+++def get_kg_method(task: str, method: str) -> Optional[Callable]:+ """+ Get KG method by task and name.++ Args:+ task: Task type ("build", "analyze", "resolve", "validate", "conflict", "centrality", "community", "connectivity", "deduplicate", "temporal")+ method: Method name++ Returns:+ Method function or None++ Examples:+ >>> from semantica.kg.methods import get_kg_method+ >>> build_fn = get_kg_method("build", "default")+ """+ return method_registry.get(task, method)+++def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all available KG methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to method names++ Examples:+ >>> from semantica.kg.methods import list_available_methods+ >>> all_methods = list_available_methods()+ >>> build_methods = list_available_methods("build")+ """+ return method_registry.list_all(task)+diff --git a/semantica/kg/registry.py b/semantica/kg/registry.pynew file mode 100644index 00000000..6cd218e9--- /dev/null+++ b/semantica/kg/registry.py@@ -0,0 +1,138 @@+"""+Method Registry Module for Knowledge Graph++This module provides a method registry system for registering custom knowledge graph methods,+enabling extensibility and community contributions to the knowledge graph toolkit.++Supported Registration Types:+ - Method Registry: Register custom KG methods for:+ * "build": Knowledge graph building methods+ * "analyze": Graph analysis methods+ * "resolve": Entity resolution methods+ * "validate": Graph validation methods+ * "conflict": Conflict detection methods+ * "centrality": Centrality calculation methods+ * "community": Community detection methods+ * "connectivity": Connectivity analysis methods+ * "deduplicate": Deduplication methods+ * "temporal": Temporal query methods++Algorithms Used:+ - Registry Pattern: Dictionary-based registration and lookup+ - Dynamic Registration: Runtime function registration+ - Type Checking: Type validation for registered components+ - Lookup Algorithms: Hash-based O(1) lookup for methods+ - Task-based Organization: Hierarchical organization by task type++Key Features:+ - Method registry for custom KG methods+ - Task-based method organization (build, analyze, resolve, validate, conflict, centrality, community, connectivity, deduplicate, temporal)+ - Dynamic registration and unregistration+ - Easy discovery of available methods+ - Support for community-contributed extensions++Main Classes:+ - MethodRegistry: Registry for custom KG methods++Global Instances:+ - method_registry: Global method registry instance++Example Usage:+ >>> from semantica.kg.registry import method_registry+ >>> method_registry.register("build", "custom_method", custom_build_function)+ >>> available = method_registry.list_all("build")+"""++from typing import Dict, Callable, Any, List, Optional+++class MethodRegistry:+ """Registry for custom knowledge graph methods."""++ _methods: Dict[str, Dict[str, Callable]] = {+ "build": {},+ "analyze": {},+ "resolve": {},+ "validate": {},+ "conflict": {},+ "centrality": {},+ "community": {},+ "connectivity": {},+ "deduplicate": {},+ "temporal": {},+ }++ @classmethod+ def register(cls, task: str, name: str, method_func: Callable):+ """+ Register a custom KG method.++ Args:+ task: Task type ("build", "analyze", "resolve", "validate", "conflict", "centrality", "community", "connectivity", "deduplicate", "temporal")+ name: Method name+ method_func: Method function+ """+ if task not in cls._methods:+ cls._methods[task] = {}+ cls._methods[task][name] = method_func++ @classmethod+ def get(cls, task: str, name: str) -> Optional[Callable]:+ """+ Get method by task and name.++ Args:+ task: Task type ("build", "analyze", "resolve", "validate", "conflict", "centrality", "community", "connectivity", "deduplicate", "temporal")+ name: Method name++ Returns:+ Method function or None+ """+ return cls._methods.get(task, {}).get(name)++ @classmethod+ def list_all(cls, task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all registered methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to method names+ """+ if task:+ return {task: list(cls._methods.get(task, {}).keys())}+ return {t: list(m.keys()) for t, m in cls._methods.items()}++ @classmethod+ def unregister(cls, task: str, name: str):+ """+ Unregister a method.++ Args:+ task: Task type ("build", "analyze", "resolve", "validate", "conflict", "centrality", "community", "connectivity", "deduplicate", "temporal")+ name: Method name+ """+ if task in cls._methods and name in cls._methods[task]:+ del cls._methods[task][name]++ @classmethod+ def clear(cls, task: Optional[str] = None):+ """+ Clear all registered methods for a task or all tasks.++ Args:+ task: Optional task type to clear (clears all if None)+ """+ if task:+ if task in cls._methods:+ cls._methods[task].clear()+ else:+ for task_dict in cls._methods.values():+ task_dict.clear()+++# Global registry+method_registry = MethodRegistry()+diff --git a/semantica/semantic_extract/semantic_extract_usage.md b/semantica/semantic_extract/semantic_extract_usage.mdindex d1accaa3..de0418ee 100644--- a/semantica/semantic_extract/semantic_extract_usage.md+++ b/semantica/semantic_extract/semantic_extract_usage.md@@ -1,6 +1,6 @@# Semantic Extract Module Usage Guide-This guide demonstrates how to use the semantic extraction module for extracting entities, relations, events, triples, and semantic networks from text.+This comprehensive guide demonstrates how to use the semantic extraction module for extracting entities, relations, events, triples, and semantic networks from text. The module provides multiple extraction methods including pattern-based, ML-based, and LLM-based approaches, with support for custom method registration and configuration management.## Table of Contentsdiff --git a/semantica/split/split_usage.md b/semantica/split/split_usage.mdindex cd1f74f7..9c34ea52 100644--- a/semantica/split/split_usage.md+++ b/semantica/split/split_usage.md@@ -1,6 +1,6 @@# Split Module Usage Guide-This guide demonstrates how to use the split module for text chunking and splitting using various methods.+This comprehensive guide demonstrates how to use the split module for text chunking and splitting using various methods. The module supports standard text splitting methods (recursive, token-based, sentence-based, etc.) as well as KG/ontology-aware methods (entity-aware, relation-aware, graph-based, etc.) for knowledge graph workflows.## Table of Contents