odin-engine 0.1.0__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. benchmarks/__init__.py +17 -17
  2. benchmarks/datasets.py +284 -284
  3. benchmarks/metrics.py +275 -275
  4. benchmarks/run_ablation.py +279 -279
  5. benchmarks/run_npll_benchmark.py +270 -270
  6. npll/__init__.py +10 -10
  7. npll/bootstrap.py +474 -474
  8. npll/core/__init__.py +33 -33
  9. npll/core/knowledge_graph.py +308 -308
  10. npll/core/logical_rules.py +496 -496
  11. npll/core/mln.py +474 -474
  12. npll/inference/__init__.py +40 -40
  13. npll/inference/e_step.py +419 -419
  14. npll/inference/elbo.py +434 -434
  15. npll/inference/m_step.py +576 -576
  16. npll/npll_model.py +631 -631
  17. npll/scoring/__init__.py +42 -42
  18. npll/scoring/embeddings.py +441 -441
  19. npll/scoring/probability.py +402 -402
  20. npll/scoring/scoring_module.py +369 -369
  21. npll/training/__init__.py +24 -24
  22. npll/training/evaluation.py +496 -496
  23. npll/training/npll_trainer.py +520 -520
  24. npll/utils/__init__.py +47 -47
  25. npll/utils/batch_utils.py +492 -492
  26. npll/utils/config.py +144 -144
  27. npll/utils/math_utils.py +338 -338
  28. odin/__init__.py +21 -20
  29. odin/engine.py +264 -264
  30. odin/schema.py +210 -0
  31. {odin_engine-0.1.0.dist-info → odin_engine-0.2.0.dist-info}/METADATA +503 -456
  32. odin_engine-0.2.0.dist-info/RECORD +63 -0
  33. {odin_engine-0.1.0.dist-info → odin_engine-0.2.0.dist-info}/licenses/LICENSE +21 -21
  34. retrieval/__init__.py +50 -50
  35. retrieval/adapters.py +140 -140
  36. retrieval/adapters_arango.py +1418 -1418
  37. retrieval/aggregators.py +707 -707
  38. retrieval/beam.py +127 -127
  39. retrieval/budget.py +60 -60
  40. retrieval/cache.py +159 -159
  41. retrieval/confidence.py +88 -88
  42. retrieval/eval.py +49 -49
  43. retrieval/linker.py +87 -87
  44. retrieval/metrics.py +105 -105
  45. retrieval/metrics_motifs.py +36 -36
  46. retrieval/orchestrator.py +571 -571
  47. retrieval/ppr/__init__.py +12 -12
  48. retrieval/ppr/anchors.py +41 -41
  49. retrieval/ppr/bippr.py +61 -61
  50. retrieval/ppr/engines.py +257 -257
  51. retrieval/ppr/global_pr.py +76 -76
  52. retrieval/ppr/indexes.py +78 -78
  53. retrieval/ppr.py +156 -156
  54. retrieval/ppr_cache.py +25 -25
  55. retrieval/scoring.py +294 -294
  56. retrieval/utils/pii_redaction.py +36 -36
  57. retrieval/writers/__init__.py +9 -9
  58. retrieval/writers/arango_writer.py +28 -28
  59. retrieval/writers/base.py +21 -21
  60. retrieval/writers/janus_writer.py +36 -36
  61. odin_engine-0.1.0.dist-info/RECORD +0 -62
  62. {odin_engine-0.1.0.dist-info → odin_engine-0.2.0.dist-info}/WHEEL +0 -0
  63. {odin_engine-0.1.0.dist-info → odin_engine-0.2.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,63 @@
1
+ benchmarks/__init__.py,sha256=rollRY8I0xNWexV_jU-uDWYmwTH9Lu9vIxBUwPy1N60,484
2
+ benchmarks/datasets.py,sha256=MyvxpfuAwY2RVBJBvPyEzWgUMc4DcgX3IjMoz9mTVck,8171
3
+ benchmarks/metrics.py,sha256=WXAGSpGFWKZGc_5tU-GNdQNvmApfklaeG7Tve1YPzEE,7751
4
+ benchmarks/run_ablation.py,sha256=qdXTCr5PeakF-XyHGuYkqaDpfO0mAWsxQlyR3JPatUU,8484
5
+ benchmarks/run_npll_benchmark.py,sha256=uQcUq3g-AlbjT13eeY2mALtmGagOwBBmjMi2K9EPa0c,7746
6
+ npll/__init__.py,sha256=2t0fSdqg-P2QygPLeWyYT2LowERyBtifyN6CZVVt8Rk,231
7
+ npll/bootstrap.py,sha256=mb3No4rTPeQ28kqGVqiJsVoTwO6FHNPUVFA280HnCYA,18375
8
+ npll/npll_model.py,sha256=8pQOskXrugkah4OhQ3W4mYIaYfEu_XT8GvUMOJ06ZnU,26540
9
+ npll/core/__init__.py,sha256=8LWXF_z93tf-gzYvRu7ycdvgnXD5Kr6Jaa2SiFZWAUQ,832
10
+ npll/core/knowledge_graph.py,sha256=FwDrBNydCx_0PKBtWOnUbMapjkqvVkuPmmcj_fiK3Ow,11183
11
+ npll/core/logical_rules.py,sha256=x7SrGA8SsszMjy4m8mPUGDyV14uKgy3nFpeRd4qxUDk,17771
12
+ npll/core/mln.py,sha256=ShtA9MK-7vmqzQcS42A4iFE6CWmzFA1XlKCMfEqCaSQ,18585
13
+ npll/inference/__init__.py,sha256=ydHHiRQ8hJAZe0ayHIDgKvDTzugn5q_0vK4O0NkkUN8,1039
14
+ npll/inference/e_step.py,sha256=7u7Xk520WLcyu2f3OlUTRHmURdRh7bG-I91mrIx_nvk,16929
15
+ npll/inference/elbo.py,sha256=vVUFHNzKvUhvW6c-1GSf9YIYy1ZACeY9_Z8WX4qnqRg,16886
16
+ npll/inference/m_step.py,sha256=MG5LKPCcZHyYXr6SjuhKHDPxJOgPKobe_lS-RP_zOp8,22730
17
+ npll/scoring/__init__.py,sha256=y2JMOBGpVGMZRvL0K07OiH1RObARqu9RYkBEr06aCcE,1296
18
+ npll/scoring/embeddings.py,sha256=v6BID7cwjJ5i9-XnrKQ8WZV1YByrMCWaXsHTJQe9ZGQ,19478
19
+ npll/scoring/probability.py,sha256=lgokSRFE7Cu6p5mYFb_PlmjSONaRMwqx2h79hEokA7o,16799
20
+ npll/scoring/scoring_module.py,sha256=1hSNZzbnL6lw8ZYiglj8ok9pT_xQoDkCRIa8V51BwtU,13850
21
+ npll/training/__init__.py,sha256=BLR-CcMMdQ_v9uKHVNuErq2-xE4eRHynOfWaawJZgGA,641
22
+ npll/training/evaluation.py,sha256=rHPpofDOU5zYfbClrC3xrAMrYfDLrIYeMvh5IVZewFM,17155
23
+ npll/training/npll_trainer.py,sha256=1Nt-cdkM3LGLFbe0S87OX7GEzvpABXJbCHIVNObXoPo,17880
24
+ npll/utils/__init__.py,sha256=5xGn-xONVUiH8557_yTWwStBdNF46Yt2Pi7SHTPJa4c,1337
25
+ npll/utils/batch_utils.py,sha256=W1sXyX9b42YOmy-i_7Sv-4KkAIasf8Vip4qUSpKwc1Y,18498
26
+ npll/utils/config.py,sha256=b_s377KZ218jjS0_zWMgX92GkouOqbKk-LLpQHPb3z0,5134
27
+ npll/utils/math_utils.py,sha256=O2-rSZxFDI0WtD2EWx6dnA_YayHFW04WD91V-2d2CxQ,11398
28
+ odin/__init__.py,sha256=rV4ADDt5c43pVexCVcFB3OXlHXWLK3hc_xla2vSDpn8,670
29
+ odin/engine.py,sha256=fG0vof-wcHuU5vrRSnbkzv2l812EvhjXgOZulQFLsu8,9102
30
+ odin/schema.py,sha256=jmaaQRj94IHbppXdqtnIXv00lt3fLBHtZFrYhvqEslw,6524
31
+ odin_engine-0.2.0.dist-info/licenses/LICENSE,sha256=nTutNg_5r6C-zttxTWEYi8nTR8CmF8hMbszt-2qPlgs,1070
32
+ retrieval/__init__.py,sha256=Jf3-Dd82Xr4d78fCDYOpoQCAPCSZXDM_zxMWonp_d3g,2284
33
+ retrieval/adapters.py,sha256=ElU3FzadpeyDc7aajYQQN0QHCKHl5KM4ou_B83NRBXQ,5021
34
+ retrieval/adapters_arango.py,sha256=TP7_c8BeXGWxppyp3DkBCg2b45lOWB8ikwd7JU39zQg,53764
35
+ retrieval/aggregators.py,sha256=Efce66eDSdHiErpEXBzX2dffhdQxOe8IxnLQnUUsGac,23934
36
+ retrieval/beam.py,sha256=we5BV9NbKErFnYH8fOTRI5SklO2pOAycec2h2GW_X6I,4856
37
+ retrieval/budget.py,sha256=uLUUTGOc98q5Ll08_GLNMoLdpY69L33_y7QY6wJ8flQ,1474
38
+ retrieval/cache.py,sha256=OmDEFkOXjLCe5K5g-eiqtYjbslvV2pDJC0WV-DxDLrE,6107
39
+ retrieval/confidence.py,sha256=dlxU-dIK0IK01Y-EAr5xI7pZAbEbhYRdjBnA0_M_p1M,3272
40
+ retrieval/eval.py,sha256=j8_EaTaAFGPykhkIE3ruhbFzch7_1WJykDPTj4-q82M,1483
41
+ retrieval/linker.py,sha256=ZpZuTeLwKDgNWYXPPuPo7_D-af5-0L1-g6tMbFYzx4M,3210
42
+ retrieval/metrics.py,sha256=kDltG_Uu1Ows394Rcc0iWqNgsXbuFgfQSHnzfcevtjs,3288
43
+ retrieval/metrics_motifs.py,sha256=wqVPSpfoIx5F1L9sUX6_LNAy_6zlKg27wUPsQKVcU8I,1346
44
+ retrieval/orchestrator.py,sha256=jm4LzkhUL7P93BEpgPP16gZSkBYOOmMBqc3JAoLexjU,22493
45
+ retrieval/ppr.py,sha256=xR_ovxOIVPMXHcWw5FTkrhnCIzxDqXOOVR6CHjdP894,5376
46
+ retrieval/ppr_cache.py,sha256=mQCGDtwBu-Sw1eFoAfL3f1ryZSfIY2CCE4cMn5QwnsQ,760
47
+ retrieval/scoring.py,sha256=ilQnrmdZvrbQ58io7nIcwvKdDlY2LpbQf2WO8RkU6ys,11022
48
+ retrieval/ppr/__init__.py,sha256=O1f0pM9592kcC2CHRjSHYKO299zAY0RfunlUhk3K7mc,453
49
+ retrieval/ppr/anchors.py,sha256=l_4JuB1UBaTZu3jLvc0z5I0-0QMUDF6QZSoc-7I5DYI,1221
50
+ retrieval/ppr/bippr.py,sha256=byCxF4nCvnu__izsoof2aLSUxx2_sh9KLJd5ie6Ns30,2175
51
+ retrieval/ppr/engines.py,sha256=FzraG3A3Zh2d-iVWIEfnJIrKrNH_lLBYv3sTREYW5sE,10132
52
+ retrieval/ppr/global_pr.py,sha256=dABidLtuhAnfLdbJvSJnQKBbmdTO7woePL6xmQRh05k,2457
53
+ retrieval/ppr/indexes.py,sha256=w1xmqr6xw91WPvShooj3DBV_x1kQWh37kkstcgO1M7I,2480
54
+ retrieval/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
55
+ retrieval/utils/pii_redaction.py,sha256=hZyw_8HQM7yUsBm46yIBQCNT7Z-5xGqMXiVmR3ZqUqs,1224
56
+ retrieval/writers/__init__.py,sha256=DvTadpcfbz5-XUI2d8dsP6CoajuYPIJ8vuYpHdDpCKc,203
57
+ retrieval/writers/arango_writer.py,sha256=yfV8Q6EzI3Xso-moDYvt-NsjM5MITqmOkxUtm0cF3-4,1004
58
+ retrieval/writers/base.py,sha256=pe_fgsI6ic8LUyNl2vShjK-OhPEmn2XqZrNW5B-dd1Y,637
59
+ retrieval/writers/janus_writer.py,sha256=SmNEh3ebOZAuO8Iddcs2B7zA3r5GDnad4aMIdk5Wj20,1505
60
+ odin_engine-0.2.0.dist-info/METADATA,sha256=q6EtepkN-Y2v30MR7q1K6tVPj-ANcp3yAiMl_Dgu2Y4,17358
61
+ odin_engine-0.2.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
62
+ odin_engine-0.2.0.dist-info/top_level.txt,sha256=U53RwIYgQIJ0DBf_OaThVdHosqy06lkB4Zz4crmFadQ,31
63
+ odin_engine-0.2.0.dist-info/RECORD,,
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Prescott Data
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Prescott Data
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
retrieval/__init__.py CHANGED
@@ -1,50 +1,50 @@
1
- """
2
- Retrieval components: budgets, PPR, beam search, adapters, and confidence providers.
3
- """
4
-
5
- from .budget import SearchBudget, BudgetTracker
6
- from .adapters import GraphAccessor, KGCommunityAccessor, OverlayAccessor, JanusGraphAccessor
7
- from .adapters_arango import ArangoCommunityAccessor, GlobalGraphAccessor
8
- from .cache import CachedGraphAccessor
9
- from .confidence import EdgeConfidenceProvider, ConstantConfidence, NPLLConfidence
10
- from .ppr import (
11
- PushPPREngine, MonteCarloPPREngine, BiPPREngine, PPRParams,
12
- APPRAnchors, APPRAnchorParams,
13
- GlobalPR, GlobalPRParams,
14
- RandomWalkIndex, WalkIndexConfig,
15
- )
16
- from .beam import beam_search, BeamParams
17
- from .ppr_cache import PPRCache
18
- from .scoring import (
19
- PathScoreConfig, path_score,
20
- aggregate_evidence_strength,
21
- InsightScoreConfig, insight_score,
22
- score_paths_and_insight,
23
- )
24
- from .orchestrator import RetrievalOrchestrator, OrchestratorParams
25
- from .linker import CoherenceLinker, LinkerConfig, Mention
26
- from .metrics import MetricsLogger, JSONLSink, RetrievalMetrics, aggregate_latency_and_budget
27
- from .metrics_motifs import wedge_and_triad_closures
28
- from .eval import recall_at_k, expected_calibration_error, SimpleLLMCalibrator
29
- from .writers import PersistenceWriter, ArangoWriter, JanusGraphWriter
30
-
31
- __all__ = [
32
- 'GraphAccessor', 'KGCommunityAccessor', 'OverlayAccessor', 'JanusGraphAccessor',
33
- 'ArangoCommunityAccessor', 'GlobalGraphAccessor',
34
- 'CachedGraphAccessor',
35
- 'EdgeConfidenceProvider', 'ConstantConfidence', 'NPLLConfidence',
36
- 'PushPPREngine', 'MonteCarloPPREngine', 'BiPPREngine', 'PPRParams',
37
- 'APPRAnchors', 'APPRAnchorParams', 'GlobalPR', 'GlobalPRParams',
38
- 'RandomWalkIndex', 'WalkIndexConfig',
39
- 'beam_search', 'BeamParams',
40
- 'PPRCache',
41
- 'PathScoreConfig', 'path_score', 'aggregate_evidence_strength',
42
- 'InsightScoreConfig', 'insight_score', 'score_paths_and_insight',
43
- 'RetrievalOrchestrator', 'OrchestratorParams', 'CoherenceLinker', 'LinkerConfig', 'Mention',
44
- 'MetricsLogger', 'JSONLSink', 'RetrievalMetrics',
45
- 'aggregate_latency_and_budget', 'wedge_and_triad_closures',
46
- 'recall_at_k', 'expected_calibration_error', 'SimpleLLMCalibrator',
47
- 'PersistenceWriter', 'ArangoWriter', 'JanusGraphWriter',
48
- 'SearchBudget', 'BudgetTracker'
49
- ]
50
-
1
+ """
2
+ Retrieval components: budgets, PPR, beam search, adapters, and confidence providers.
3
+ """
4
+
5
+ from .budget import SearchBudget, BudgetTracker
6
+ from .adapters import GraphAccessor, KGCommunityAccessor, OverlayAccessor, JanusGraphAccessor
7
+ from .adapters_arango import ArangoCommunityAccessor, GlobalGraphAccessor
8
+ from .cache import CachedGraphAccessor
9
+ from .confidence import EdgeConfidenceProvider, ConstantConfidence, NPLLConfidence
10
+ from .ppr import (
11
+ PushPPREngine, MonteCarloPPREngine, BiPPREngine, PPRParams,
12
+ APPRAnchors, APPRAnchorParams,
13
+ GlobalPR, GlobalPRParams,
14
+ RandomWalkIndex, WalkIndexConfig,
15
+ )
16
+ from .beam import beam_search, BeamParams
17
+ from .ppr_cache import PPRCache
18
+ from .scoring import (
19
+ PathScoreConfig, path_score,
20
+ aggregate_evidence_strength,
21
+ InsightScoreConfig, insight_score,
22
+ score_paths_and_insight,
23
+ )
24
+ from .orchestrator import RetrievalOrchestrator, OrchestratorParams
25
+ from .linker import CoherenceLinker, LinkerConfig, Mention
26
+ from .metrics import MetricsLogger, JSONLSink, RetrievalMetrics, aggregate_latency_and_budget
27
+ from .metrics_motifs import wedge_and_triad_closures
28
+ from .eval import recall_at_k, expected_calibration_error, SimpleLLMCalibrator
29
+ from .writers import PersistenceWriter, ArangoWriter, JanusGraphWriter
30
+
31
+ __all__ = [
32
+ 'GraphAccessor', 'KGCommunityAccessor', 'OverlayAccessor', 'JanusGraphAccessor',
33
+ 'ArangoCommunityAccessor', 'GlobalGraphAccessor',
34
+ 'CachedGraphAccessor',
35
+ 'EdgeConfidenceProvider', 'ConstantConfidence', 'NPLLConfidence',
36
+ 'PushPPREngine', 'MonteCarloPPREngine', 'BiPPREngine', 'PPRParams',
37
+ 'APPRAnchors', 'APPRAnchorParams', 'GlobalPR', 'GlobalPRParams',
38
+ 'RandomWalkIndex', 'WalkIndexConfig',
39
+ 'beam_search', 'BeamParams',
40
+ 'PPRCache',
41
+ 'PathScoreConfig', 'path_score', 'aggregate_evidence_strength',
42
+ 'InsightScoreConfig', 'insight_score', 'score_paths_and_insight',
43
+ 'RetrievalOrchestrator', 'OrchestratorParams', 'CoherenceLinker', 'LinkerConfig', 'Mention',
44
+ 'MetricsLogger', 'JSONLSink', 'RetrievalMetrics',
45
+ 'aggregate_latency_and_budget', 'wedge_and_triad_closures',
46
+ 'recall_at_k', 'expected_calibration_error', 'SimpleLLMCalibrator',
47
+ 'PersistenceWriter', 'ArangoWriter', 'JanusGraphWriter',
48
+ 'SearchBudget', 'BudgetTracker'
49
+ ]
50
+
retrieval/adapters.py CHANGED
@@ -1,140 +1,140 @@
1
- from __future__ import annotations
2
- from typing import Iterable, Tuple, Protocol, List, Dict, Optional
3
- from gremlin_python.process.graph_traversal import __
4
- from gremlin_python.structure.graph import Graph
5
-
6
- NodeId = str
7
- RelId = str
8
-
9
-
10
- class GraphAccessor(Protocol):
11
- """
12
- Minimal graph view inside a single community/subgraph.
13
- Implement these methods for your KG.
14
- """
15
-
16
- def iter_out(self, node: NodeId) -> Iterable[Tuple[NodeId, RelId, float]]:
17
- """Yield (neighbor, relation, weight)."""
18
- ...
19
-
20
- def community_seed_norm(self, community_id: str, seeds: List[NodeId]) -> List[NodeId]:
21
- """Optional mapping from external IDs to internal; default passthrough."""
22
- return seeds
23
-
24
- def nodes(self, community_id: str) -> Iterable[NodeId]:
25
- """All node IDs in this community."""
26
- ...
27
-
28
- def degree(self, node: NodeId) -> int:
29
- """Fast out-degree if available; else len(list(iter_out(node)))."""
30
- ...
31
-
32
-
33
- class KGCommunityAccessor:
34
- """
35
- Example adapter to a KnowledgeGraph with a pre-sliced community.
36
- Provide a set of allowed node IDs (entity names) for the community.
37
- """
38
-
39
- def __init__(self, kg, community_id: str, community_nodes: Optional[set[str]] = None):
40
- self.kg = kg
41
- self.community_id = community_id
42
- self.allowed = community_nodes or set(n.name for n in kg.entities)
43
-
44
- def iter_out(self, node: NodeId):
45
- ent = self.kg.get_entity(node)
46
- if ent is None:
47
- return
48
- for triple in self.kg.get_facts_by_head(ent):
49
- v = triple.tail.name
50
- if v in self.allowed:
51
- yield v, triple.relation.name, 1.0
52
-
53
- def nodes(self, community_id: str):
54
- return list(self.allowed)
55
-
56
- def degree(self, node: NodeId) -> int:
57
- ent = self.kg.get_entity(node)
58
- if ent is None:
59
- return 0
60
- return sum(1 for t in self.kg.get_facts_by_head(ent) if t.tail.name in self.allowed)
61
-
62
-
63
- class OverlayAccessor:
64
- """
65
- Wrap a base GraphAccessor with soft overlay edges.
66
- Overlay edges are tuples (u, rel, v, weight) scoped to a community.
67
- """
68
-
69
- def __init__(self, base: GraphAccessor, community_id: str):
70
- self.base = base
71
- self.cid = community_id
72
- self._overlay: dict[NodeId, list[tuple[NodeId, str, float]]] = {}
73
-
74
- def add_edge(self, u: NodeId, rel: str, v: NodeId, weight: float = 1.0):
75
- self._overlay.setdefault(u, []).append((v, rel, weight))
76
-
77
- def iter_out(self, node: NodeId):
78
- # Base edges
79
- for v, r, w in self.base.iter_out(node):
80
- yield v, r, w
81
- # Overlay edges
82
- for v, r, w in self._overlay.get(node, []):
83
- yield v, r, w
84
-
85
- def community_seed_norm(self, community_id: str, seeds: list[NodeId]) -> list[NodeId]:
86
- return getattr(self.base, 'community_seed_norm', lambda cid, s: s)(community_id, seeds)
87
-
88
- def nodes(self, community_id: str):
89
- return getattr(self.base, 'nodes', lambda cid: [])(community_id)
90
-
91
- def degree(self, node: NodeId) -> int:
92
- base_deg = getattr(self.base, 'degree', lambda n: 0)(node)
93
- return base_deg + len(self._overlay.get(node, []))
94
-
95
-
96
- class JanusGraphAccessor(GraphAccessor):
97
- """
98
- GraphAccessor implementation for JanusGraph.
99
- Assumes connection to a JanusGraph instance via a Gremlin client.
100
- """
101
- def __init__(self, graph: Graph, community_id_property: str = "communityId"):
102
- self.g = graph.traversal()
103
- self.community_id_property = community_id_property
104
-
105
- def iter_out(self, node: NodeId) -> Iterable[Tuple[NodeId, RelId, float]]:
106
- """
107
- Yields (neighbor, relation, weight) for outgoing edges from a node.
108
- Example Gremlin query: g.V(node).outE().as_('e').inV().as_('v').select('e', 'v')
109
- """
110
- traversal = self.g.V(node).outE().as_('e').inV().as_('v').select('e', 'v').toList()
111
- for edge, neighbor in traversal:
112
- # Note: You might need to adjust how you access IDs and properties based on your graph schema
113
- neighbor_id = neighbor.id
114
- rel_id = edge.label
115
- weight = edge.properties.get('weight', 1.0)
116
- yield neighbor_id, rel_id, weight
117
-
118
- def nodes(self, community_id: str) -> Iterable[NodeId]:
119
- """
120
- Yields all node IDs in a given community.
121
- Example Gremlin query: g.V().has('communityId', community_id).id()
122
- """
123
- traversal = self.g.V().has(self.community_id_property, community_id).id().toList()
124
- for node_id in traversal:
125
- yield node_id
126
-
127
- def degree(self, node: NodeId) -> int:
128
- """
129
- Returns the out-degree of a node.
130
- Example Gremlin query: g.V(node).outE().count()
131
- """
132
- return self.g.V(node).outE().count().next()
133
-
134
- def in_degree(self, node: NodeId) -> int:
135
- """
136
- Returns the in-degree of a node.
137
- Example Gremlin query: g.V(node).inE().count()
138
- """
139
- return self.g.V(node).inE().count().next()
140
-
1
+ from __future__ import annotations
2
+ from typing import Iterable, Tuple, Protocol, List, Dict, Optional
3
+ from gremlin_python.process.graph_traversal import __
4
+ from gremlin_python.structure.graph import Graph
5
+
6
+ NodeId = str
7
+ RelId = str
8
+
9
+
10
+ class GraphAccessor(Protocol):
11
+ """
12
+ Minimal graph view inside a single community/subgraph.
13
+ Implement these methods for your KG.
14
+ """
15
+
16
+ def iter_out(self, node: NodeId) -> Iterable[Tuple[NodeId, RelId, float]]:
17
+ """Yield (neighbor, relation, weight)."""
18
+ ...
19
+
20
+ def community_seed_norm(self, community_id: str, seeds: List[NodeId]) -> List[NodeId]:
21
+ """Optional mapping from external IDs to internal; default passthrough."""
22
+ return seeds
23
+
24
+ def nodes(self, community_id: str) -> Iterable[NodeId]:
25
+ """All node IDs in this community."""
26
+ ...
27
+
28
+ def degree(self, node: NodeId) -> int:
29
+ """Fast out-degree if available; else len(list(iter_out(node)))."""
30
+ ...
31
+
32
+
33
+ class KGCommunityAccessor:
34
+ """
35
+ Example adapter to a KnowledgeGraph with a pre-sliced community.
36
+ Provide a set of allowed node IDs (entity names) for the community.
37
+ """
38
+
39
+ def __init__(self, kg, community_id: str, community_nodes: Optional[set[str]] = None):
40
+ self.kg = kg
41
+ self.community_id = community_id
42
+ self.allowed = community_nodes or set(n.name for n in kg.entities)
43
+
44
+ def iter_out(self, node: NodeId):
45
+ ent = self.kg.get_entity(node)
46
+ if ent is None:
47
+ return
48
+ for triple in self.kg.get_facts_by_head(ent):
49
+ v = triple.tail.name
50
+ if v in self.allowed:
51
+ yield v, triple.relation.name, 1.0
52
+
53
+ def nodes(self, community_id: str):
54
+ return list(self.allowed)
55
+
56
+ def degree(self, node: NodeId) -> int:
57
+ ent = self.kg.get_entity(node)
58
+ if ent is None:
59
+ return 0
60
+ return sum(1 for t in self.kg.get_facts_by_head(ent) if t.tail.name in self.allowed)
61
+
62
+
63
+ class OverlayAccessor:
64
+ """
65
+ Wrap a base GraphAccessor with soft overlay edges.
66
+ Overlay edges are tuples (u, rel, v, weight) scoped to a community.
67
+ """
68
+
69
+ def __init__(self, base: GraphAccessor, community_id: str):
70
+ self.base = base
71
+ self.cid = community_id
72
+ self._overlay: dict[NodeId, list[tuple[NodeId, str, float]]] = {}
73
+
74
+ def add_edge(self, u: NodeId, rel: str, v: NodeId, weight: float = 1.0):
75
+ self._overlay.setdefault(u, []).append((v, rel, weight))
76
+
77
+ def iter_out(self, node: NodeId):
78
+ # Base edges
79
+ for v, r, w in self.base.iter_out(node):
80
+ yield v, r, w
81
+ # Overlay edges
82
+ for v, r, w in self._overlay.get(node, []):
83
+ yield v, r, w
84
+
85
+ def community_seed_norm(self, community_id: str, seeds: list[NodeId]) -> list[NodeId]:
86
+ return getattr(self.base, 'community_seed_norm', lambda cid, s: s)(community_id, seeds)
87
+
88
+ def nodes(self, community_id: str):
89
+ return getattr(self.base, 'nodes', lambda cid: [])(community_id)
90
+
91
+ def degree(self, node: NodeId) -> int:
92
+ base_deg = getattr(self.base, 'degree', lambda n: 0)(node)
93
+ return base_deg + len(self._overlay.get(node, []))
94
+
95
+
96
+ class JanusGraphAccessor(GraphAccessor):
97
+ """
98
+ GraphAccessor implementation for JanusGraph.
99
+ Assumes connection to a JanusGraph instance via a Gremlin client.
100
+ """
101
+ def __init__(self, graph: Graph, community_id_property: str = "communityId"):
102
+ self.g = graph.traversal()
103
+ self.community_id_property = community_id_property
104
+
105
+ def iter_out(self, node: NodeId) -> Iterable[Tuple[NodeId, RelId, float]]:
106
+ """
107
+ Yields (neighbor, relation, weight) for outgoing edges from a node.
108
+ Example Gremlin query: g.V(node).outE().as_('e').inV().as_('v').select('e', 'v')
109
+ """
110
+ traversal = self.g.V(node).outE().as_('e').inV().as_('v').select('e', 'v').toList()
111
+ for edge, neighbor in traversal:
112
+ # Note: You might need to adjust how you access IDs and properties based on your graph schema
113
+ neighbor_id = neighbor.id
114
+ rel_id = edge.label
115
+ weight = edge.properties.get('weight', 1.0)
116
+ yield neighbor_id, rel_id, weight
117
+
118
+ def nodes(self, community_id: str) -> Iterable[NodeId]:
119
+ """
120
+ Yields all node IDs in a given community.
121
+ Example Gremlin query: g.V().has('communityId', community_id).id()
122
+ """
123
+ traversal = self.g.V().has(self.community_id_property, community_id).id().toList()
124
+ for node_id in traversal:
125
+ yield node_id
126
+
127
+ def degree(self, node: NodeId) -> int:
128
+ """
129
+ Returns the out-degree of a node.
130
+ Example Gremlin query: g.V(node).outE().count()
131
+ """
132
+ return self.g.V(node).outE().count().next()
133
+
134
+ def in_degree(self, node: NodeId) -> int:
135
+ """
136
+ Returns the in-degree of a node.
137
+ Example Gremlin query: g.V(node).inE().count()
138
+ """
139
+ return self.g.V(node).inE().count().next()
140
+