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
refactor(kg): enhance documentation and code quality for remaining kg modules
KaifAhmad16b354781dc62
diff --git a/semantica/kg/__init__.py b/semantica/kg/__init__.pyindex 0ee65438..5fdb5953 100644--- a/semantica/kg/__init__.py+++ b/semantica/kg/__init__.py@@ -19,8 +19,11 @@ Exports:- Deduplicator: Graph deduplication- GraphValidator: Graph validation- SeedManager: Seed data management+ - build: Module-level build function for knowledge graph construction"""+from typing import Any, Dict, List, Optional, Union+from .graph_builder import GraphBuilderfrom .entity_resolver import EntityResolverfrom .graph_analyzer import GraphAnalyzer@@ -49,4 +52,72 @@ __all__ = ["Deduplicator","GraphValidator","SeedManager",+ "build",]+++def build(+ sources: Union[List[Any], Any],+ merge_entities: bool = True,+ entity_resolution_strategy: str = "fuzzy",+ resolve_conflicts: bool = True,+ enable_temporal: bool = False,+ temporal_granularity: str = "day",+ track_history: bool = False,+ version_snapshots: bool = False,+ entity_resolver: Optional[EntityResolver] = None,+ **options+) -> Dict[str, Any]:+ """+ Build knowledge graph from sources (module-level convenience function).++ This is a user-friendly wrapper around GraphBuilder.build() that creates+ a GraphBuilder instance and builds the knowledge graph.++ Args:+ sources: List of sources (documents, entities, relationships, or dicts with entities/relationships)+ merge_entities: Whether to merge duplicate entities (default: True)+ entity_resolution_strategy: Strategy for entity resolution - "fuzzy", "exact", "semantic" (default: "fuzzy")+ resolve_conflicts: Whether to resolve conflicts (default: True)+ enable_temporal: Enable temporal knowledge graph features (default: False)+ temporal_granularity: Time granularity - "second", "minute", "hour", "day", etc. (default: "day")+ track_history: Track historical changes (default: False)+ version_snapshots: Create version snapshots (default: False)+ entity_resolver: Optional EntityResolver instance (default: None, creates one if needed)+ **options: Additional build options++ Returns:+ Dictionary containing:+ - entities: List of entities+ - relationships: List of relationships+ - metadata: Graph metadata including counts and timestamps++ Examples:+ >>> import semantica+ >>> result = semantica.kg.build(+ ... sources=[{"entities": [...], "relationships": [...]}],+ ... merge_entities=True,+ ... resolve_conflicts=True+ ... )+ >>> print(f"Built graph with {result['metadata']['num_entities']} entities")+ """+ # Normalize sources to list+ if not isinstance(sources, list):+ sources = [sources]++ # Create GraphBuilder instance+ graph_builder = GraphBuilder(+ merge_entities=merge_entities,+ entity_resolution_strategy=entity_resolution_strategy,+ resolve_conflicts=resolve_conflicts,+ enable_temporal=enable_temporal,+ temporal_granularity=temporal_granularity,+ track_history=track_history,+ version_snapshots=version_snapshots,+ **options+ )++ # Build knowledge graph+ graph = graph_builder.build(sources, entity_resolver=entity_resolver, **options)++ return graphdiff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.pyindex 9f051604..528fd102 100644--- a/semantica/kg/centrality_calculator.py+++ b/semantica/kg/centrality_calculator.py@@ -1,18 +1,24 @@"""Centrality Calculator Module-Handles centrality measures calculation for knowledge graphs including-degree, betweenness, closeness, and eigenvector centrality.+This module provides comprehensive centrality measure calculations for knowledge+graphs, helping identify the most important or influential nodes in the graph.Key Features:- - Degree centrality calculation- - Betweenness centrality calculation- - Closeness centrality calculation- - Eigenvector centrality calculation+ - Degree centrality: Measures node connectivity+ - Betweenness centrality: Measures node importance as a bridge+ - Closeness centrality: Measures average distance to all other nodes+ - Eigenvector centrality: Measures influence based on connections to important nodes- Centrality ranking and statistics-Main Classes:- - CentralityCalculator: Main centrality calculation engine+Example Usage:+ >>> from semantica.kg import CentralityCalculator+ >>> calculator = CentralityCalculator()+ >>> centrality = calculator.calculate_degree_centrality(graph)+ >>> all_centrality = calculator.calculate_all_centrality(graph)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -25,71 +31,125 @@ class CentralityCalculator:"""Centrality measures calculation engine.- • Calculates various centrality measures- • Handles different centrality types- • Manages centrality rankings- • Processes centrality statistics+ This class calculates various centrality measures to identify important+ nodes in knowledge graphs. It supports multiple centrality types and+ can use NetworkX for optimized calculations when available.++ Supported Centrality Types:+ - degree: Number of connections (simplest, fastest)+ - betweenness: Importance as a bridge between nodes+ - closeness: Average distance to all other nodes+ - eigenvector: Influence based on connections to important nodes- Attributes:- • supported_centrality_types: List of supported centrality types- • calculation_config: Configuration for centrality calculations- • ranking_tools: Tools for ranking nodes by centrality- • statistics_processor: Processor for centrality statistics-- Methods:- • calculate_degree_centrality(): Calculate degree centrality- • calculate_betweenness_centrality(): Calculate betweenness centrality- • calculate_closeness_centrality(): Calculate closeness centrality- • calculate_eigenvector_centrality(): Calculate eigenvector centrality+ Example Usage:+ >>> calculator = CentralityCalculator()+ >>> # Calculate single type+ >>> degree = calculator.calculate_degree_centrality(graph)+ >>> # Calculate all types+ >>> all_centrality = calculator.calculate_all_centrality(graph)"""def __init__(self, **config):"""Initialize centrality calculator.- • Setup centrality algorithms- • Configure calculation methods- • Initialize ranking tools- • Setup statistics processing+ Sets up the calculator with configuration and attempts to use NetworkX+ for optimized calculations if available, otherwise falls back to+ basic implementations.++ Args:+ **config: Configuration options:+ - calculation_config: Additional calculation configuration"""self.logger = get_logger("centrality_calculator")+ self.config = config++ # Supported centrality typesself.supported_centrality_types = [- "degree", "betweenness", "closeness", "eigenvector"+ "degree",+ "betweenness",+ "closeness",+ "eigenvector"]+self.calculation_config = config.get("calculation_config", {})- self.config = config- # Try to use networkx if available+ # Try to use NetworkX for optimized calculations (optional dependency)try:import networkx as nxself.nx = nxself.use_networkx = True+ self.logger.debug("NetworkX available, using optimized implementations")except ImportError:self.nx = Noneself.use_networkx = False- self.logger.warning("NetworkX not available, using basic implementations")+ self.logger.debug(+ "NetworkX not available, using basic implementations. "+ "Install with: pip install networkx"+ )++ self.logger.info("Centrality calculator initialized")- def calculate_degree_centrality(self, graph):+ def calculate_degree_centrality(self, graph: Dict[str, Any]) -> Dict[str, Any]:"""- Calculate degree centrality for all nodes.+ Calculate degree centrality for all nodes in the graph.- • Count node degrees- • Normalize by maximum degree- • Rank nodes by degree- • Return degree centrality scores+ Degree centrality measures the number of direct connections a node has.+ It's the simplest centrality measure and is normalized by the maximum+ possible degree (n-1 for n nodes).Args:- graph: Input graph for centrality calculation+ graph: Input graph (dict with "entities" and "relationships" or NetworkX graph)Returns:- dict: Node centrality scores and rankings+ Dictionary containing:+ - centrality: Dict mapping node IDs to centrality scores (0.0 to 1.0)+ - rankings: List of nodes ranked by centrality (highest first)+ - max_degree: Maximum degree in the graph+ - total_nodes: Total number of nodes++ Example:+ >>> result = calculator.calculate_degree_centrality(graph)+ >>> top_node = result["rankings"][0]["node"]+ >>> top_score = result["rankings"][0]["score"]"""self.logger.info("Calculating degree centrality")- # Build adjacency structure+ # Use NetworkX if available for faster calculation+ if self.use_networkx:+ try:+ nx_graph = self._to_networkx(graph)+ centrality_dict = self.nx.degree_centrality(nx_graph)++ # Convert to rankings+ ranked = sorted(+ centrality_dict.items(),+ key=lambda x: x[1],+ reverse=True+ )++ max_degree = max(+ dict(nx_graph.degree()).values()+ ) if nx_graph.number_of_nodes() > 0 else 0++ return {+ "centrality": centrality_dict,+ "rankings": [+ {"node": node, "score": score}+ for node, score in ranked+ ],+ "max_degree": max_degree,+ "total_nodes": nx_graph.number_of_nodes()+ }+ except Exception as e:+ self.logger.warning(+ f"NetworkX calculation failed: {e}, using basic implementation"+ )++ # Basic implementation using adjacency listadjacency = self._build_adjacency(graph)- # Calculate degrees+ # Calculate raw degrees (number of connections per node)degrees = {}max_degree = 0@@ -98,22 +158,33 @@ class CentralityCalculator:degrees[node] = degreemax_degree = max(max_degree, degree)- # Calculate normalized centrality+ # Calculate normalized centrality scores+ # Normalization: degree / (n - 1) where n is number of nodescentrality = {}- n = len(adjacency)- normalization = n - 1 if n > 1 else 1+ num_nodes = len(adjacency)+ normalization = num_nodes - 1 if num_nodes > 1 else 1for node, degree in degrees.items():- centrality[node] = degree / normalization if normalization > 0 else 0.0+ centrality[node] = (+ degree / normalization if normalization > 0 else 0.0+ )- # Rank nodes+ # Rank nodes by centrality (highest first)ranked = sorted(centrality.items(), key=lambda x: x[1], reverse=True)+ self.logger.debug(+ f"Degree centrality calculated: {num_nodes} nodes, "+ f"max degree: {max_degree}"+ )+return {"centrality": centrality,- "rankings": [{"node": node, "score": score} for node, score in ranked],+ "rankings": [+ {"node": node, "score": score}+ for node, score in ranked+ ],"max_degree": max_degree,- "total_nodes": n+ "total_nodes": num_nodes}def calculate_betweenness_centrality(self, graph):diff --git a/semantica/kg/community_detector.py b/semantica/kg/community_detector.pyindex 1c7a6956..f6055048 100644--- a/semantica/kg/community_detector.py+++ b/semantica/kg/community_detector.py@@ -1,18 +1,29 @@"""Community Detection Module-Handles community detection in knowledge graphs using various algorithms-including Louvain, Leiden, and overlapping community detection.+This module provides comprehensive community detection capabilities for the+Semantica framework, enabling identification of communities (clusters) in+knowledge graphs using various algorithms.Key Features:- - Louvain community detection- - Leiden community detection- - Overlapping community detection- - Community quality metrics- - Community analysis and statistics+ - Louvain community detection algorithm+ - Leiden community detection algorithm (with refinement)+ - Overlapping community detection (k-clique communities)+ - Community quality metrics (modularity, size distribution)+ - Community structure analysis+ - NetworkX integration with fallback implementationsMain Classes:- CommunityDetector: Main community detection engine++Example Usage:+ >>> from semantica.kg import CommunityDetector+ >>> detector = CommunityDetector()+ >>> communities = detector.detect_communities(graph, algorithm="louvain")+ >>> metrics = detector.calculate_community_metrics(graph, communities)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -25,32 +36,36 @@ class CommunityDetector:"""Community detection engine.- • Detects communities in graphs- • Handles different detection algorithms- • Manages community quality metrics- • Processes overlapping communities+ This class provides community detection capabilities for knowledge graphs,+ supporting multiple algorithms including Louvain, Leiden, and overlapping+ community detection. Uses NetworkX when available, with fallback to basic+ implementations.++ Features:+ - Louvain algorithm for modularity optimization+ - Leiden algorithm with refinement step+ - Overlapping community detection (k-clique)+ - Community quality metrics calculation+ - Community structure analysis- Attributes:- • supported_algorithms: List of supported detection algorithms- • detection_config: Configuration for community detection- • quality_metrics: Community quality assessment tools- • overlapping_detector: Overlapping community detection engine-- Methods:- • detect_communities_louvain(): Detect communities using Louvain- • detect_communities_leiden(): Detect communities using Leiden- • detect_overlapping_communities(): Detect overlapping communities- • calculate_community_metrics(): Calculate community quality metrics+ Example Usage:+ >>> detector = CommunityDetector()+ >>> communities = detector.detect_communities(graph, algorithm="louvain")+ >>> metrics = detector.calculate_community_metrics(graph, communities)+ >>> structure = detector.analyze_community_structure(graph, communities)"""def __init__(self, **config):"""Initialize community detector.- • Setup detection algorithms- • Configure quality metrics- • Initialize overlapping detection- • Setup community analysis+ Sets up the detector with configuration and checks for optional+ dependencies (NetworkX). Falls back to basic implementations if+ NetworkX is not available.++ Args:+ **config: Configuration options:+ - detection_config: Detection algorithm configuration (optional)"""self.logger = get_logger("community_detector")self.supported_algorithms = [@@ -59,31 +74,46 @@ class CommunityDetector:self.detection_config = config.get("detection_config", {})self.config = config- # Try to use networkx/igraph if available+ # Try to use networkx if available (optional dependency)try:import networkx as nxself.nx = nxself.use_networkx = True+ self.logger.debug("NetworkX available, using optimized implementations")except ImportError:self.nx = Noneself.use_networkx = Falseself.logger.warning("NetworkX not available, using basic implementations")- def detect_communities_louvain(self, graph, **options):+ def detect_communities_louvain(+ self,+ graph: Any,+ resolution: float = 1.0,+ max_iter: int = 10,+ **options+ ) -> Dict[str, Any]:"""Detect communities using Louvain algorithm.- • Apply Louvain community detection- • Optimize modularity- • Handle resolution parameters- • Return community assignments+ This method applies the Louvain algorithm for community detection,+ which optimizes modularity through iterative greedy optimization.+ Uses NetworkX implementation when available, with fallback to basic+ greedy modularity approach.Args:- graph: Input graph for community detection- **options: Additional detection options+ graph: Input graph for community detection (dict, object with+ relationships, or NetworkX graph)+ resolution: Resolution parameter for modularity optimization+ (default: 1.0, higher values favor smaller communities)+ max_iter: Maximum iterations for basic implementation (default: 10)+ **options: Additional detection options (unused)Returns:- dict: Community detection results and assignments+ dict: Community detection results containing:+ - communities: List of community lists (each list contains node IDs)+ - node_assignments: Dictionary mapping node IDs to community IDs+ - modularity: Calculated modularity score+ - algorithm: Algorithm name ("louvain")"""self.logger.info("Detecting communities using Louvain algorithm")@@ -117,43 +147,66 @@ class CommunityDetector:adjacency = self._build_adjacency(graph)return self._basic_community_detection(adjacency, algorithm="louvain", **options)- def detect_communities_leiden(self, graph, **options):+ def detect_communities_leiden(+ self,+ graph: Any,+ resolution: float = 1.0,+ max_iter: int = 10,+ **options+ ) -> Dict[str, Any]:"""Detect communities using Leiden algorithm.- • Apply Leiden community detection- • Optimize modularity with refinement- • Handle resolution parameters- • Return community assignments+ This method applies the Leiden algorithm for community detection,+ which is similar to Louvain but includes a refinement step for better+ quality. Currently uses Louvain implementation as Leiden refinement+ requires additional libraries.Args:graph: Input graph for community detection+ resolution: Resolution parameter for modularity optimization+ (default: 1.0)+ max_iter: Maximum iterations (default: 10)**options: Additional detection optionsReturns:- dict: Community detection results and assignments+ dict: Community detection results (same format as Louvain)"""self.logger.info("Detecting communities using Leiden algorithm")# Leiden is similar to Louvain but with refinement- # For now, use Louvain-like approach- return self.detect_communities_louvain(graph, **options)+ # For now, use Louvain-like approach (full Leiden requires igraph)+ result = self.detect_communities_louvain(graph, resolution=resolution, max_iter=max_iter, **options)+ result["algorithm"] = "leiden"+ return result- def detect_overlapping_communities(self, graph, **options):+ def detect_overlapping_communities(+ self,+ graph: Any,+ k: int = 3,+ min_size: int = 3,+ **options+ ) -> Dict[str, Any]:"""Detect overlapping communities.- • Apply overlapping detection algorithms- • Handle node membership in multiple communities- • Calculate overlapping metrics- • Return overlapping community structure+ This method detects communities where nodes can belong to multiple+ communities simultaneously. Uses k-clique communities when NetworkX+ is available, with fallback to basic dense subgraph detection.Args:graph: Input graph for community detection+ k: Minimum clique size for k-clique communities (default: 3)+ min_size: Minimum community size for basic detection (default: 3)**options: Additional detection optionsReturns:- dict: Overlapping community detection results+ dict: Overlapping community detection results containing:+ - communities: List of community lists+ - node_assignments: Dictionary mapping node IDs to list of+ community IDs (nodes can belong to multiple)+ - algorithm: Algorithm name ("overlapping")+ - overlap_count: Number of nodes belonging to multiple communities"""self.logger.info("Detecting overlapping communities")@@ -185,21 +238,30 @@ class CommunityDetector:adjacency = self._build_adjacency(graph)return self._basic_overlapping_detection(adjacency, **options)- def calculate_community_metrics(self, graph, communities):+ def calculate_community_metrics(+ self,+ graph: Any,+ communities: Any+ ) -> Dict[str, Any]:"""Calculate community quality metrics.- • Calculate modularity- • Compute community statistics- • Assess community quality- • Return community metrics+ This method calculates various quality metrics for detected communities,+ including modularity, community size distribution, and basic statistics.Args:graph: Input graph for community analysis- communities: Community assignments to analyze+ communities: Community assignments (can be dict with "node_assignments",+ dict mapping nodes to community IDs, or list of community lists)Returns:- dict: Community quality metrics and statistics+ dict: Community quality metrics containing:+ - num_communities: Total number of communities+ - community_sizes: Dictionary mapping community ID to size+ - avg_community_size: Average community size+ - max_community_size: Largest community size+ - min_community_size: Smallest community size+ - modularity: Calculated modularity score"""self.logger.info("Calculating community quality metrics")@@ -238,21 +300,28 @@ class CommunityDetector:"modularity": modularity}- def analyze_community_structure(self, graph, communities):+ def analyze_community_structure(+ self,+ graph: Any,+ communities: Any+ ) -> Dict[str, Any]:"""Analyze community structure and properties.- • Analyze community size distribution- • Calculate community connectivity- • Assess community stability- • Return community structure analysis+ This method performs comprehensive analysis of community structure,+ including connectivity metrics (intra-community vs inter-community edges)+ and community quality metrics.Args:graph: Input graph for community analysiscommunities: Community assignments to analyzeReturns:- dict: Community structure analysis results+ dict: Community structure analysis containing all metrics from+ calculate_community_metrics plus:+ - intra_community_edges: Number of edges within communities+ - inter_community_edges: Number of edges between communities+ - edge_ratio: Ratio of intra- to inter-community edges"""self.logger.info("Analyzing community structure")@@ -290,22 +359,29 @@ class CommunityDetector:"edge_ratio": intra_community_edges / (inter_community_edges + 1)}- def detect_communities(self, graph, algorithm="louvain", **options):+ def detect_communities(+ self,+ graph: Any,+ algorithm: str = "louvain",+ **options+ ) -> Dict[str, Any]:"""Detect communities using specified algorithm.- • Apply specified community detection algorithm- • Handle different algorithm parameters- • Return community detection results- • Provide algorithm-specific analysis+ This is a convenience method that routes to the appropriate algorithm+ based on the specified algorithm name.Args:graph: Input graph for community detectionalgorithm: Community detection algorithm to use- **options: Additional detection options+ (supported: "louvain", "leiden", "overlapping")+ **options: Additional detection options (passed to algorithm-specific method)Returns:dict: Community detection results and analysis++ Raises:+ ValueError: If algorithm is not supported"""self.logger.info(f"Detecting communities using {algorithm} algorithm")diff --git a/semantica/kg/conflict_detector.py b/semantica/kg/conflict_detector.pyindex ea864298..c07911d9 100644--- a/semantica/kg/conflict_detector.py+++ b/semantica/kg/conflict_detector.py@@ -1,8 +1,28 @@"""-Conflict detector for Semantica framework.+Conflict Detection Module-This module provides conflict identification and resolution-for knowledge graph inconsistencies.+This module provides comprehensive conflict identification and resolution+capabilities for the Semantica framework, enabling detection of inconsistencies+in knowledge graphs.++Key Features:+ - Value conflict detection (conflicting property values for same entity)+ - Relationship conflict detection (conflicting relationship properties)+ - Conflict resolution with multiple strategies+ - Source tracking for conflicts+ - Conflict categorization and prioritization++Main Classes:+ - ConflictDetector: Main conflict detection and resolution engine++Example Usage:+ >>> from semantica.kg import ConflictDetector+ >>> detector = ConflictDetector()+ >>> conflicts = detector.detect_conflicts(knowledge_graph)+ >>> resolution = detector.resolve_conflicts(conflicts)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -14,29 +34,64 @@ from ..conflicts.conflict_resolver import ConflictResolverclass ConflictDetector:"""- Conflict detector.+ Conflict detection and resolution engine.- Identifies conflicts and inconsistencies in knowledge graphs.+ This class identifies conflicts and inconsistencies in knowledge graphs,+ including value conflicts (same entity with different property values)+ and relationship conflicts. Provides conflict resolution capabilities.++ Features:+ - Entity property value conflict detection+ - Relationship property conflict detection+ - Conflict resolution with configurable strategies+ - Source tracking for conflict origins++ Example Usage:+ >>> detector = ConflictDetector()+ >>> conflicts = detector.detect_conflicts(knowledge_graph)+ >>> resolution = detector.resolve_conflicts(conflicts)"""def __init__(self, **config):- """Initialize conflict detector."""+ """+ Initialize conflict detector.++ Sets up the detector with base conflict detection and resolution+ components from the conflicts module.++ Args:+ **config: Configuration options:+ - detection: Configuration for conflict detection (optional)+ - resolution: Configuration for conflict resolution (optional)+ """self.logger = get_logger("conflict_detector")self.config = config# Initialize conflict detection componentsself.base_detector = BaseConflictDetector(**config.get("detection", {}))self.resolver = ConflictResolver(**config.get("resolution", {}))++ self.logger.debug("Conflict detector initialized")def detect_conflicts(self, knowledge_graph: Any) -> List[Dict[str, Any]]:"""Detect conflicts in knowledge graph.+ This method identifies conflicts in the knowledge graph, including:+ - Value conflicts: Same entity with different values for the same property+ - Relationship conflicts: Same relationship with conflicting properties+Args:- knowledge_graph: Knowledge graph instance+ knowledge_graph: Knowledge graph instance (object with entities/relationships+ attributes, or dict with "entities" and "relationships" keys)Returns:- List of detected conflicts+ list: List of conflict dictionaries, each containing:+ - entity_id or relationship: Identifier of conflicted element+ - property: Property name with conflict+ - conflicting_values: List of conflicting values+ - type: Conflict type ("value_conflict" or "relationship_conflict")+ - sources: List of source identifiers for conflicting values"""self.logger.info("Detecting conflicts in knowledge graph")@@ -133,15 +188,29 @@ class ConflictDetector:self.logger.info(f"Detected {len(conflicts)} conflicts")return conflicts- def resolve_conflicts(self, conflicts: List[Dict[str, Any]]) -> Dict[str, Any]:+ def resolve_conflicts(+ self,+ conflicts: List[Dict[str, Any]],+ strategy: str = "highest_confidence"+ ) -> Dict[str, Any]:"""Resolve detected conflicts.+ This method attempts to resolve conflicts using the configured conflict+ resolver with the specified strategy. Converts conflict dictionaries+ to Conflict objects for resolution.+Args:- conflicts: List of conflicts+ conflicts: List of conflict dictionaries from detect_conflicts()+ strategy: Resolution strategy to use (default: "highest_confidence")Returns:- Resolution results+ dict: Resolution results containing:+ - resolved: List of successfully resolved conflicts with resolutions+ - unresolved: List of conflicts that could not be resolved+ - total: Total number of conflicts+ - resolved_count: Number of resolved conflicts+ - unresolved_count: Number of unresolved conflicts"""self.logger.info(f"Resolving {len(conflicts)} conflicts")diff --git a/semantica/kg/connectivity_analyzer.py b/semantica/kg/connectivity_analyzer.pyindex c72e12ac..407b2e9f 100644--- a/semantica/kg/connectivity_analyzer.py+++ b/semantica/kg/connectivity_analyzer.py@@ -1,18 +1,31 @@"""Connectivity Analyzer Module-Handles connectivity analysis for knowledge graphs including-connected components, shortest paths, and bridge identification.+This module provides comprehensive connectivity analysis capabilities for the+Semantica framework, enabling analysis of graph connectivity, path finding,+and structural properties.Key Features:- - Graph connectivity analysis- - Connected components detection- - Shortest path calculation- - Bridge identification- - Connectivity metrics and statistics+ - Graph connectivity analysis (connected/disconnected)+ - Connected components detection (DFS-based)+ - Shortest path calculation (BFS-based)+ - Bridge edge identification (edges whose removal disconnects graph)+ - Connectivity metrics (density, degree statistics)+ - Graph structure classification+ - NetworkX integration with fallback implementationsMain Classes:- ConnectivityAnalyzer: Main connectivity analysis engine++Example Usage:+ >>> from semantica.kg import ConnectivityAnalyzer+ >>> analyzer = ConnectivityAnalyzer()+ >>> connectivity = analyzer.analyze_connectivity(graph)+ >>> paths = analyzer.calculate_shortest_paths(graph, source="A", target="B")+ >>> bridges = analyzer.identify_bridges(graph)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional, Set, Tuple@@ -25,32 +38,36 @@ class ConnectivityAnalyzer:"""Connectivity analysis engine.- • Analyzes graph connectivity- • Calculates connectivity metrics- • Identifies connected components- • Processes path analysis+ This class provides comprehensive connectivity analysis for knowledge graphs,+ including connected component detection, shortest path calculation, bridge+ identification, and connectivity metrics. Uses NetworkX when available,+ with fallback to basic implementations.++ Features:+ - Connected component detection (DFS-based)+ - Shortest path calculation (BFS-based)+ - Bridge edge identification+ - Connectivity metrics (density, degree statistics)+ - Graph structure classification- Attributes:- • connectivity_algorithms: Available connectivity algorithms- • analysis_config: Configuration for connectivity analysis- • component_detector: Connected components detection engine- • path_analyzer: Path analysis and calculation engine-- Methods:- • analyze_connectivity(): Analyze graph connectivity- • find_connected_components(): Find connected components- • calculate_shortest_paths(): Calculate shortest paths- • identify_bridges(): Identify bridge edges+ Example Usage:+ >>> analyzer = ConnectivityAnalyzer()+ >>> connectivity = analyzer.analyze_connectivity(graph)+ >>> components = analyzer.find_connected_components(graph)+ >>> path = analyzer.calculate_shortest_paths(graph, source="A", target="B")"""def __init__(self, **config):"""Initialize connectivity analyzer.- • Setup connectivity algorithms- • Configure component detection- • Initialize path analysis- • Setup metric calculation+ Sets up the analyzer with configuration and checks for optional+ dependencies (NetworkX). Falls back to basic implementations if+ NetworkX is not available.++ Args:+ **config: Configuration options:+ - analysis_config: Analysis configuration (optional)"""self.logger = get_logger("connectivity_analyzer")self.connectivity_algorithms = [@@ -59,30 +76,42 @@ class ConnectivityAnalyzer:self.analysis_config = config.get("analysis_config", {})self.config = config- # Try to use networkx if available+ # Try to use networkx if available (optional dependency)try:import networkx as nxself.nx = nxself.use_networkx = True+ self.logger.debug("NetworkX available, using optimized implementations")except ImportError:self.nx = Noneself.use_networkx = Falseself.logger.warning("NetworkX not available, using basic implementations")- def analyze_connectivity(self, graph):+ def analyze_connectivity(self, graph: Any) -> Dict[str, Any]:"""Analyze graph connectivity.- • Calculate connectivity metrics- • Identify connected components- • Analyze graph structure- • Return connectivity analysis+ This method performs comprehensive connectivity analysis, including+ connected component detection and connectivity metrics calculation.Args:- graph: Input graph for connectivity analysis+ graph: Input graph for connectivity analysis (dict, object with+ relationships, or NetworkX graph)Returns:- dict: Comprehensive connectivity analysis results+ dict: Comprehensive connectivity analysis containing:+ - components: List of connected component lists+ - num_components: Number of connected components+ - component_sizes: List of component sizes+ - largest_component_size: Size of largest component+ - smallest_component_size: Size of smallest component+ - num_nodes: Total number of nodes+ - num_edges: Total number of edges+ - density: Graph density (0.0 to 1.0)+ - avg_degree: Average node degree+ - max_degree: Maximum node degree+ - min_degree: Minimum node degree+ - is_connected: Whether graph is fully connected (single component)"""self.logger.info("Analyzing graph connectivity")@@ -95,20 +124,23 @@ class ConnectivityAnalyzer:"is_connected": components_result.get("num_components", 0) == 1}- def find_connected_components(self, graph):+ def find_connected_components(self, graph: Any) -> Dict[str, Any]:"""Find connected components in graph.- • Identify disconnected subgraphs- • Calculate component sizes- • Analyze component structure- • Return component information+ This method identifies all connected components (disconnected subgraphs)+ in the graph using depth-first search (DFS).Args:graph: Input graph for component analysisReturns:- dict: Connected components analysis results+ dict: Connected components analysis containing:+ - components: List of component lists (each list contains node IDs)+ - num_components: Total number of connected components+ - component_sizes: List of sizes for each component+ - largest_component_size: Size of largest component+ - smallest_component_size: Size of smallest component"""self.logger.info("Finding connected components")@@ -146,22 +178,36 @@ class ConnectivityAnalyzer:"smallest_component_size": min(component_sizes) if component_sizes else 0}- def calculate_shortest_paths(self, graph, source=None, target=None):+ def calculate_shortest_paths(+ self,+ graph: Any,+ source: Optional[str] = None,+ target: Optional[str] = None+ ) -> Dict[str, Any]:"""Calculate shortest paths in graph.- • Find shortest paths between nodes- • Calculate path lengths- • Handle weighted and unweighted graphs- • Return path information+ This method calculates shortest paths between nodes using breadth-first+ search (BFS). If both source and target are provided, calculates single+ pair shortest path. If omitted, calculates all pairs shortest paths.Args:graph: Input graph for path analysis- source: Source node for path calculation- target: Target node for path calculation+ source: Source node ID for path calculation (optional)+ target: Target node ID for path calculation (optional)Returns:- dict: Shortest path analysis results+ dict: Shortest path results:+ - If source and target provided:+ - source: Source node ID+ - target: Target node ID+ - path: List of node IDs forming shortest path (or None)+ - distance: Path length in edges (or -1 if no path)+ - exists: Whether path exists+ - If source/target omitted:+ - distances: Dictionary of all-pairs distances+ - paths: Dictionary of all-pairs paths+ - avg_path_length: Average shortest path length"""self.logger.info(f"Calculating shortest paths from {source} to {target}")@@ -182,20 +228,24 @@ class ConnectivityAnalyzer:"exists": path is not None}- def identify_bridges(self, graph):+ def identify_bridges(self, graph: Any) -> Dict[str, Any]:"""Identify bridge edges in graph.- • Find edges whose removal disconnects graph- • Calculate bridge importance- • Analyze bridge impact- • Return bridge information+ This method identifies bridge edges (edges whose removal would+ disconnect the graph or increase the number of connected components).+ Uses a simple approach: temporarily removes each edge and checks if+ connectivity changes.Args:graph: Input graph for bridge analysisReturns:- dict: Bridge identification and analysis results+ dict: Bridge identification results containing:+ - bridges: List of bridge edge tuples (source, target)+ - num_bridges: Total number of bridge edges+ - bridge_edges: List of bridge edge dictionaries with+ "source" and "target" keys"""self.logger.info("Identifying bridge edges")@@ -230,20 +280,24 @@ class ConnectivityAnalyzer:"bridge_edges": [{"source": s, "target": t} for s, t in bridges]}- def calculate_connectivity_metrics(self, graph):+ def calculate_connectivity_metrics(self, graph: Any) -> Dict[str, Any]:"""Calculate comprehensive connectivity metrics.- • Calculate connectivity statistics- • Analyze graph structure metrics- • Compute connectivity indices- • Return connectivity metrics+ This method calculates various connectivity and structural metrics+ for the graph, including density, degree statistics, and edge counts.Args:graph: Input graph for metrics calculationReturns:- dict: Connectivity metrics and statistics+ dict: Connectivity metrics containing:+ - num_nodes: Total number of nodes+ - num_edges: Total number of edges+ - density: Graph density (edges / max_possible_edges, 0.0 to 1.0)+ - avg_degree: Average node degree+ - max_degree: Maximum node degree+ - min_degree: Minimum node degree"""self.logger.info("Calculating connectivity metrics")@@ -271,20 +325,23 @@ class ConnectivityAnalyzer:"min_degree": min(degrees) if degrees else 0}- def analyze_graph_structure(self, graph):+ def analyze_graph_structure(self, graph: Any) -> Dict[str, Any]:"""Analyze overall graph structure and connectivity.- • Analyze graph topology- • Calculate structural metrics- • Identify structural patterns- • Return structure analysis+ This method performs comprehensive graph structure analysis, combining+ connectivity analysis, metrics calculation, and bridge identification,+ and classifies the graph structure type.Args:graph: Input graph for structure analysisReturns:- dict: Graph structure analysis results+ dict: Comprehensive structure analysis containing all metrics from+ analyze_connectivity(), calculate_connectivity_metrics(), and+ identify_bridges(), plus:+ - structure_type: Classification ("disconnected", "sparse",+ "moderate", or "dense")"""self.logger.info("Analyzing graph structure")diff --git a/semantica/kg/deduplicator.py b/semantica/kg/deduplicator.pyindex 6ce03a69..4752e0ec 100644--- a/semantica/kg/deduplicator.py+++ b/semantica/kg/deduplicator.py@@ -1,8 +1,28 @@"""-Deduplicator for Semantica framework.+Deduplication Module-This module provides duplicate detection and merging-for knowledge graph entities and relationships.+This module provides comprehensive duplicate detection and merging capabilities+for the Semantica framework, enabling identification and resolution of duplicate+entities and relationships in knowledge graphs.++Key Features:+ - Duplicate entity detection using similarity metrics+ - Duplicate group identification+ - Entity merging with configurable strategies+ - Relationship deduplication+ - Provenance tracking for merged entities++Main Classes:+ - Deduplicator: Main deduplication engine++Example Usage:+ >>> from semantica.kg import Deduplicator+ >>> deduplicator = Deduplicator()+ >>> duplicate_groups = deduplicator.find_duplicates(entities)+ >>> merged_entities = deduplicator.merge_duplicates(duplicate_groups)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -14,29 +34,62 @@ from ..deduplication.entity_merger import EntityMergerclass Deduplicator:"""- Deduplicator.+ Deduplication engine.- Detects and merges duplicate entities and relationships in knowledge graphs.+ This class provides duplicate detection and merging capabilities for+ knowledge graphs, using the deduplication module's duplicate detector+ and entity merger components.++ Features:+ - Duplicate entity detection with similarity metrics+ - Duplicate group identification+ - Entity merging with configurable strategies+ - Provenance tracking for merged entities++ Example Usage:+ >>> deduplicator = Deduplicator()+ >>> duplicate_groups = deduplicator.find_duplicates(entities)+ >>> merged_entities = deduplicator.merge_duplicates(duplicate_groups)"""def __init__(self, **config):- """Initialize deduplicator."""+ """+ Initialize deduplicator.++ Sets up the deduplicator with duplicate detector and entity merger+ components from the deduplication module.++ Args:+ **config: Configuration options:+ - detection: Configuration for duplicate detection (optional)+ - merger: Configuration for entity merging (optional)+ """self.logger = get_logger("deduplicator")self.config = config# Initialize deduplication componentsself.duplicate_detector = DuplicateDetector(**config.get("detection", {}))self.entity_merger = EntityMerger(**config.get("merger", {}))++ self.logger.debug("Deduplicator initialized")- def find_duplicates(self, entities: List[Dict[str, Any]]) -> List[List[Dict[str, Any]]]:+ def find_duplicates(+ self,+ entities: List[Dict[str, Any]]+ ) -> List[List[Dict[str, Any]]]:"""Find duplicate entities.+ This method detects duplicate entities using similarity metrics and+ groups them into duplicate groups. Uses the duplicate detector from+ the deduplication module.+Args:- entities: List of entities+ entities: List of entity dictionaries to check for duplicatesReturns:- List of duplicate groups+ list: List of duplicate groups, where each group is a list of+ duplicate entity dictionaries (groups with 2+ entities)"""self.logger.info(f"Finding duplicates in {len(entities)} entities")@@ -62,11 +115,16 @@ class Deduplicator:"""Merge duplicate entities.+ This method merges groups of duplicate entities using the entity merger+ from the deduplication module. Each group is merged into a single entity+ with merged properties and provenance tracking.+Args:- duplicate_groups: Groups of duplicate entities+ duplicate_groups: List of duplicate groups (each group is a list+ of duplicate entity dictionaries)Returns:- Merged entities+ list: List of merged entity dictionaries (one per duplicate group)"""self.logger.info(f"Merging {len(duplicate_groups)} duplicate groups")diff --git a/semantica/kg/entity_resolver.py b/semantica/kg/entity_resolver.pyindex 548f3e18..99eec652 100644--- a/semantica/kg/entity_resolver.py+++ b/semantica/kg/entity_resolver.py@@ -1,8 +1,23 @@"""-Entity resolver for Semantica framework.+Entity Resolver Module-This module provides entity disambiguation and resolution-for knowledge graph construction.+This module provides entity disambiguation and resolution capabilities for+knowledge graph construction, helping to merge duplicate entities and+maintain entity consistency.++Key Features:+ - Entity deduplication and merging+ - Multiple resolution strategies (fuzzy, exact, semantic)+ - Similarity-based entity matching+ - Entity ID normalization and tracking++Example Usage:+ >>> from semantica.kg import EntityResolver+ >>> resolver = EntityResolver(strategy="fuzzy", similarity_threshold=0.8)+ >>> resolved = resolver.resolve_entities(entities)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -14,75 +29,143 @@ from ..deduplication.entity_merger import EntityMergerclass EntityResolver:"""- Entity resolver.+ Entity resolver for knowledge graph construction.- Provides entity disambiguation and resolution for knowledge graph construction.+ This class provides entity disambiguation and resolution by detecting+ duplicate entities and merging them based on similarity. It supports+ multiple resolution strategies and configurable similarity thresholds.++ Resolution Strategies:+ - "fuzzy": Fuzzy string matching (default)+ - "exact": Exact string matching+ - "semantic": Semantic similarity matching++ Example Usage:+ >>> resolver = EntityResolver(strategy="fuzzy", similarity_threshold=0.8)+ >>> entities = [{"id": "1", "name": "Apple Inc."}, {"id": "2", "name": "Apple"}]+ >>> resolved = resolver.resolve_entities(entities)"""- def __init__(self, **config):- """Initialize entity resolver."""+ def __init__(self, strategy: str = "fuzzy", similarity_threshold: float = 0.7, **config):+ """+ Initialize entity resolver.++ Sets up the resolver with duplicate detection and entity merging+ components configured according to the specified strategy.++ Args:+ strategy: Resolution strategy - "fuzzy", "exact", or "semantic" (default: "fuzzy")+ similarity_threshold: Minimum similarity score for considering entities as duplicates+ (0.0 to 1.0, default: 0.7)+ **config: Additional configuration:+ - deduplication: Configuration for duplicate detector+ - merger: Configuration for entity merger+ """self.logger = get_logger("entity_resolver")self.config = config+ # Resolution strategy and threshold+ self.resolution_strategy = strategy+ self.similarity_threshold = similarity_threshold+# Initialize deduplication components- self.duplicate_detector = DuplicateDetector(**config.get("deduplication", {}))- self.entity_merger = EntityMerger(**config.get("merger", {}))+ deduplication_config = config.get("deduplication", {})+ merger_config = config.get("merger", {})- self.resolution_strategy = config.get("strategy", "fuzzy")- self.similarity_threshold = config.get("similarity_threshold", 0.7)+ self.duplicate_detector = DuplicateDetector(**deduplication_config)+ self.entity_merger = EntityMerger(**merger_config)++ self.logger.debug(+ f"Entity resolver initialized with strategy: {strategy}, "+ f"threshold: {similarity_threshold}"+ )def resolve_entities(self, entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""- Resolve and disambiguate entities.+ Resolve and disambiguate entities by detecting and merging duplicates.++ This method performs a three-step process:+ 1. Detect duplicate entity groups using similarity matching+ 2. Merge duplicate groups into single canonical entities+ 3. Combine merged entities with non-duplicate entitiesArgs:- entities: List of entities to resolve+ entities: List of entity dictionaries to resolve. Each entity should+ have at least an "id" or "entity_id" field and a "name" field.Returns:- Resolved entities+ List of resolved entities with duplicates merged. The number of+ returned entities will be less than or equal to the input count.++ Example:+ >>> entities = [+ ... {"id": "1", "name": "Apple Inc.", "type": "Company"},+ ... {"id": "2", "name": "Apple", "type": "Company"},+ ... {"id": "3", "name": "Microsoft", "type": "Company"}+ ... ]+ >>> resolved = resolver.resolve_entities(entities)+ >>> # Returns 2 entities: merged "Apple Inc."/Apple and "Microsoft""""- self.logger.info(f"Resolving {len(entities)} entities")+ self.logger.info(f"Resolving {len(entities)} entities using {self.resolution_strategy} strategy")+ # Handle empty inputif not entities:+ self.logger.debug("No entities to resolve")return []- # Step 1: Detect duplicates+ # Step 1: Detect duplicate groups+ # Groups entities that are similar enough to be considered duplicates+ self.logger.debug(f"Detecting duplicate groups with threshold {self.similarity_threshold}")duplicate_groups = self.duplicate_detector.detect_duplicate_groups(entities,threshold=self.similarity_threshold)- # Step 2: Merge duplicates+ self.logger.debug(f"Found {len(duplicate_groups)} duplicate group(s)")++ # Step 2: Merge duplicates in each groupmerged_entities = []- processed_ids = set()+ processed_entity_ids = set() # Track which entities have been mergedfor group in duplicate_groups:+ # Skip groups with less than 2 entities (not duplicates)if len(group.entities) < 2:continue- # Merge the group+ # Merge the duplicate group into a single canonical entitymerge_operations = self.entity_merger.merge_duplicates(group.entities,**self.config)+ # Process each merge operationfor operation in merge_operations:merged_entity = operation.merged_entitymerged_entities.append(merged_entity)- # Mark source entities as processed+ # Mark all source entities as processedfor source_entity in operation.source_entities:entity_id = source_entity.get("id") or source_entity.get("entity_id")if entity_id:- processed_ids.add(entity_id)+ processed_entity_ids.add(entity_id)- # Step 3: Add non-duplicate entities+ # Step 3: Add non-duplicate entities (entities not in 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:+ if entity_id and entity_id not in processed_entity_ids:+ # This entity was not merged, add it as-ismerged_entities.append(entity)- self.logger.info(f"Resolved to {len(merged_entities)} unique entities")+ # Log resolution statistics+ original_count = len(entities)+ resolved_count = len(merged_entities)+ reduction = original_count - resolved_count++ self.logger.info(+ f"Entity resolution complete: {original_count} -> {resolved_count} "+ f"({reduction} duplicate(s) merged)"+ )+return merged_entitiesdef merge_duplicates(self, entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:diff --git a/semantica/kg/graph_analyzer.py b/semantica/kg/graph_analyzer.pyindex 0e592cfa..2bdbe8ac 100644--- a/semantica/kg/graph_analyzer.py+++ b/semantica/kg/graph_analyzer.py@@ -1,17 +1,25 @@"""Graph Analytics Module-Handles comprehensive graph analytics including centrality measures, community detection, and connectivity analysis.+This module provides comprehensive graph analytics capabilities for knowledge graphs,+including centrality measures, community detection, connectivity analysis, and+graph metrics calculation.Key Features:- - Centrality measures (degree, betweenness, closeness, eigenvector)- - Community detection algorithms- - Connectivity analysis+ - Multiple centrality measures (degree, betweenness, closeness, eigenvector)+ - Community detection algorithms (Louvain, Leiden, etc.)+ - Connectivity analysis and path finding- Graph metrics and statistics- - Path analysis and shortest paths+ - Temporal graph analysis (optional)-Main Classes:- - GraphAnalyzer: Main graph analytics class+Example Usage:+ >>> from semantica.kg import GraphAnalyzer+ >>> analyzer = GraphAnalyzer()+ >>> analysis = analyzer.analyze_graph(graph)+ >>> centrality = analyzer.calculate_centrality(graph, centrality_type="degree")++Author: Semantica Contributors+License: MIT"""from .centrality_calculator import CentralityCalculator@@ -23,91 +31,118 @@ class GraphAnalyzer:"""Comprehensive graph analytics handler.- • Performs graph analytics and metrics calculation- • Calculates centrality measures for nodes- • Detects communities and clusters in graphs- • Analyzes graph connectivity and structure- • Provides graph statistics and insights- • Supports various graph algorithms+ This class provides a unified interface for performing various graph analytics+ including centrality calculations, community detection, connectivity analysis,+ and graph metrics computation. It coordinates multiple specialized analyzers.++ Features:+ - Centrality measures (degree, betweenness, closeness, eigenvector)+ - Community detection (Louvain, Leiden, etc.)+ - Connectivity analysis and path finding+ - Graph metrics and statistics+ - Temporal graph analysis (optional)- Attributes:- • centrality_calculator: Centrality measures calculator- • community_detector: Community detection engine- • connectivity_analyzer: Connectivity analysis engine- • metrics_calculator: Graph metrics calculator- • supported_algorithms: List of supported algorithms-- Methods:- • analyze_graph(): Perform comprehensive graph analysis- • calculate_centrality(): Calculate centrality measures- • detect_communities(): Detect graph communities- • analyze_connectivity(): Analyze graph connectivity+ Example Usage:+ >>> analyzer = GraphAnalyzer()+ >>> # Comprehensive analysis+ >>> results = analyzer.analyze_graph(graph)+ >>> # Specific analysis+ >>> centrality = analyzer.calculate_centrality(graph, "betweenness")+ >>> communities = analyzer.detect_communities(graph, algorithm="louvain")"""def __init__(self,- config=None,- enable_temporal=False,- temporal_granularity="day",+ config: Optional[Dict[str, Any]] = None,+ enable_temporal: bool = False,+ temporal_granularity: str = "day",**kwargs):"""Initialize graph analyzer.- • Setup graph analysis algorithms- • Configure centrality calculations- • Initialize community detection- • Setup connectivity analysis- • Configure metrics calculation- • Enable temporal analysis if requested+ Sets up all analysis components including centrality calculator,+ community detector, and connectivity analyzer.Args:- config: Configuration dictionary- enable_temporal: Enable temporal graph analysis+ config: Configuration dictionary for analyzers+ enable_temporal: Enable temporal graph analysis features (default: False)temporal_granularity: Time granularity for temporal analysis- **kwargs: Additional configuration options+ ("second", "minute", "hour", "day", etc., default: "day")+ **kwargs: Additional configuration options merged into config"""+ from ..utils.logging import get_logger+ self.logger = get_logger("graph_analyzer")++ # Merge configurationself.config = config or {}+ self.config.update(kwargs)++ # Temporal analysis settingsself.enable_temporal = enable_temporalself.temporal_granularity = temporal_granularity++ # Initialize specialized analyzersself.centrality_calculator = CentralityCalculator(**self.config)self.community_detector = CommunityDetector(**self.config)self.connectivity_analyzer = ConnectivityAnalyzer(**self.config)- # Initialize graph analysis components- from ..utils.logging import get_logger- self.logger = get_logger("graph_analyzer")+ self.logger.info(+ f"Graph analyzer initialized (temporal: {enable_temporal})"+ )- def analyze_graph(self, graph, **options):+ def analyze_graph(self, graph: Dict[str, Any], **options) -> Dict[str, Any]:"""Perform comprehensive graph analysis.- • Calculate graph metrics and statistics- • Analyze graph structure and properties- • Identify key nodes and relationships- • Detect patterns and anomalies- • Return comprehensive analysis results+ This method runs all available graph analytics including centrality+ measures, community detection, connectivity analysis, and metrics+ computation. Returns a comprehensive analysis report.++ Args:+ graph: Knowledge graph to analyze (dict with "entities" and "relationships")+ **options: Analysis options passed to individual analyzers++ Returns:+ Dictionary containing:+ - centrality: Centrality measures for all nodes+ - communities: Detected community structures+ - connectivity: Connectivity analysis results+ - metrics: Graph metrics and statistics++ Example:+ >>> analysis = analyzer.analyze_graph(graph)+ >>> top_nodes = analysis["centrality"]["rankings"][:10]+ >>> num_communities = len(analysis["communities"])"""self.logger.info("Performing comprehensive graph analysis")- # Calculate centrality+ # Calculate centrality measures for all nodes+ self.logger.debug("Calculating centrality measures")centrality = self.calculate_centrality(graph, **options)- # Detect communities+ # Detect community structures+ self.logger.debug("Detecting communities")communities = self.detect_communities(graph, **options)- # Analyze connectivity+ # Analyze graph connectivity+ self.logger.debug("Analyzing connectivity")connectivity = self.analyze_connectivity(graph, **options)- # Compute metrics+ # Compute overall graph metrics+ self.logger.debug("Computing graph metrics")metrics = self.compute_metrics(graph=graph, **options)- return {+ # Compile comprehensive results+ results = {"centrality": centrality,"communities": communities,"connectivity": connectivity,"metrics": metrics}++ self.logger.info("Graph analysis completed successfully")+ return resultsdef calculate_centrality(self, graph, centrality_type="degree", **options):"""diff --git a/semantica/kg/graph_builder.py b/semantica/kg/graph_builder.pyindex 1df27a72..39bd45eb 100644--- a/semantica/kg/graph_builder.py+++ b/semantica/kg/graph_builder.py@@ -1,11 +1,30 @@"""-Knowledge graph builder for Semantica framework.+Knowledge Graph Builder Module-This module provides knowledge graph construction capabilities-from extracted entities and relationships, with support for-temporal knowledge graphs.+This module provides comprehensive knowledge graph construction capabilities+from extracted entities and relationships, with full support for temporal+knowledge graphs and advanced graph operations.++Key Features:+ - Build knowledge graphs from entities and relationships+ - Temporal knowledge graph support with time-aware edges+ - Entity resolution and deduplication+ - Conflict detection and resolution+ - Temporal snapshots and versioning+ - Neo4j integration for graph storage++Example Usage:+ >>> from semantica.kg import GraphBuilder+ >>> builder = GraphBuilder(merge_entities=True, resolve_conflicts=True)+ >>> graph = builder.build(sources=[{"entities": [...], "relationships": [...]}])++Author: Semantica Contributors+License: MIT"""+from typing import Any, Dict, List, Optional, Union+from datetime import datetime+class GraphBuilder:"""@@ -66,97 +85,161 @@ class GraphBuilder:self.track_history = track_historyself.version_snapshots = version_snapshots- # Initialize graph building components+ # Initialize loggingfrom ..utils.logging import get_loggerself.logger = get_logger("graph_builder")- config = kwargs- # Initialize entity resolver if needed+ # Initialize entity resolver if entity merging is enabled+ # This helps deduplicate and merge similar entitiesif self.merge_entities:from .entity_resolver import EntityResolver+ entity_resolution_config = kwargs.get("entity_resolution", {})self.entity_resolver = EntityResolver(strategy=self.entity_resolution_strategy,- **kwargs.get("entity_resolution", {})+ **entity_resolution_config)+ self.logger.debug(f"Entity resolver initialized with strategy: {self.entity_resolution_strategy}")else:self.entity_resolver = None+ self.logger.debug("Entity merging disabled, skipping entity resolver")- # Initialize conflict detector if needed+ # Initialize conflict detector if conflict resolution is enabled+ # This helps detect and resolve conflicting information in the graphif self.resolve_conflicts:from .conflict_detector import ConflictDetector- self.conflict_detector = ConflictDetector(**kwargs.get("conflict_detection", {}))+ conflict_detection_config = kwargs.get("conflict_detection", {})+ self.conflict_detector = ConflictDetector(**conflict_detection_config)+ self.logger.debug("Conflict detector initialized")else:self.conflict_detector = None+ self.logger.debug("Conflict resolution disabled")- def build(self, sources, entity_resolver=None, **options):+ def build(+ self,+ sources: Union[List[Any], Any],+ entity_resolver: Optional[Any] = None,+ **options+ ) -> Dict[str, Any]:"""Build knowledge graph from sources.+ This method processes various source formats and extracts entities and+ relationships to construct a knowledge graph. It handles entity resolution+ and conflict detection if enabled.+Args:- sources: List of sources (documents, entities, relationships)- entity_resolver: Optional entity resolver+ sources: List of sources in various formats:+ - Dict with "entities" and/or "relationships" keys+ - Dict with entity-like structure (has "id" or "entity_id")+ - Dict with relationship structure (has "source" and "target")+ - List of entity/relationship dicts+ entity_resolver: Optional custom entity resolver (overrides default)**options: Additional build optionsReturns:- Knowledge graph object+ Dictionary containing:+ - entities: List of resolved entities+ - relationships: List of relationships+ - metadata: Graph metadata including counts and timestamps++ Example:+ >>> sources = [+ ... {"entities": [{"id": "1", "name": "Alice"}],+ ... "relationships": [{"source": "1", "target": "2", "type": "knows"}]}+ ... ]+ >>> graph = builder.build(sources)"""- self.logger.info(f"Building knowledge graph from {len(sources)} sources")+ # Normalize sources to list+ if not isinstance(sources, list):+ sources = [sources]- # Use provided resolver or default- resolver = entity_resolver or self.entity_resolver+ self.logger.info(f"Building knowledge graph from {len(sources)} source(s)")- # Extract entities and relationships- entities = []- relationships = []+ # Use provided resolver or default instance resolver+ resolver_to_use = entity_resolver or self.entity_resolver++ # Extract entities and relationships from all sources+ all_entities = []+ all_relationships = []for source in sources:if isinstance(source, dict):- # Extract entities and relationships from source+ # Source is a dictionary - extract entities and relationshipsif "entities" in source:- entities.extend(source["entities"])+ # Explicit entities list+ all_entities.extend(source["entities"])elif "id" in source or "entity_id" in source:- entities.append(source)+ # Single entity object+ all_entities.append(source)if "relationships" in source:- relationships.extend(source["relationships"])+ # Explicit relationships list+ all_relationships.extend(source["relationships"])elif "source" in source and "target" in source:- relationships.append(source)+ # Single relationship object+ all_relationships.append(source)+elif isinstance(source, list):- # Assume list of entities or relationships+ # Source is a list - process each itemfor item in source:if isinstance(item, dict):+ # Determine if item is a relationship or entityif "source" in item and "target" in item:- relationships.append(item)+ all_relationships.append(item)else:- entities.append(item)-- # Resolve entities if needed- if resolver and entities:- self.logger.info(f"Resolving {len(entities)} entities")- entities = resolver.resolve_entities(entities)- self.logger.info(f"Resolved to {len(entities)} unique entities")+ all_entities.append(item)++ self.logger.debug(+ f"Extracted {len(all_entities)} entities and "+ f"{len(all_relationships)} relationships from sources"+ )++ # Resolve entities (deduplicate and merge) if resolver is available+ resolved_entities = all_entities+ if resolver_to_use and all_entities:+ self.logger.info(f"Resolving {len(all_entities)} entities using {self.entity_resolution_strategy} strategy")+ resolved_entities = resolver_to_use.resolve_entities(all_entities)+ self.logger.info(+ f"Entity resolution complete: {len(all_entities)} -> {len(resolved_entities)} unique entities"+ )# Build graph structuregraph = {- "entities": entities,- "relationships": relationships,+ "entities": resolved_entities,+ "relationships": all_relationships,"metadata": {- "num_entities": len(entities),- "num_relationships": len(relationships),+ "num_entities": len(resolved_entities),+ "num_relationships": len(all_relationships),"temporal_enabled": self.enable_temporal,- "timestamp": self._get_timestamp()+ "timestamp": self._get_timestamp(),+ "entity_resolution_applied": resolver_to_use is not None}}- # Detect and resolve conflicts if needed+ # Detect and resolve conflicts if conflict detector is availableif self.conflict_detector:- conflicts = self.conflict_detector.detect_conflicts(graph)- if conflicts:- self.logger.warning(f"Detected {len(conflicts)} conflicts")- resolution = self.conflict_detector.resolve_conflicts(conflicts)- self.logger.info(f"Resolved {resolution.get('resolved_count', 0)} conflicts")+ self.logger.debug("Detecting conflicts in graph")+ detected_conflicts = self.conflict_detector.detect_conflicts(graph)++ if detected_conflicts:+ conflict_count = len(detected_conflicts)+ self.logger.warning(f"Detected {conflict_count} conflict(s) in graph")++ # Attempt to resolve conflicts+ resolution_result = self.conflict_detector.resolve_conflicts(detected_conflicts)+ resolved_count = resolution_result.get('resolved_count', 0)++ if resolved_count > 0:+ self.logger.info(f"Successfully resolved {resolved_count} out of {conflict_count} conflict(s)")+ else:+ self.logger.warning("No conflicts were automatically resolved")++ # Log final graph statistics+ self.logger.info(+ f"Knowledge graph built successfully: "+ f"{len(resolved_entities)} entities, {len(all_relationships)} relationships"+ )- self.logger.info(f"Built graph with {len(entities)} entities and {len(relationships)} relationships")return graphdef add_temporal_edge(@@ -399,30 +482,69 @@ class GraphBuilder:self.logger.error(f"Error loading from Neo4j: {e}")raise- def _get_timestamp(self):- """Get current timestamp."""- from datetime import datetime+ def _get_timestamp(self) -> str:+ """+ Get current timestamp in ISO format.++ Returns:+ ISO format timestamp string (e.g., "2024-01-15T10:30:00")+ """return datetime.now().isoformat()- def _parse_time(self, time_value):- """Parse time value to ISO string."""- from datetime import datetime+ def _parse_time(self, time_value: Optional[Union[str, datetime, Any]]) -> Optional[str]:+ """+ Parse time value to ISO format string.++ This method handles various time input formats and converts them+ to a standardized ISO format string for temporal operations.+ Args:+ time_value: Time value in various formats:+ - None: Returns None+ - str: ISO format string (returned as-is)+ - datetime: Converted to ISO string+ - Other: Converted to string++ Returns:+ ISO format timestamp string or None+ """if time_value is None:return None+ # Already a string - assume it's in correct formatif isinstance(time_value, str):return time_value+ # datetime object - convert to ISO stringif isinstance(time_value, datetime):return time_value.isoformat()+ # Other types - convert to stringreturn str(time_value)- def _compare_times(self, time1, time2):- """Compare two time strings."""+ def _compare_times(self, time1: Optional[str], time2: Optional[str]) -> int:+ """+ Compare two time strings.++ This method performs lexicographic comparison of ISO format time strings.+ Returns -1 if time1 < time2, 0 if equal, 1 if time1 > time2.++ Args:+ time1: First time string (ISO format)+ time2: Second time string (ISO format)++ Returns:+ Comparison result: -1, 0, or 1+ """+ # Handle None valuesif time1 is None or time2 is None:return 0- # Simple string comparison for ISO format- return (time1 > time2) - (time1 < time2)+ # Simple lexicographic comparison works for ISO format strings+ # ISO format: YYYY-MM-DDTHH:MM:SS ensures correct string comparison+ if time1 < time2:+ return -1+ elif time1 > time2:+ return 1+ else:+ return 0diff --git a/semantica/kg/graph_validator.py b/semantica/kg/graph_validator.pyindex 8912288d..fc1d3262 100644--- a/semantica/kg/graph_validator.py+++ b/semantica/kg/graph_validator.py@@ -1,8 +1,29 @@"""-Graph validator for Semantica framework.+Graph Validation Module-This module provides consistency validation and quality checking-for knowledge graphs.+This module provides comprehensive consistency validation and quality checking+capabilities for the Semantica framework, enabling validation of knowledge+graph structure and consistency.++Key Features:+ - Entity validation (required fields, unique IDs)+ - Relationship validation (valid references, required fields)+ - Consistency checking (type consistency, circular relationships)+ - Orphaned entity detection+ - Validation result reporting with errors and warnings++Main Classes:+ - GraphValidator: Main graph validation engine+ - ValidationResult: Validation result dataclass++Example Usage:+ >>> from semantica.kg import GraphValidator+ >>> validator = GraphValidator()+ >>> result = validator.validate(knowledge_graph)+ >>> is_consistent = validator.check_consistency(knowledge_graph)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -13,7 +34,17 @@ from ..utils.logging import get_logger@dataclassclass ValidationResult:- """Validation result."""+ """+ Validation result dataclass.++ This dataclass represents the result of graph validation, containing+ validation status, errors, and warnings.++ Attributes:+ valid: Whether the graph is valid (True if no errors)+ errors: List of error messages (critical issues)+ warnings: List of warning messages (non-critical issues)+ """valid: boolerrors: List[str]@@ -22,25 +53,61 @@ class ValidationResult:class GraphValidator:"""- Graph validator.+ Graph validation engine.++ This class provides comprehensive validation capabilities for knowledge+ graphs, checking for structural consistency, required fields, valid+ references, and logical consistency.++ Features:+ - Entity validation (IDs, types, required fields)+ - Relationship validation (valid entity references)+ - Consistency checking (type consistency, circular relationships)+ - Orphaned entity detection+ - Detailed error and warning reporting- Validates consistency and quality of knowledge graphs.+ Example Usage:+ >>> validator = GraphValidator()+ >>> result = validator.validate(knowledge_graph)+ >>> if not result.valid:+ ... print(f"Errors: {result.errors}")+ >>> is_consistent = validator.check_consistency(knowledge_graph)"""def __init__(self, **config):- """Initialize graph validator."""+ """+ Initialize graph validator.++ Sets up the validator with configuration options.++ Args:+ **config: Configuration options (currently unused)+ """self.logger = get_logger("graph_validator")self.config = config++ self.logger.debug("Graph validator initialized")def validate(self, knowledge_graph: Any) -> ValidationResult:"""Validate knowledge graph.+ This method performs comprehensive validation of the knowledge graph,+ checking for:+ - Entity validity (required ID field, unique IDs)+ - Relationship validity (required source/target/type fields)+ - Valid entity references in relationships+ - Orphaned entities (entities with no relationships)+Args:- knowledge_graph: Knowledge graph instance+ knowledge_graph: Knowledge graph instance (object with entities/relationships+ attributes, or dict with "entities" and "relationships" keys)Returns:- Validation result+ ValidationResult: Validation result object containing:+ - valid: True if no errors found, False otherwise+ - errors: List of error messages (critical issues)+ - warnings: List of warning messages (non-critical issues)"""self.logger.info("Validating knowledge graph")@@ -127,11 +194,16 @@ class GraphValidator:"""Check graph consistency.+ This method performs logical consistency checking, including:+ - Type consistency (same entity should not have conflicting types)+ - Circular relationship detection+ - Basic validation checks+Args:knowledge_graph: Knowledge graph instanceReturns:- True if consistent, False otherwise+ bool: True if graph is consistent, False if inconsistencies found"""self.logger.info("Checking graph consistency")diff --git a/semantica/kg/provenance_tracker.py b/semantica/kg/provenance_tracker.pyindex 49300afc..26c13b54 100644--- a/semantica/kg/provenance_tracker.py+++ b/semantica/kg/provenance_tracker.py@@ -1,8 +1,29 @@"""-Provenance tracker for Semantica framework.+Provenance Tracking Module-This module provides source tracking and lineage+This module provides comprehensive source tracking and lineage capabilities+for the Semantica framework, enabling tracking of data origins and evolutionfor knowledge graph entities and relationships.++Key Features:+ - Entity provenance tracking (source, timestamp, metadata)+ - Relationship provenance tracking+ - Lineage retrieval (complete provenance history)+ - Source aggregation (multiple sources per entity)+ - Temporal tracking (first seen, last updated)++Main Classes:+ - ProvenanceTracker: Main provenance tracking engine++Example Usage:+ >>> from semantica.kg import ProvenanceTracker+ >>> tracker = ProvenanceTracker()+ >>> tracker.track_entity("entity_1", source="source_1", metadata={"confidence": 0.9})+ >>> lineage = tracker.get_lineage("entity_1")+ >>> sources = tracker.get_all_sources("entity_1")++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -13,16 +34,41 @@ from ..utils.logging import get_loggerclass ProvenanceTracker:"""- Provenance tracker.+ Provenance tracking engine.++ This class provides provenance tracking capabilities, maintaining source+ and lineage information for knowledge graph entities and relationships.+ Tracks multiple sources per entity and maintains temporal information.- Tracks source and lineage for knowledge graph entities and relationships.+ Features:+ - Entity and relationship provenance tracking+ - Multiple source support per entity+ - Temporal tracking (first seen, last updated)+ - Metadata storage and aggregation+ - Lineage retrieval++ Example Usage:+ >>> tracker = ProvenanceTracker()+ >>> tracker.track_entity("entity_1", source="source_1", metadata={"confidence": 0.9})+ >>> lineage = tracker.get_lineage("entity_1")+ >>> sources = tracker.get_all_sources("entity_1")"""def __init__(self, **config):- """Initialize provenance tracker."""+ """+ Initialize provenance tracker.++ Sets up the tracker with configuration and initializes provenance+ data storage.++ Args:+ **config: Configuration options (currently unused)+ """self.logger = get_logger("provenance_tracker")self.config = configself.provenance_data: Dict[str, Any] = {}++ self.logger.debug("Provenance tracker initialized")def track_entity(self,@@ -33,10 +79,15 @@ class ProvenanceTracker:"""Track entity provenance.+ This method records provenance information for an entity, including+ source, timestamp, and optional metadata. Supports multiple sources+ per entity and maintains first seen and last updated timestamps.+Args:entity_id: Entity identifier- source: Source identifier- metadata: Optional metadata+ source: Source identifier (e.g., "file_1", "api_endpoint_2")+ metadata: Optional metadata dictionary (e.g., confidence scores,+ extraction methods, etc.)"""if entity_id not in self.provenance_data:self.provenance_data[entity_id] = {@@ -71,10 +122,14 @@ class ProvenanceTracker:"""Track relationship provenance.+ This method records provenance information for a relationship, including+ source, timestamp, and optional metadata. Similar to track_entity()+ but for relationships.+Args:relationship_id: Relationship identifiersource: Source identifier- metadata: Optional metadata+ metadata: Optional metadata dictionary"""if relationship_id not in self.provenance_data:self.provenance_data[relationship_id] = {@@ -100,11 +155,17 @@ class ProvenanceTracker:"""Get all sources for an entity.+ This method retrieves all source entries for a given entity, including+ source identifiers, timestamps, and metadata.+Args:entity_id: Entity identifierReturns:- List of source entries+ list: List of source entry dictionaries, each containing:+ - source: Source identifier+ - timestamp: ISO format timestamp+ - metadata: Source metadata dictionary"""if entity_id not in self.provenance_data:return []@@ -115,11 +176,18 @@ class ProvenanceTracker:"""Get complete lineage for an entity.+ This method retrieves complete lineage information for an entity,+ including all sources, temporal information, and aggregated metadata.+Args:entity_id: Entity identifierReturns:- Lineage information+ dict: Complete lineage information containing:+ - sources: List of all source entries+ - first_seen: ISO timestamp of first source+ - last_updated: ISO timestamp of most recent source+ - metadata: Aggregated metadata dictionary"""if entity_id not in self.provenance_data:return {}@@ -130,10 +198,14 @@ class ProvenanceTracker:"""Get provenance for entity.+ This method is an alias for get_lineage(), returning the complete+ provenance information for an entity, or None if not tracked.+Args:entity_id: Entity identifierReturns:- Provenance information or None+ dict: Complete provenance information (same as get_lineage()),+ or None if entity is not tracked"""return self.provenance_data.get(entity_id)diff --git a/semantica/kg/seed_manager.py b/semantica/kg/seed_manager.pyindex b7ff1610..4307b381 100644--- a/semantica/kg/seed_manager.py+++ b/semantica/kg/seed_manager.py@@ -1,8 +1,29 @@"""-Seed manager for Semantica framework.+Seed Management Module-This module provides initial data loading and seeding-for knowledge graph construction.+This module provides comprehensive initial data loading and seeding capabilities+for the Semantica framework, enabling bootstrap data loading for knowledge+graph construction.++Key Features:+ - Seed data loading from various sources+ - File-based seed data loading (JSON)+ - Data normalization and validation+ - Source tracking for seed data+ - Seed data management (clear, retrieve)++Main Classes:+ - SeedManager: Main seed data management engine++Example Usage:+ >>> from semantica.kg import SeedManager+ >>> manager = SeedManager()+ >>> manager.load_seed_data("source_1", entities)+ >>> manager.load_from_file("seed_data.json", source="file_source")+ >>> seed_data = manager.get_seed_data()++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -13,24 +34,53 @@ from ..utils.logging import get_loggerclass SeedManager:"""- Seed manager.+ Seed data management engine.++ This class provides seed data loading and management capabilities for+ knowledge graph construction, enabling bootstrap data loading from various+ sources with normalization and validation.- Manages initial data loading and seeding for knowledge graph construction.+ Features:+ - Seed data loading from dictionaries and lists+ - File-based seed data loading (JSON)+ - Data normalization and ID generation+ - Source tracking and metadata+ - Seed data retrieval and management++ Example Usage:+ >>> manager = SeedManager()+ >>> manager.load_seed_data("source_1", entities)+ >>> manager.load_from_file("seed_data.json")+ >>> seed_data = manager.get_seed_data()"""def __init__(self, **config):- """Initialize seed manager."""+ """+ Initialize seed manager.++ Sets up the manager with configuration and initializes seed data storage.++ Args:+ **config: Configuration options (currently unused)+ """self.logger = get_logger("seed_manager")self.config = configself.seed_data: List[Dict[str, Any]] = []++ self.logger.debug("Seed manager initialized")def load_seed_data(self, source: str, data: Any) -> None:"""Load seed data.+ This method loads seed data from various formats (list of entities,+ dict with "entities" key, or single entity dict), normalizes the data,+ ensures required fields (ID, source), and stores it with metadata.+Args:- source: Source identifier- data: Seed data to load+ source: Source identifier (e.g., "initial_data", "bootstrap")+ data: Seed data to load (list of entities, dict with "entities" key,+ or single entity dict)"""self.logger.info(f"Loading seed data from source: {source}")@@ -69,13 +119,24 @@ class SeedManager:self.logger.info(f"Loaded {len(processed_entities)} entities from {source}")- def load_from_file(self, file_path: str, source: Optional[str] = None) -> None:+ def load_from_file(+ self,+ file_path: str,+ source: Optional[str] = None+ ) -> None:"""Load seed data from file.+ This method loads seed data from a JSON file. The source identifier+ defaults to the file stem (filename without extension) if not provided.+Args:- file_path: Path to seed data file- source: Optional source identifier+ file_path: Path to seed data file (must be JSON format)+ source: Optional source identifier (defaults to file stem)++ Raises:+ FileNotFoundError: If file does not exist+ ValueError: If file format is unsupported"""import jsonfrom pathlib import Path@@ -103,11 +164,23 @@ class SeedManager:"""Get loaded seed data.+ This method retrieves all loaded seed data with their metadata.+Returns:- List of seed data entries+ list: List of seed data entry dictionaries, each containing:+ - source: Source identifier+ - entities: List of entity dictionaries+ - count: Number of entities+ - timestamp: ISO timestamp when data was loaded"""return self.seed_datadef clear_seed_data(self) -> None:- """Clear all seed data."""+ """+ Clear all seed data.++ This method removes all loaded seed data from the manager. Useful+ for resetting state or freeing memory.+ """self.seed_data = []+ self.logger.debug("Cleared all seed data")diff --git a/semantica/kg/temporal_query.py b/semantica/kg/temporal_query.pyindex e5baf9b3..59aff72b 100644--- a/semantica/kg/temporal_query.py+++ b/semantica/kg/temporal_query.py@@ -1,7 +1,31 @@"""-Temporal Query Module for Knowledge Graphs+Temporal Query Module-Provides time-aware querying capabilities for temporal knowledge graphs.+This module provides comprehensive time-aware querying capabilities for the+Semantica framework, enabling temporal queries and analysis on knowledge+graphs with temporal information.++Key Features:+ - Time-point queries (query graph at specific time)+ - Time-range queries (query within time intervals)+ - Temporal pattern detection (sequences, cycles, trends)+ - Graph evolution analysis+ - Temporal path finding+ - Temporal version management++Main Classes:+ - TemporalGraphQuery: Main temporal query engine+ - TemporalPatternDetector: Temporal pattern detection engine+ - TemporalVersionManager: Temporal version/snapshot management++Example Usage:+ >>> from semantica.kg import TemporalGraphQuery+ >>> query_engine = TemporalGraphQuery()+ >>> result = query_engine.query_at_time(graph, query, at_time="2024-01-01")+ >>> evolution = query_engine.analyze_evolution(graph, start_time="2024-01-01")++Author: Semantica Contributors+License: MIT"""@@ -9,42 +33,46 @@ class TemporalGraphQuery:"""Temporal knowledge graph query engine.- • Executes time-aware queries on knowledge graphs- • Supports queries at specific time points- • Handles temporal range queries- • Manages temporal window queries- • Processes temporal pattern queries- • Supports temporal evolution analysis+ This class provides time-aware querying capabilities for knowledge graphs+ with temporal information, enabling queries at specific time points, within+ time ranges, and temporal pattern detection.++ Features:+ - Time-point queries (filter relationships valid at specific time)+ - Time-range queries (filter relationships valid within range)+ - Temporal pattern detection (sequences, cycles, trends)+ - Graph evolution analysis+ - Temporal path finding (paths considering temporal validity)- Attributes:- • supported_query_languages: Supported query languages- • temporal_reasoner: Temporal reasoning engine- • pattern_detector: Temporal pattern detector- • evolution_analyzer: Graph evolution analyzer-- Methods:- • query_at_time(): Query graph at specific time- • query_time_range(): Query within time range- • query_temporal_pattern(): Query temporal patterns- • analyze_evolution(): Analyze graph evolution- • find_temporal_paths(): Find paths in temporal context+ Example Usage:+ >>> query_engine = TemporalGraphQuery()+ >>> result = query_engine.query_at_time(graph, query, at_time="2024-01-01")+ >>> range_result = query_engine.query_time_range(graph, query, start_time, end_time)+ >>> evolution = query_engine.analyze_evolution(graph)"""def __init__(self,- enable_temporal_reasoning=True,- temporal_granularity="day",- max_temporal_depth=None,+ enable_temporal_reasoning: bool = True,+ temporal_granularity: str = "day",+ max_temporal_depth: Optional[int] = None,**kwargs):"""Initialize temporal query engine.+ Sets up the query engine with temporal reasoning configuration and+ pattern detector.+Args:- enable_temporal_reasoning: Enable temporal reasoning+ enable_temporal_reasoning: Enable temporal reasoning capabilities+ (default: True)temporal_granularity: Time granularity for queries- max_temporal_depth: Maximum depth for temporal queries- **kwargs: Additional configuration+ (default: "day", options: "second", "minute",+ "hour", "day", "week", "month", "year")+ max_temporal_depth: Maximum depth for temporal queries (optional)+ **kwargs: Additional configuration options:+ - pattern_detection: Configuration for pattern detector (optional)"""self.enable_temporal_reasoning = enable_temporal_reasoningself.temporal_granularity = temporal_granularity@@ -59,26 +87,37 @@ class TemporalGraphQuery:def query_at_time(self,- graph,- query,- at_time,- include_history=False,- temporal_precision=None,+ graph: Any,+ query: str,+ at_time: Any,+ include_history: bool = False,+ temporal_precision: Optional[str] = None,**options- ):+ ) -> Dict[str, Any]:"""Query graph at specific time point.+ This method filters the knowledge graph to only include relationships+ that are valid at the specified time point, based on valid_from and+ valid_until fields in relationships.+Args:- graph: Knowledge graph to query- query: Query string (Cypher, SPARQL, or natural language)- at_time: Time point (datetime, timestamp, or ISO string)- include_history: Include historical context- temporal_precision: Precision for time matching- **options: Additional query options+ graph: Knowledge graph to query (dict with "entities" and "relationships")+ query: Query string (currently unused, reserved for future query parsing)+ at_time: Time point (datetime object, timestamp, or ISO format string)+ include_history: Whether to include all relationships with temporal+ information (default: False, only valid relationships)+ temporal_precision: Precision for time matching (optional, unused)+ **options: Additional query options (unused)Returns:- Query results valid at specified time+ dict: Query results containing:+ - query: Original query string+ - at_time: Parsed time point+ - entities: All entities (not filtered by time)+ - relationships: Relationships valid at specified time+ - num_entities: Number of entities+ - num_relationships: Number of valid relationships"""self.logger.info(f"Querying graph at time: {at_time}")@@ -119,28 +158,40 @@ class TemporalGraphQuery:def query_time_range(self,- graph,- query,- start_time,- end_time,- temporal_aggregation="union",- include_intervals=True,+ graph: Any,+ query: str,+ start_time: Any,+ end_time: Any,+ temporal_aggregation: str = "union",+ include_intervals: bool = True,**options- ):+ ) -> Dict[str, Any]:"""Query graph within time range.+ This method filters relationships that are valid within the specified+ time range, with different aggregation strategies.+Args:graph: Knowledge graph to query- query: Query string- start_time: Start of time range- end_time: End of time range- temporal_aggregation: How to aggregate results ("union", "intersection", "evolution")- include_intervals: Include partial matches within range- **options: Additional query options+ query: Query string (currently unused, reserved for future)+ start_time: Start of time range (datetime, timestamp, or ISO string)+ end_time: End of time range (datetime, timestamp, or ISO string)+ temporal_aggregation: Aggregation strategy:+ - "union": Include all relationships overlapping with range (default)+ - "intersection": Only relationships valid throughout entire range+ - "evolution": Group relationships by time periods+ include_intervals: Include partial matches within range (default: True)+ **options: Additional query options (unused)Returns:- Query results within time range+ dict: Query results containing:+ - query: Original query string+ - start_time: Parsed start time+ - end_time: Parsed end time+ - relationships: Filtered relationships+ - num_relationships: Number of relationships+ - aggregation: Aggregation strategy used"""self.logger.info(f"Querying graph in time range: {start_time} to {end_time}")@@ -186,24 +237,30 @@ class TemporalGraphQuery:def query_temporal_pattern(self,- graph,- pattern,- time_window=None,- min_support=1,+ graph: Any,+ pattern: str,+ time_window: Optional[Any] = None,+ min_support: int = 1,**options- ):+ ) -> Dict[str, Any]:"""Query for temporal patterns in graph.+ This method detects temporal patterns (sequences, cycles, trends) in+ the knowledge graph using the temporal pattern detector.+Args:graph: Knowledge graph to query- pattern: Pattern to search for- time_window: Time window for pattern matching- min_support: Minimum support for pattern+ pattern: Pattern type to search for ("sequence", "cycle", "trend", "anomaly")+ time_window: Time window for pattern matching (optional)+ min_support: Minimum frequency/support for pattern (default: 1)**options: Additional pattern query optionsReturns:- Matching temporal patterns+ dict: Pattern query results containing:+ - pattern: Pattern type searched+ - patterns: List of detected patterns+ - num_patterns: Number of patterns found"""self.logger.info(f"Querying temporal patterns: {pattern}")@@ -224,28 +281,41 @@ class TemporalGraphQuery:def analyze_evolution(self,- graph,- entity=None,- relationship=None,- start_time=None,- end_time=None,- metrics=["count", "diversity", "stability"],+ graph: Any,+ entity: Optional[str] = None,+ relationship: Optional[str] = None,+ start_time: Optional[Any] = None,+ end_time: Optional[Any] = None,+ metrics: List[str] = None,**options- ):+ ) -> Dict[str, Any]:"""Analyze graph evolution over time.+ This method analyzes how the knowledge graph (or specific entities/relationships)+ evolves over a time period, calculating various evolution metrics.+Args:graph: Knowledge graph to analyze- entity: Specific entity to track (None for entire graph)- relationship: Specific relationship type to track (None for all)- start_time: Start of analysis period- end_time: End of analysis period- metrics: Metrics to calculate- **options: Additional analysis options+ entity: Specific entity ID to track (optional, None for entire graph)+ relationship: Specific relationship type to track (optional, None for all)+ start_time: Start of analysis period (optional)+ end_time: End of analysis period (optional)+ metrics: List of metrics to calculate (default: ["count", "diversity", "stability"])+ - "count": Number of relationships+ - "diversity": Number of unique relationship types+ - "stability": Relationship duration/stability measure+ **options: Additional analysis options (unused)Returns:- Evolution analysis results+ dict: Evolution analysis results containing:+ - entity: Entity ID tracked (if specified)+ - relationship: Relationship type tracked (if specified)+ - time_range: Dictionary with start and end times+ - num_relationships: Number of relationships in period+ - count: Relationship count (if "count" in metrics)+ - diversity: Relationship type diversity (if "diversity" in metrics)+ - stability: Stability measure (if "stability" in metrics)"""self.logger.info("Analyzing graph evolution")@@ -312,30 +382,41 @@ class TemporalGraphQuery:def find_temporal_paths(self,- graph,- source,- target,- start_time=None,- end_time=None,- max_path_length=None,- temporal_constraints=None,+ graph: Any,+ source: str,+ target: str,+ start_time: Optional[Any] = None,+ end_time: Optional[Any] = None,+ max_path_length: Optional[int] = None,+ temporal_constraints: Optional[Dict[str, Any]] = None,**options- ):+ ) -> Dict[str, Any]:"""Find paths between entities considering temporal validity.+ This method finds paths between source and target entities, considering+ only relationships that are temporally valid within the specified+ time range. Uses BFS for path finding.+Args:graph: Knowledge graph to search- source: Source entity- target: Target entity- start_time: Start time for path validity- end_time: End time for path validity- max_path_length: Maximum path length- temporal_constraints: Additional temporal constraints- **options: Additional path finding options+ source: Source entity ID+ target: Target entity ID+ start_time: Start time for path validity (optional)+ end_time: End time for path validity (optional)+ max_path_length: Maximum path length in edges (optional)+ temporal_constraints: Additional temporal constraints (optional, unused)+ **options: Additional path finding options (unused)Returns:- Temporal paths between entities+ dict: Temporal path results containing:+ - source: Source entity ID+ - target: Target entity ID+ - paths: List of path dictionaries, each containing:+ - path: List of node IDs forming the path+ - edges: List of relationship dictionaries+ - length: Path length in edges+ - num_paths: Total number of paths found"""self.logger.info(f"Finding temporal paths from {source} to {target}")@@ -423,41 +504,67 @@ class TemporalGraphQuery:class TemporalPatternDetector:"""- Temporal pattern detection in knowledge graphs.+ Temporal pattern detection engine.++ This class provides temporal pattern detection capabilities for knowledge+ graphs, identifying recurring patterns, sequences, cycles, and trends in+ temporal data.- • Detects recurring temporal patterns- • Identifies temporal sequences- • Finds temporal anomalies- • Discovers temporal trends- • Analyzes temporal correlations+ Features:+ - Sequence pattern detection+ - Cycle pattern detection+ - Trend analysis+ - Anomaly detection (planned)++ Example Usage:+ >>> detector = TemporalPatternDetector()+ >>> patterns = detector.detect_temporal_patterns(+ ... graph, pattern_type="sequence", min_frequency=2+ ... )"""def __init__(self, **config):- """Initialize temporal pattern detector."""+ """+ Initialize temporal pattern detector.++ Sets up the detector with configuration options.++ Args:+ **config: Configuration options (currently unused)+ """from ..utils.logging import get_loggerself.logger = get_logger("temporal_pattern_detector")self.config = config++ self.logger.debug("Temporal pattern detector initialized")def detect_temporal_patterns(self,- graph,- pattern_type="sequence",- min_frequency=2,- time_window=None,+ graph: Any,+ pattern_type: str = "sequence",+ min_frequency: int = 2,+ time_window: Optional[Any] = None,**options- ):+ ) -> List[Dict[str, Any]]:"""Detect temporal patterns in graph.+ This method detects various types of temporal patterns in the knowledge+ graph, including sequences and cycles.+Args:graph: Knowledge graph to analyze- pattern_type: Type of pattern ("sequence", "cycle", "trend", "anomaly")- min_frequency: Minimum frequency for pattern- time_window: Time window for pattern detection- **options: Additional detection options+ pattern_type: Type of pattern to detect:+ - "sequence": Sequential relationship patterns+ - "cycle": Cyclic relationship patterns+ - "trend": Trend patterns (planned)+ - "anomaly": Anomaly patterns (planned)+ min_frequency: Minimum frequency/support for pattern (default: 2)+ time_window: Time window for pattern detection (optional)+ **options: Additional detection options (unused)Returns:- Detected temporal patterns+ list: List of detected pattern dictionaries"""self.logger.info(f"Detecting temporal patterns: {pattern_type}")@@ -490,30 +597,47 @@ class TemporalPatternDetector:class TemporalVersionManager:"""- Temporal version management for knowledge graphs.+ Temporal version management engine.- • Creates temporal versions/snapshots- • Manages version history- • Handles version comparison- • Supports version rollback- • Tracks version metadata+ This class provides version/snapshot management capabilities for knowledge+ graphs, enabling creation of temporal versions, version comparison, and+ version history tracking.++ Features:+ - Version snapshot creation+ - Version comparison+ - Version history tracking+ - Automatic snapshotting (planned)+ - Version rollback (planned)++ Example Usage:+ >>> manager = TemporalVersionManager()+ >>> version = manager.create_version(graph, version_label="v1.0")+ >>> comparison = manager.compare_versions(version1, version2)"""def __init__(self,- snapshot_interval=None,- auto_snapshot=False,- version_strategy="timestamp",+ snapshot_interval: Optional[int] = None,+ auto_snapshot: bool = False,+ version_strategy: str = "timestamp",**config):"""Initialize temporal version manager.+ Sets up the version manager with snapshot configuration and versioning+ strategy.+Args:- snapshot_interval: Interval for automatic snapshots- auto_snapshot: Enable automatic snapshots- version_strategy: Versioning strategy ("timestamp", "incremental", "semantic")- **config: Additional configuration+ snapshot_interval: Interval for automatic snapshots in seconds+ (optional, auto_snapshot must be True)+ auto_snapshot: Enable automatic snapshots (default: False)+ version_strategy: Versioning strategy:+ - "timestamp": Use timestamps for version labels (default)+ - "incremental": Use incremental version numbers (planned)+ - "semantic": Use semantic versioning (planned)+ **config: Additional configuration options (unused)"""self.snapshot_interval = snapshot_intervalself.auto_snapshot = auto_snapshot@@ -521,24 +645,32 @@ class TemporalVersionManager:def create_version(self,- graph,- version_label=None,- timestamp=None,- metadata=None,+ graph: Any,+ version_label: Optional[str] = None,+ timestamp: Optional[Any] = None,+ metadata: Optional[Dict[str, Any]] = None,**options- ):+ ) -> Dict[str, Any]:"""Create version snapshot of graph.+ This method creates a snapshot/version of the knowledge graph at a+ specific point in time, copying entities and relationships.+Args:- graph: Knowledge graph to version- version_label: Optional version label- timestamp: Timestamp for version (None for current)- metadata: Additional version metadata- **options: Additional version options+ graph: Knowledge graph to version (dict with "entities" and "relationships")+ version_label: Optional version label (defaults to "version_{timestamp}")+ timestamp: Timestamp for version (defaults to current time)+ metadata: Additional version metadata dictionary (optional)+ **options: Additional version options (unused)Returns:- Version snapshot object+ dict: Version snapshot containing:+ - label: Version label+ - timestamp: ISO format timestamp+ - entities: Copy of entities list+ - relationships: Copy of relationships list+ - metadata: Version metadata dictionary"""from datetime import datetime@@ -554,18 +686,31 @@ class TemporalVersionManager:return version- def compare_versions(self, version1, version2, comparison_metrics=None, **options):+ def compare_versions(+ self,+ version1: Dict[str, Any],+ version2: Dict[str, Any],+ comparison_metrics: Optional[List[str]] = None,+ **options+ ) -> Dict[str, Any]:"""Compare two graph versions.+ This method compares two version snapshots and calculates differences+ in entities and relationships.+Args:- version1: First version- version2: Second version- comparison_metrics: Metrics for comparison- **options: Additional comparison options+ version1: First version snapshot dictionary+ version2: Second version snapshot dictionary+ comparison_metrics: List of metrics to calculate (optional, unused)+ **options: Additional comparison options (unused)Returns:- Version comparison results+ dict: Version comparison results containing:+ - version1: Label of first version+ - version2: Label of second version+ - entities_added: Change in entity count (version2 - version1)+ - relationships_added: Change in relationship count (version2 - version1)"""comparison = {"version1": version1.get("label", "unknown"),