- stage1: OCR 591 страниц DjVu через Tesseract (rus+lat) - stage2: сегментация на 158 статей о растениях - stage3: LLM-извлечение структурированных данных (GLM-4.5-air) - stage4: граф знаний (NetworkX), community detection, co-occurrence - stage4b: извлечение связей болезнь→растение из Главы IV - enrich_families: обогащение таксономией (род→семейство) - visualize: 4 интерактивных HTML-графа (pyvis) - output: отчёт, анализ, визуализации Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
359 lines
14 KiB
Python
359 lines
14 KiB
Python
"""Stage 4: Build knowledge graph and discover patterns.
|
|
|
|
Builds a NetworkX graph from extracted plant data,
|
|
runs graph algorithms and statistical analysis to find
|
|
hidden patterns and non-obvious correlations.
|
|
"""
|
|
|
|
import json
|
|
import sys
|
|
from collections import Counter, defaultdict
|
|
from itertools import combinations
|
|
from pathlib import Path
|
|
|
|
import networkx as nx
|
|
|
|
from config import EXTRACTED_DIR, OUTPUT_DIR
|
|
|
|
|
|
def load_plants(path: Path) -> list[dict]:
|
|
"""Load all extracted plant data."""
|
|
f = path / "all_plants.json"
|
|
if not f.exists():
|
|
print(f"ERROR: {f} not found. Run stage3_extract.py first.")
|
|
sys.exit(1)
|
|
return json.loads(f.read_text())
|
|
|
|
|
|
def build_graph(plants: list[dict]) -> nx.Graph:
|
|
"""Build knowledge graph from plant data + Chapter IV."""
|
|
G = nx.Graph()
|
|
|
|
for p in plants:
|
|
pid = p["name_latin"] or p["name_ru"]
|
|
G.add_node(pid, type="plant", **{k: v for k, v in p.items()
|
|
if k not in ("raw_text",)})
|
|
|
|
# Chemical connections
|
|
for chem in p.get("chemicals", []):
|
|
chem_lower = chem.lower().strip()
|
|
if chem_lower:
|
|
G.add_node(chem_lower, type="chemical")
|
|
G.add_edge(pid, chem_lower, rel="CONTAINS")
|
|
|
|
# Medicinal property connections
|
|
for prop in p.get("medicinal_properties", []):
|
|
prop_lower = prop.lower().strip()
|
|
if prop_lower:
|
|
G.add_node(prop_lower, type="property")
|
|
G.add_edge(pid, prop_lower, rel="HAS_PROPERTY")
|
|
|
|
# Disease connections
|
|
for disease in p.get("diseases", []):
|
|
dis_lower = disease.lower().strip()
|
|
if dis_lower:
|
|
G.add_node(dis_lower, type="disease")
|
|
G.add_edge(pid, dis_lower, rel="TREATS")
|
|
|
|
# Habitat connections
|
|
for hab in p.get("habitat", []):
|
|
hab_lower = hab.lower().strip()
|
|
if hab_lower:
|
|
G.add_node(hab_lower, type="habitat")
|
|
G.add_edge(pid, hab_lower, rel="GROWS_IN")
|
|
|
|
# Add Chapter IV disease→plant links
|
|
ch4_file = EXTRACTED_DIR / "chapter4_disease_plants.json"
|
|
if ch4_file.exists():
|
|
ch4_data = json.loads(ch4_file.read_text())
|
|
ch4_links = 0
|
|
for entry in ch4_data:
|
|
disease = entry["disease"].lower().strip()
|
|
G.add_node(disease, type="disease")
|
|
for plant_latin in entry["plants"]:
|
|
if plant_latin in G:
|
|
G.add_edge(plant_latin, disease, rel="TREATS_CH4")
|
|
ch4_links += 1
|
|
print(f" Added {ch4_links} links from Chapter IV")
|
|
|
|
return G
|
|
|
|
|
|
def analyze_communities(G: nx.Graph, plants_set: set) -> list[dict]:
|
|
"""Find plant communities using Louvain algorithm."""
|
|
if len(G.nodes) < 3:
|
|
return []
|
|
|
|
communities = nx.community.louvain_communities(G, seed=42)
|
|
results = []
|
|
|
|
for i, comm in enumerate(communities):
|
|
comm_plants = [n for n in comm if n in plants_set]
|
|
comm_chemicals = [n for n in comm if G.nodes[n].get("type") == "chemical"]
|
|
comm_diseases = [n for n in comm if G.nodes[n].get("type") == "disease"]
|
|
comm_properties = [n for n in comm if G.nodes[n].get("type") == "property"]
|
|
|
|
if len(comm_plants) >= 2:
|
|
results.append({
|
|
"community_id": i,
|
|
"plants": comm_plants,
|
|
"shared_chemicals": comm_chemicals,
|
|
"shared_diseases": comm_diseases,
|
|
"shared_properties": comm_properties,
|
|
"size": len(comm),
|
|
})
|
|
|
|
return sorted(results, key=lambda x: len(x["plants"]), reverse=True)
|
|
|
|
|
|
def find_central_nodes(G: nx.Graph) -> dict:
|
|
"""Find most connected chemicals, diseases, and properties."""
|
|
result = {}
|
|
for node_type in ["chemical", "disease", "property"]:
|
|
nodes = [n for n, d in G.nodes(data=True) if d.get("type") == node_type]
|
|
if not nodes:
|
|
continue
|
|
centrality = {n: G.degree(n) for n in nodes}
|
|
top = sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:15]
|
|
result[node_type] = top
|
|
return result
|
|
|
|
|
|
def find_cooccurrences(plants: list[dict], field: str, min_count: int = 3) -> list[dict]:
|
|
"""Find pairs of items that frequently co-occur across plants."""
|
|
pair_counts = Counter()
|
|
item_counts = Counter()
|
|
|
|
for p in plants:
|
|
items = [x.lower().strip() for x in p.get(field, []) if x.strip()]
|
|
item_counts.update(items)
|
|
for a, b in combinations(sorted(set(items)), 2):
|
|
pair_counts[(a, b)] += 1
|
|
|
|
results = []
|
|
for (a, b), count in pair_counts.most_common(20):
|
|
if count >= min_count:
|
|
results.append({
|
|
"pair": [a, b],
|
|
"co_occurrences": count,
|
|
"a_total": item_counts[a],
|
|
"b_total": item_counts[b],
|
|
"jaccard": count / (item_counts[a] + item_counts[b] - count),
|
|
})
|
|
|
|
return results
|
|
|
|
|
|
def find_anomalies(plants: list[dict]) -> list[dict]:
|
|
"""Find plants that are unusual within their family or general patterns."""
|
|
# Group plants by family
|
|
family_chemicals = defaultdict(lambda: defaultdict(int))
|
|
family_plants = defaultdict(list)
|
|
|
|
for p in plants:
|
|
family = (p.get("family_ru") or "unknown").lower()
|
|
family_plants[family].append(p)
|
|
for chem in p.get("chemicals", []):
|
|
family_chemicals[family][chem.lower().strip()] += 1
|
|
|
|
anomalies = []
|
|
for family, members in family_plants.items():
|
|
if len(members) < 3 or family == "unknown":
|
|
continue
|
|
|
|
# Find chemicals common in family (>60% of members)
|
|
common_chems = {
|
|
chem for chem, count in family_chemicals[family].items()
|
|
if count / len(members) > 0.6
|
|
}
|
|
|
|
# Find members missing common chemicals
|
|
for p in members:
|
|
plant_chems = {c.lower().strip() for c in p.get("chemicals", [])}
|
|
missing = common_chems - plant_chems
|
|
if missing and plant_chems: # has some chemicals but missing common ones
|
|
anomalies.append({
|
|
"plant": p.get("name_latin") or p["name_ru"],
|
|
"family": family,
|
|
"missing_common_chemicals": list(missing),
|
|
"has_chemicals": list(plant_chems),
|
|
"family_size": len(members),
|
|
})
|
|
|
|
return anomalies
|
|
|
|
|
|
def find_cross_family_similarity(plants: list[dict]) -> list[dict]:
|
|
"""Find plants from different families with similar chemical/disease profiles."""
|
|
results = []
|
|
|
|
for i, p1 in enumerate(plants):
|
|
for p2 in plants[i + 1:]:
|
|
f1 = (p1.get("family_ru") or "").lower()
|
|
f2 = (p2.get("family_ru") or "").lower()
|
|
if not f1 or not f2 or f1 == f2:
|
|
continue
|
|
|
|
# Compare chemical profiles
|
|
chems1 = {c.lower().strip() for c in p1.get("chemicals", []) if c.strip()}
|
|
chems2 = {c.lower().strip() for c in p2.get("chemicals", []) if c.strip()}
|
|
|
|
if len(chems1) < 2 or len(chems2) < 2:
|
|
continue
|
|
|
|
intersection = chems1 & chems2
|
|
union = chems1 | chems2
|
|
jaccard = len(intersection) / len(union) if union else 0
|
|
|
|
if jaccard > 0.3 and len(intersection) >= 3:
|
|
results.append({
|
|
"plant1": p1.get("name_latin") or p1["name_ru"],
|
|
"family1": f1,
|
|
"plant2": p2.get("name_latin") or p2["name_ru"],
|
|
"family2": f2,
|
|
"shared_chemicals": list(intersection),
|
|
"jaccard_similarity": round(jaccard, 3),
|
|
})
|
|
|
|
return sorted(results, key=lambda x: x["jaccard_similarity"], reverse=True)[:20]
|
|
|
|
|
|
def generate_report(
|
|
plants: list[dict],
|
|
communities: list[dict],
|
|
central: dict,
|
|
chem_cooccurrences: list[dict],
|
|
disease_cooccurrences: list[dict],
|
|
anomalies: list[dict],
|
|
cross_family: list[dict],
|
|
) -> str:
|
|
"""Generate human-readable analysis report."""
|
|
lines = []
|
|
lines.append("# Анализ: Земли Тюменской травы целебные")
|
|
lines.append(f"\nВсего растений в базе: {len(plants)}\n")
|
|
|
|
# Communities
|
|
lines.append("## 1. Кластеры растений (community detection)")
|
|
lines.append("Растения, объединённые общими химикатами, свойствами и болезнями:\n")
|
|
for c in communities[:10]:
|
|
lines.append(f"### Кластер #{c['community_id']} ({len(c['plants'])} растений)")
|
|
lines.append(f"- Растения: {', '.join(c['plants'][:10])}")
|
|
if c["shared_chemicals"]:
|
|
lines.append(f"- Общие химикаты: {', '.join(c['shared_chemicals'][:10])}")
|
|
if c["shared_diseases"]:
|
|
lines.append(f"- Общие болезни: {', '.join(c['shared_diseases'][:10])}")
|
|
if c["shared_properties"]:
|
|
lines.append(f"- Общие свойства: {', '.join(c['shared_properties'][:10])}")
|
|
lines.append("")
|
|
|
|
# Central nodes
|
|
lines.append("## 2. Самые «центральные» узлы")
|
|
for node_type, top in central.items():
|
|
type_name = {"chemical": "Химические вещества", "disease": "Заболевания",
|
|
"property": "Лечебные свойства"}.get(node_type, node_type)
|
|
lines.append(f"\n### {type_name} (по количеству связей с растениями)")
|
|
for name, degree in top:
|
|
lines.append(f"- **{name}**: {degree} растений")
|
|
|
|
# Co-occurrences
|
|
lines.append("\n## 3. Ко-встречаемость (co-occurrence)")
|
|
if chem_cooccurrences:
|
|
lines.append("\n### Химикаты, которые часто встречаются вместе")
|
|
for co in chem_cooccurrences[:10]:
|
|
lines.append(
|
|
f"- **{co['pair'][0]}** + **{co['pair'][1]}**: "
|
|
f"{co['co_occurrences']} растений (Jaccard={co['jaccard']:.2f})"
|
|
)
|
|
if disease_cooccurrences:
|
|
lines.append("\n### Заболевания, которые лечат одними растениями")
|
|
for co in disease_cooccurrences[:10]:
|
|
lines.append(
|
|
f"- **{co['pair'][0]}** + **{co['pair'][1]}**: "
|
|
f"{co['co_occurrences']} растений (Jaccard={co['jaccard']:.2f})"
|
|
)
|
|
|
|
# Anomalies
|
|
if anomalies:
|
|
lines.append("\n## 4. Аномалии внутри семейств")
|
|
lines.append("Растения, не вписывающиеся в химический профиль своего семейства:\n")
|
|
for a in anomalies[:10]:
|
|
lines.append(
|
|
f"- **{a['plant']}** (сем. {a['family']}, {a['family_size']} видов): "
|
|
f"отсутствуют обычные: {', '.join(a['missing_common_chemicals'])}"
|
|
)
|
|
|
|
# Cross-family similarity
|
|
if cross_family:
|
|
lines.append("\n## 5. Межсемейственное сходство")
|
|
lines.append("Растения из РАЗНЫХ семейств с похожим химическим составом:\n")
|
|
for cf in cross_family[:10]:
|
|
lines.append(
|
|
f"- **{cf['plant1']}** ({cf['family1']}) ↔ **{cf['plant2']}** ({cf['family2']}): "
|
|
f"общие: {', '.join(cf['shared_chemicals'])} (Jaccard={cf['jaccard_similarity']})"
|
|
)
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
def main():
|
|
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
plants = load_plants(EXTRACTED_DIR)
|
|
print(f"Loaded {len(plants)} plants")
|
|
|
|
# Build graph
|
|
G = build_graph(plants)
|
|
print(f"Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
|
|
|
|
plants_set = {p.get("name_latin") or p["name_ru"] for p in plants}
|
|
|
|
# Analysis
|
|
print("Running community detection...")
|
|
communities = analyze_communities(G, plants_set)
|
|
|
|
print("Finding central nodes...")
|
|
central = find_central_nodes(G)
|
|
|
|
print("Finding chemical co-occurrences...")
|
|
chem_co = find_cooccurrences(plants, "chemicals")
|
|
|
|
print("Finding disease co-occurrences...")
|
|
disease_co = find_cooccurrences(plants, "diseases")
|
|
|
|
print("Finding family anomalies...")
|
|
anomalies = find_anomalies(plants)
|
|
|
|
print("Finding cross-family similarities...")
|
|
cross_family = find_cross_family_similarity(plants)
|
|
|
|
# Generate report
|
|
report = generate_report(plants, communities, central, chem_co, disease_co, anomalies, cross_family)
|
|
report_file = OUTPUT_DIR / "report.md"
|
|
report_file.write_text(report, encoding="utf-8")
|
|
print(f"\nReport saved to {report_file}")
|
|
|
|
# Save raw analysis data
|
|
analysis = {
|
|
"communities": communities,
|
|
"central_nodes": central,
|
|
"chemical_cooccurrences": chem_co,
|
|
"disease_cooccurrences": disease_co,
|
|
"anomalies": anomalies,
|
|
"cross_family_similarity": cross_family,
|
|
}
|
|
analysis_file = OUTPUT_DIR / "analysis.json"
|
|
analysis_file.write_text(json.dumps(analysis, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print(f"Raw analysis saved to {analysis_file}")
|
|
|
|
# Print summary
|
|
print(f"\n{'='*60}")
|
|
print(f"Кластеров: {len(communities)}")
|
|
print(f"Химических ко-паттернов: {len(chem_co)}")
|
|
print(f"Паттернов болезней: {len(disease_co)}")
|
|
print(f"Аномалий в семействах: {len(anomalies)}")
|
|
print(f"Межсемейственных сходств: {len(cross_family)}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|