Files
smartguide/service/scripts/falkordb/bulk_load.py
T
arzani 552fa2daaf
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
Added fakordb tests
2026-11-03 13:50:10 +01:00

1011 lines
55 KiB
Python

"""
bulk_load.py — Build the whole-university graph in FalkorDB with bulk extraction.
Instead of calling the per-researcher REST logic 6,000 times, this scans the Elasticsearch
mirrors once per source and streams nodes/edges into FalkorDB in batches:
cohort active researchers of the institution (backend membership query) + profile,
affiliations, topics -> Author(:Cohort), Institution, Topic
works every work of every cohort researcher, with all authorships, institutions,
topics, venue, funders/awards -> Work, Author, Venue, Funder, ...
institutions names/countries for institutions known only as lineage ancestors -> Institution props
affiliations per-work affiliations: AUTHORED.institution_ids, (Work)-[:INVOLVES]->(Institution)
classifications LLM work classifications (primary category, Pasteur quadrant, ...) -> Work props
projects CORDIS + DFG projects via publication DOIs, institution-level participations,
DFG persons matched by ORCID, project details and EU consortium partners
patents pre-matched org_patents index -> Patent, INVENTOR_OF
news UDE news mentions by display name (bulk) -> NewsArticle, MENTIONED_IN
companies Handelsregister officer matches per researcher -> Company, OFFICER_OF
hierarchy OpenAlex domain/field/subfield tree -> Domain, Field, Subfield
derive CO_AUTHOR, Author-FUNDED_BY, Author-CONTRIBUTED_TO computed inside FalkorDB
profile (Institution)-[:ACTIVE_IN {works, researchers}]->(Topic|Subfield|Field|Domain)
Co-author policy: every authorship becomes an AUTHORED edge. CO_AUTHOR pairs are derived for all
author pairs on works with <= --pair-cap authors, and for pairs involving a cohort member on larger
works (all pairs on 5,000-author papers would be billions of edges).
Usage (see run.sh):
python scripts/falkordb/bulk_load.py --graph ude --reset
python scripts/falkordb/bulk_load.py --graph ude_test --reset --limit-authors 25 # smoke test
python scripts/falkordb/bulk_load.py --graph ude --phases derive # re-run one phase
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import os
import sqlite3
import sys
import tempfile
import time
from collections import Counter, defaultdict
from datetime import date, datetime
from pathlib import Path
from typing import Any
_current_dir = Path(__file__).resolve().parent
_service_dir = _current_dir.parent.parent
_src_main = _service_dir / "src" / "main"
if not (_src_main / "inse").is_dir():
_src_main = Path(os.environ.get("INSE_SRC_DIR", "/home"))
sys.path.insert(0, str(_src_main))
from dotenv import load_dotenv # noqa: E402
_env_file = _src_main / "inse" / ".env"
if _env_file.exists():
load_dotenv(dotenv_path=_env_file)
from inse.authors.institution_membership_query import ( # noqa: E402
build_institution_membership_query,
current_affiliation_year_cutoff,
)
from inse.company_connections.logic import get_company_connections_by_author_id # noqa: E402
from inse.dashboard.top_authors_service import _dfg_institution_ids_for_organization # noqa: E402
from inse.institutions.institutions_search_client import InstitutionsSearchClient # noqa: E402
from inse.institutions.v2.service import get_institution_by_id # noqa: E402
from inse.integrations import elasticsearch # noqa: E402
from inse.model import ESCluster, ESIndex # noqa: E402
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient # noqa: E402
from inse.projects.projects_search_client import ( # noqa: E402
get_cordis_eu_publications_by_dois,
get_dfg_publications_by_dois,
)
from inse.topics.v2.service import get_topic_hierarchy # noqa: E402
from inse.works.v2.service import search_work_classifications # noqa: E402
logger = logging.getLogger("falkordb.bulk_load")
OPENALEX_PREFIX = "https://openalex.org/"
PREDEFINED_ACCOUNTS = _src_main.parent / "data" / "predefined_accounts.json"
PHASES = ("cohort", "works", "institutions", "affiliations", "classifications", "projects", "patents", "news", "companies", "hierarchy", "derive", "profile")
WORK_SOURCE_FIELDS = [
"id", "doi", "title", "publication_year", "type", "language", "cited_by_count", "authors_count", "fwci",
"open_access.is_oa", "primary_location.source.id", "primary_location.source.display_name",
"primary_location.source.type", "primary_location.source.issn_l", "primary_location.source.host_organization_name",
"authorships.author", "authorships.author_position", "authorships.is_corresponding",
"authorships.institutions.id", "authorships.institutions.display_name", "authorships.institutions.country_code",
"authorships.institutions.type", "authorships.institutions.lineage",
"topics", "funders", "awards",
]
# --------------------------------------------------------------------------- helpers
def short_id(raw: str | None) -> str | None:
if not raw:
return None
return str(raw).strip().removeprefix(OPENALEX_PREFIX)
def raw_doi(doi: str) -> str:
for prefix in ("https://doi.org/", "http://doi.org/", "http://dx.doi.org/", "https://dx.doi.org/"):
if doi.startswith(prefix):
return doi[len(prefix):]
return doi
def _scalar(value: Any) -> Any:
if isinstance(value, (date, datetime)):
return value.isoformat()
if isinstance(value, str):
return value[:2000]
if isinstance(value, (bool, int, float)):
return value
return str(value)
def clean_props(props: dict[str, Any] | None) -> dict[str, Any]:
cleaned: dict[str, Any] = {}
for key, value in (props or {}).items():
if value is None or isinstance(value, dict):
continue
if isinstance(value, (list, tuple, set)):
cleaned[key] = [_scalar(v) for v in value if v is not None and not isinstance(v, dict)]
else:
cleaned[key] = _scalar(value)
return cleaned
def chunks(items: list, size: int):
for start in range(0, len(items), size):
yield items[start:start + size]
def topic_props(topic: dict[str, Any]) -> dict[str, Any]:
return {
"name": topic.get("display_name"),
"subfield": (topic.get("subfield") or {}).get("display_name"),
"subfield_id": short_id((topic.get("subfield") or {}).get("id")),
"field": (topic.get("field") or {}).get("display_name"),
"field_id": short_id((topic.get("field") or {}).get("id")),
"domain": (topic.get("domain") or {}).get("display_name"),
"domain_id": short_id((topic.get("domain") or {}).get("id")),
}
# --------------------------------------------------------------------------- FalkorDB writer
class GraphWriter:
"""Buffers node/edge rows and writes them with batched UNWIND ... MERGE queries.
Node buffers are always flushed before edge buffers, so an edge may reference any node
queued earlier in the same run."""
def __init__(self, host: str, port: int, password: str | None, name: str, reset: bool,
batch_size: int = 2000, timeout_ms: int = 600_000):
from falkordb import FalkorDB
self.db = FalkorDB(host=host, port=port, password=password)
self.name = name
if reset and name in self.db.list_graphs():
self.db.select_graph(name).delete()
logger.info("Deleted existing graph %r", name)
self.graph = self.db.select_graph(name)
self.batch_size = batch_size
self.timeout_ms = timeout_ms
self.node_buffers: dict[tuple[str, str], list[dict]] = defaultdict(list)
self.edge_buffers: dict[tuple[str, str, str], list[dict]] = defaultdict(list)
self.buffered = 0
self.stats: Counter = Counter()
self.query_time = 0.0
def run(self, query: str, params: dict | None = None, timeout_ms: int | None = None):
started = time.perf_counter()
result = self.graph.query(query, params or {}, timeout=timeout_ms or self.timeout_ms)
self.query_time += time.perf_counter() - started
self.stats["nodes_created"] += int(result.nodes_created or 0)
self.stats["relationships_created"] += int(result.relationships_created or 0)
self.stats["properties_set"] += int(result.properties_set or 0)
return result
def ro(self, query: str, params: dict | None = None):
return self.graph.ro_query(query, params or {}, timeout=self.timeout_ms)
def ro_all(self, query: str, params: dict | None = None, page: int = 5000) -> list:
"""Paged read for result sets larger than the server's RESULTSET_SIZE cap.
`query` must end with an ORDER BY clause; SKIP/LIMIT are appended here."""
rows: list = []
skip = 0
while True:
chunk = self.graph.ro_query(f"{query} SKIP {skip} LIMIT {page}", params or {}, timeout=self.timeout_ms).result_set
rows.extend(chunk)
if len(chunk) < page:
return rows
skip += page
def ensure_indexes(self, labels: list[str], extra: list[tuple[str, str]] = ()) -> None:
from redis.exceptions import ResponseError
for label, prop in [(label, "id") for label in labels] + list(extra):
try:
self.graph.query(f"CREATE INDEX FOR (n:{label}) ON (n.{prop})")
except ResponseError as exc:
if "already indexed" not in str(exc):
raise
def node(self, label: str, node_id: str | None, props: dict | None = None, mode: str = "set") -> None:
"""mode: 'set' (MERGE + SET), 'create' (MERGE + ON CREATE SET), 'update' (MATCH + SET)."""
if not node_id:
return
self.node_buffers[(label, mode)].append({"id": node_id, "props": clean_props(props)})
self.buffered += 1
if self.buffered >= self.batch_size * 8:
self.flush()
def edge(self, src_label: str, src: str | None, rel: str, dst_label: str, dst: str | None,
props: dict | None = None) -> None:
if not src or not dst:
return
self.edge_buffers[(src_label, rel, dst_label)].append({"src": src, "dst": dst, "props": clean_props(props)})
self.buffered += 1
if self.buffered >= self.batch_size * 8:
self.flush()
def flush(self) -> None:
for (label, mode), rows in list(self.node_buffers.items()):
if not rows:
continue
if mode == "create":
query = f"UNWIND $rows AS r MERGE (n:{label} {{id: r.id}}) ON CREATE SET n += r.props"
elif mode == "update":
query = f"UNWIND $rows AS r MATCH (n:{label} {{id: r.id}}) SET n += r.props"
else:
query = f"UNWIND $rows AS r MERGE (n:{label} {{id: r.id}}) SET n += r.props"
for chunk in chunks(rows, self.batch_size):
self.run(query, {"rows": chunk})
self.node_buffers[(label, mode)] = []
for (src_label, rel, dst_label), rows in list(self.edge_buffers.items()):
if not rows:
continue
query = (f"UNWIND $rows AS r MATCH (a:{src_label} {{id: r.src}}), (b:{dst_label} {{id: r.dst}}) "
f"MERGE (a)-[e:{rel}]->(b) SET e += r.props")
for chunk in chunks(rows, self.batch_size):
self.run(query, {"rows": chunk})
self.edge_buffers[(src_label, rel, dst_label)] = []
self.buffered = 0
def label_counts(self) -> tuple[list, list]:
nodes = self.ro("MATCH (n) RETURN labels(n)[0] AS l, count(n) ORDER BY count(n) DESC").result_set
rels = self.ro("MATCH ()-[r]->() RETURN type(r), count(r) ORDER BY count(r) DESC").result_set
return nodes, rels
# --------------------------------------------------------------------------- shared state
class State:
def __init__(self) -> None:
self.cohort_ids: list[str] = [] # short ids
self.cohort_set: set[str] = set()
self.cohort_orcids: dict[str, str] = {} # orcid (bare) -> author short id
self.cohort_names: dict[str, list[str]] = defaultdict(list)
self.seen_authors: set[str] = set()
self.seen_institutions: set[str] = set()
self.stub_institutions: set[str] = set() # created from lineage with only an id
self.seen_topics: set[str] = set()
self.seen_venues: set[str] = set()
self.seen_funders: set[str] = set()
self.work_ids: list[str] = []
self.doi_to_work: dict[str, str] = {} # raw lowercase doi -> work short id
self.cordis_projects: set[str] = set()
self.dfg_projects: set[str] = set()
self.institution_id: str = ""
self.organization_name: str = ""
def bare_orcid(value: str | None) -> str | None:
if not value:
return None
return value.strip().removeprefix("https://orcid.org/").removeprefix("http://orcid.org/")
def load_cohort_from_graph(w: GraphWriter, st: State) -> None:
"""Used when a later phase runs without the cohort phase in the same process."""
rows = w.ro_all("MATCH (a:Cohort) RETURN a.id, a.orcid, a.name ORDER BY a.id")
for aid, orcid, name in rows:
st.cohort_ids.append(aid)
st.cohort_set.add(aid)
if orcid:
st.cohort_orcids[bare_orcid(orcid)] = aid
if name:
st.cohort_names[name].append(aid)
logger.info("Loaded %d cohort members from the graph", len(st.cohort_ids))
def load_works_from_graph(w: GraphWriter, st: State) -> None:
rows = w.ro_all("MATCH (x:Work) RETURN x.id, x.doi ORDER BY x.id")
for wid, doi in rows:
st.work_ids.append(wid)
if doi:
st.doi_to_work[doi.lower()] = wid
logger.info("Loaded %d works (%d with DOI) from the graph", len(st.work_ids), len(st.doi_to_work))
# --------------------------------------------------------------------------- phases
async def phase_cohort(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
inst_id = st.institution_id
institution = await get_institution_by_id(inst_id)
inst_name = getattr(institution, "display_name", None) or st.organization_name
w.node("Organization", st.organization_name, {"name": st.organization_name, "openalex_institution_id": inst_id})
w.node("Institution", inst_id, {"name": inst_name, "ror": getattr(institution, "ror", None),
"country_code": getattr(institution, "country_code", None),
"type": str(institution.type) if getattr(institution, "type", None) else None})
st.seen_institutions.add(inst_id)
w.edge("Organization", st.organization_name, "REPRESENTS", "Institution", inst_id)
query = build_institution_membership_query(inst_id, year_mode="from", year=current_affiliation_year_cutoff())
source = ["id", "display_name", "orcid", "ids.orcid", "works_count", "cited_by_count", "summary_stats",
"affiliations", "last_known_institutions", "topics"]
count = 0
async for hit in elasticsearch.scan(index=ESIndex.OPENALEX_AUTHORS, query=query, source=source, page_size=1000):
if args.limit_authors and count >= args.limit_authors:
break
a = hit["_source"]
aid = short_id(a.get("id"))
if not aid:
continue
count += 1
stats = a.get("summary_stats") or {}
a["orcid"] = a.get("orcid") or (a.get("ids") or {}).get("orcid")
st.cohort_ids.append(aid)
st.cohort_set.add(aid)
st.seen_authors.add(aid)
if a.get("orcid"):
st.cohort_orcids[bare_orcid(a["orcid"])] = aid
if a.get("display_name"):
st.cohort_names[a["display_name"]].append(aid)
w.node("Author", aid, {
"name": a.get("display_name"), "orcid": a.get("orcid"), "works_count": a.get("works_count"),
"cited_by_count": a.get("cited_by_count"), "h_index": stats.get("h_index"), "i10_index": stats.get("i10_index"),
"seed": True,
})
w.edge("Author", aid, "MEMBER_OF", "Organization", st.organization_name)
last_known = {short_id(i.get("id")) for i in (a.get("last_known_institutions") or []) if i.get("id")}
for aff in a.get("affiliations") or []:
inst = aff.get("institution") or {}
iid = short_id(inst.get("id"))
if not iid:
continue
add_institution(w, st, iid, inst)
w.edge("Author", aid, "AFFILIATED_WITH", "Institution", iid,
{"years": sorted(aff.get("years") or []), "last_known": iid in last_known})
for topic in a.get("topics") or []:
tid = short_id(topic.get("id"))
if not tid:
continue
add_topic(w, st, tid, topic)
w.edge("Author", aid, "WORKS_ON", "Topic", tid, {"score": topic.get("score"), "count": topic.get("count")})
if count % 1000 == 0:
logger.info(" cohort: %d researchers", count)
w.flush()
w.run("MATCH (n:Author) WHERE n.seed = true SET n:Cohort")
logger.info("cohort: %d researchers, %d with ORCID", len(st.cohort_ids), len(st.cohort_orcids))
def add_institution(w: GraphWriter, st: State, iid: str, inst: dict[str, Any]) -> None:
if iid in st.seen_institutions and iid not in st.stub_institutions:
return
st.seen_institutions.add(iid)
st.stub_institutions.discard(iid)
w.node("Institution", iid, {"name": inst.get("display_name"), "ror": inst.get("ror"),
"country_code": inst.get("country_code"), "type": inst.get("type")})
for ancestor in inst.get("lineage") or []:
anc = short_id(ancestor)
if anc and anc != iid:
if anc not in st.seen_institutions:
st.seen_institutions.add(anc)
st.stub_institutions.add(anc)
w.node("Institution", anc, {}, mode="create")
w.edge("Institution", iid, "PART_OF", "Institution", anc)
def add_topic(w: GraphWriter, st: State, tid: str, topic: dict[str, Any]) -> None:
if tid in st.seen_topics:
return
st.seen_topics.add(tid)
w.node("Topic", tid, topic_props(topic))
async def phase_works(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
query = {"nested": {"path": "authorships", "query": {"terms": {"authorships.author.id": [OPENALEX_PREFIX + i for i in st.cohort_ids]}}}}
count = 0
authorships_total = 0
started = time.perf_counter()
async for hit in elasticsearch.scan(index=ESIndex.OPENALEX_WORKS_WILDCARD, query=query, source=WORK_SOURCE_FIELDS, page_size=500):
if args.limit_works and count >= args.limit_works:
break
s = hit["_source"]
wid = short_id(s.get("id"))
if not wid:
continue
count += 1
st.work_ids.append(wid)
doi = raw_doi(s["doi"]) if s.get("doi") else None
if doi:
st.doi_to_work[doi.lower()] = wid
authorships = s.get("authorships") or []
authorships_total += len(authorships)
source_loc = ((s.get("primary_location") or {}).get("source")) or {}
w.node("Work", wid, {
"title": s.get("title"), "year": s.get("publication_year"), "type": s.get("type"), "language": s.get("language"),
"cited_by_count": s.get("cited_by_count"), "authors_count": s.get("authors_count") or len(authorships),
"doi": doi, "is_oa": (s.get("open_access") or {}).get("is_oa"), "fwci": s.get("fwci"),
})
for ship in authorships:
author = ship.get("author") or {}
aid = short_id(author.get("id"))
if not aid:
continue
if aid not in st.seen_authors:
st.seen_authors.add(aid)
w.node("Author", aid, {"name": author.get("display_name"), "orcid": author.get("orcid"), "seed": False}, mode="create")
w.edge("Author", aid, "AUTHORED", "Work", wid, {"position": ship.get("author_position"), "corresponding": ship.get("is_corresponding")})
for inst in ship.get("institutions") or []:
iid = short_id(inst.get("id"))
if iid:
add_institution(w, st, iid, inst)
w.edge("Author", aid, "AFFILIATED_WITH", "Institution", iid)
for topic in s.get("topics") or []:
tid = short_id(topic.get("id"))
if tid:
add_topic(w, st, tid, topic)
w.edge("Work", wid, "HAS_TOPIC", "Topic", tid, {"score": topic.get("score")})
vid = short_id(source_loc.get("id"))
if vid:
if vid not in st.seen_venues:
st.seen_venues.add(vid)
w.node("Venue", vid, {"name": source_loc.get("display_name"), "type": source_loc.get("type"),
"issn_l": source_loc.get("issn_l"), "publisher": source_loc.get("host_organization_name")})
w.edge("Work", wid, "PUBLISHED_IN", "Venue", vid)
awards_by_funder: dict[str, list[str]] = defaultdict(list)
for award in s.get("awards") or []:
fid = short_id(award.get("funder_id"))
if fid and award.get("funder_award_id"):
awards_by_funder[fid].append(award["funder_award_id"])
for funder in s.get("funders") or []:
fid = short_id(funder.get("id"))
if not fid:
continue
if fid not in st.seen_funders:
st.seen_funders.add(fid)
w.node("Funder", fid, {"name": funder.get("display_name"), "ror": funder.get("ror")})
w.edge("Work", wid, "FUNDED_BY", "Funder", fid, {"awards": awards_by_funder.get(fid) or None})
if count % 10000 == 0:
logger.info(" works: %d (%d authorships, %d authors, %.0fs)", count, authorships_total, len(st.seen_authors), time.perf_counter() - started)
w.flush()
logger.info("works: %d works, %d authorships, %d distinct authors, %d institutions, %d venues, %d funders, %d DOIs",
count, authorships_total, len(st.seen_authors), len(st.seen_institutions), len(st.seen_venues), len(st.seen_funders), len(st.doi_to_work))
async def phase_institutions(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
"""Institutions known only as lineage ancestors have no name yet; fetch them from the institutions index."""
ids = [r[0] for r in w.ro_all("MATCH (i:Institution) WHERE i.name IS NULL RETURN i.id ORDER BY i.id")]
fixed = 0
for batch in chunks(ids, 500):
resp = await elasticsearch.search(index=ESIndex.OPENALEX_INSTITUTIONS, query={"ids": {"values": batch}}, size=500,
source=["id", "display_name", "ror", "country_code", "type"])
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
fixed += 1
w.node("Institution", short_id(s.get("id")) or hit["_id"], {"name": s.get("display_name"), "ror": s.get("ror"),
"country_code": s.get("country_code"), "type": s.get("type")}, mode="update")
w.flush()
logger.info("institutions: %d of %d nameless institutions enriched from the institutions index", fixed, len(ids))
async def phase_affiliations(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
"""Per-work affiliations, which the author-level AFFILIATED_WITH edges cannot express:
AUTHORED.institution_ids = institutions named on that authorship, and
(Work)-[:INVOLVES {authors}]->(Institution) for every institution on the paper."""
query = {"nested": {"path": "authorships", "query": {"terms": {"authorships.author.id": [OPENALEX_PREFIX + i for i in st.cohort_ids]}}}}
seen: set[str] = set()
ship_rows: list[dict] = []
inv_rows: list[dict] = []
ships = involved = 0
started = time.perf_counter()
def flush() -> None:
nonlocal ships, involved, ship_rows, inv_rows
for chunk in chunks(ship_rows, args.batch_size):
ships += int(w.run("UNWIND $rows AS r MATCH (a:Author {id: r.a})-[e:AUTHORED]->(x:Work {id: r.w}) "
"SET e.institution_ids = r.inst", {"rows": chunk}).properties_set or 0)
for chunk in chunks(inv_rows, args.batch_size):
involved += int(w.run("UNWIND $rows AS r MATCH (x:Work {id: r.w}), (i:Institution {id: r.i}) "
"MERGE (x)-[e:INVOLVES]->(i) SET e.authors = r.n", {"rows": chunk}).relationships_created or 0)
ship_rows, inv_rows = [], []
async for hit in elasticsearch.scan(index=ESIndex.OPENALEX_WORKS_WILDCARD, query=query,
source=["id", "authorships.author.id", "authorships.institutions.id"], page_size=1000):
s = hit["_source"]
wid = short_id(s.get("id"))
if not wid or wid in seen:
continue
seen.add(wid)
per_institution: Counter = Counter()
for ship in s.get("authorships") or []:
aid = short_id((ship.get("author") or {}).get("id"))
inst_ids = [short_id(i.get("id")) for i in (ship.get("institutions") or []) if i.get("id")]
if not aid or not inst_ids:
continue
ship_rows.append({"a": aid, "w": wid, "inst": inst_ids})
per_institution.update(inst_ids)
inv_rows.extend({"w": wid, "i": iid, "n": n} for iid, n in per_institution.items())
if len(ship_rows) >= args.batch_size * 4:
flush()
if len(seen) % 20000 == 0:
logger.info(" affiliations: %d works, %d authorship updates, %d work-institution edges, %.0fs", len(seen), ships, involved, time.perf_counter() - started)
flush()
logger.info("affiliations: %d works, %d AUTHORED edges carry institution_ids, %d INVOLVES edges", len(seen), ships, involved)
async def phase_classifications(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
found = 0
for batch in chunks(st.work_ids, 1000):
page = await search_work_classifications(
query={"terms": {"work_id": [OPENALEX_PREFIX + i for i in batch]}},
source=["work_id", "classification"], page=0, size=1000)
for c in page.elements:
d = c.classification
if not d:
continue
found += 1
w.node("Work", short_id(c.work_id), {
"primary_category": str(d.primary_category) if d.primary_category else None,
"classification_confidence": d.confidence, "pasteur_quadrant": d.pasteur_quadrant,
"applied_orientation_score": d.applied_orientation_score,
}, mode="update")
w.flush()
logger.info("classifications: %d of %d works classified", found, len(st.work_ids))
def _project_node(w: GraphWriter, st: State, source: str, pid: str) -> str:
node_id = f"{source}:{pid}"
registry = st.cordis_projects if source == "cordis" else st.dfg_projects
if pid not in registry:
registry.add(pid)
w.node("Project", node_id, {"source": source, "source_id": pid}, mode="create")
return node_id
async def phase_projects(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
inst_id = st.institution_id
dois = list(st.doi_to_work.keys())
# D1: CORDIS projects via publication DOIs
links = 0
for batch in chunks(dois, 1000):
resp = await get_cordis_eu_publications_by_dois(batch)
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
pid = s.get("projectID")
wid = None
for candidate in (s.get("doi"), s.get("qaProcessedDoi")):
if candidate:
wid = st.doi_to_work.get(raw_doi(candidate).lower())
if wid:
break
if pid and wid:
links += 1
w.edge("Work", wid, "OUTPUT_OF", "Project", _project_node(w, st, "cordis", str(pid)), {"source": "cordis_publications"})
logger.info("projects: %d work->CORDIS project links via DOI (%d projects)", links, len(st.cordis_projects))
# D2: DFG projects via publication DOIs (project docs list their publications)
links = 0
url_dois = list({f"https://doi.org/{d}" for d in dois} | set(dois))
for batch in chunks(url_dois, 1000):
resp = await get_dfg_publications_by_dois(batch)
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
pid = s.get("id")
if not pid:
continue
for pub in s.get("publications") or []:
wid = st.doi_to_work.get(raw_doi(pub.get("doi") or "").lower())
if wid:
links += 1
w.edge("Work", wid, "OUTPUT_OF", "Project", _project_node(w, st, "dfg", str(pid)), {"source": "dfg_publications"})
logger.info("projects: %d work->DFG project links via DOI (%d projects)", links, len(st.dfg_projects))
w.flush()
# D3: institution-level participations
org_ids = await InstitutionsSearchClient().get_cordis_eu_organisation_ids_by_oa_institution_id(inst_id) or []
n = 0
if org_ids:
async for hit in elasticsearch.scan(index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, query={"terms": {"organisationID": org_ids}},
source=["projectID", "role", "ecContribution", "endOfParticipation"], page_size=1000, cluster="inse"):
s = hit["_source"]
if s.get("projectID"):
n += 1
w.edge("Institution", inst_id, "PARTICIPATES_IN", "Project", _project_node(w, st, "cordis", str(s["projectID"])),
{"role": s.get("role"), "ec_contribution": s.get("ecContribution"), "source": "cordis_organizations"})
dfg_inst_ids = await _dfg_institution_ids_for_organization(organization_name=st.organization_name)
m = 0
if dfg_inst_ids:
async for hit in elasticsearch.scan(index=ESIndex.DFG_PROJECTS, query={"nested": {"path": "institutions", "query": {"terms": {"institutions.institute_id": dfg_inst_ids}}}},
source=["id"], page_size=1000, cluster="inse"):
pid = hit["_source"].get("id")
if pid:
m += 1
w.edge("Institution", inst_id, "PARTICIPATES_IN", "Project", _project_node(w, st, "dfg", str(pid)), {"source": "dfg_institutions"})
logger.info("projects: institution-level participations: %d CORDIS (org ids %s), %d DFG (%d DFG institute ids)", n, org_ids, m, len(dfg_inst_ids))
w.flush()
# D4: DFG persons matched by ORCID -> roles in DFG projects
orcids = list(st.cohort_orcids.keys())
matched = roles = 0
for batch in chunks(orcids, 500):
# orcid_id is an analysed text field in dfg_persons; exact matching needs the keyword sub-field
resp = await elasticsearch.search(index=ESIndex.DFG_PERSONS, query={"terms": {"orcid_id.keyword": batch}}, size=1000, cluster=ESCluster.INSE,
source=["person_id", "orcid_id", "full_name", "projects"])
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
aid = st.cohort_orcids.get(bare_orcid(s.get("orcid_id")))
if not aid:
continue
matched += 1
w.node("Author", aid, {"dfg_person_id": s.get("person_id")}, mode="update")
for p in s.get("projects") or []:
pid = p.get("project_id")
if not pid:
continue
roles += 1
node_id = _project_node(w, st, "dfg", str(pid))
w.node("Project", node_id, {"title": p.get("title_en") or p.get("title_de"), "start": p.get("funding_start"),
"end": p.get("funding_end"), "funding_scheme": p.get("funding_type_en") or p.get("funding_type_de")})
w.edge("Author", aid, "DFG_ROLE", "Project", node_id, {"role": p.get("role_label_en") or p.get("role_label_de"), "role_key": p.get("role_key"), "source": "dfg_persons_orcid"})
logger.info("projects: %d cohort researchers matched to DFG persons by ORCID, %d project roles", matched, roles)
w.flush()
# D5: project details + EU consortium partners
for batch in chunks(sorted(st.cordis_projects), 500):
resp = await elasticsearch.search(index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, query={"terms": {"id": batch}}, size=1000, cluster=ESCluster.INSE,
source=["id", "acronym", "title", "startDate", "endDate", "ecMaxContribution", "totalCost", "fundingScheme", "frameworkProgramme", "status"])
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
w.node("Project", f"cordis:{s['id']}", {"title": s.get("title"), "acronym": s.get("acronym"), "start": s.get("startDate"), "end": s.get("endDate"),
"ec_max_contribution": s.get("ecMaxContribution"), "total_cost": s.get("totalCost"),
"funding_scheme": s.get("fundingScheme"), "programme": s.get("frameworkProgramme"), "status": s.get("status")}, mode="update")
resp = await elasticsearch.search(index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, query={"terms": {"projectID": batch}}, size=10000, cluster=ESCluster.INSE,
source=["projectID", "organisationID", "name", "shortName", "country", "role", "activityType", "ecContribution"])
partners = set()
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
oid = s.get("organisationID")
if not oid or not s.get("projectID"):
continue
if oid not in partners:
partners.add(oid)
w.node("EuOrganization", str(oid), {"name": s.get("name"), "short_name": s.get("shortName"), "country": s.get("country"), "activity_type": s.get("activityType")})
w.edge("EuOrganization", str(oid), "PARTICIPATES_IN", "Project", f"cordis:{s['projectID']}", {"role": s.get("role"), "ec_contribution": s.get("ecContribution")})
w.flush()
for batch in chunks(sorted(st.dfg_projects), 500):
resp = await elasticsearch.search(index=ESIndex.DFG_PROJECTS, query={"ids": {"values": batch}}, size=1000, cluster=ESCluster.INSE,
source=["id", "title_en", "title_de", "funding_start", "funding_end", "funding_type_en", "funding_type_de", "page_url", "subject_area_en", "dfg_procedure"])
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
w.node("Project", f"dfg:{s.get('id') or hit['_id']}", {"title": s.get("title_en") or s.get("title_de"), "start": s.get("funding_start"), "end": s.get("funding_end"),
"funding_scheme": s.get("funding_type_en") or s.get("funding_type_de"), "url": s.get("page_url"),
"subject_area": s.get("subject_area_en"), "procedure": s.get("dfg_procedure")}, mode="update")
w.flush()
logger.info("projects: details for %d CORDIS and %d DFG projects", len(st.cordis_projects), len(st.dfg_projects))
async def phase_patents(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
client = OrgPatentsSearchClient()
page, size, total, n_edges = 0, 100, None, 0
while True:
entries, total = await client.search_by_institution(st.institution_id, page=page, size=size)
if not entries:
break
for p in entries:
pid = f"{p.source}:{p.patent_id}"
year = int(p.publication_year) if p.publication_year and str(p.publication_year).isdigit() else None
w.node("Patent", pid, {"patent_id": p.patent_id, "source": p.source, "title": p.title or p.title_en or p.title_de, "year": year,
"publication_date": p.publication_date, "kind": p.kind, "status": p.status, "country": p.country,
"ipc": p.ipc, "assignees": p.assignees, "inventors": p.inventors, "match_type": str(p.match_type)})
for m in p.matched_authors:
aid = short_id(m.openalex_author_id)
if not aid:
continue
if aid not in st.seen_authors:
st.seen_authors.add(aid)
w.node("Author", aid, {"name": m.author_name, "seed": False}, mode="create")
n_edges += 1
w.edge("Author", aid, "INVENTOR_OF", "Patent", pid, {"match_type": str(p.match_type), "source": "org_patents"})
for tag in p.openalex_topics:
tid = short_id(tag.topic_id)
if tid:
if tid not in st.seen_topics:
st.seen_topics.add(tid)
w.node("Topic", tid, {"name": tag.topic_display_name, "field": tag.field_name, "domain": tag.domain_name})
w.edge("Patent", pid, "HAS_TOPIC", "Topic", tid)
page += 1
if page * size >= (total or 0):
break
w.flush()
logger.info("patents: %s patents in org_patents, %d inventor edges", total, n_edges)
async def phase_news(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
name_to_news: dict[str, set[str]] = defaultdict(set)
scanned = 0
async for hit in elasticsearch.scan(index="aktuell_postproc", query={"exists": {"field": "authors"}}, source=["news_id", "authors"], page_size=1000, cluster="inse"):
s = hit["_source"]
scanned += 1
for name in s.get("authors") or []:
if isinstance(name, str) and name in st.cohort_names and s.get("news_id"):
name_to_news[name].add(s["news_id"])
news_ids = sorted({nid for ids in name_to_news.values() for nid in ids})
for batch in chunks(news_ids, 500):
resp = await elasticsearch.search(index="aktuell", query={"ids": {"values": batch}}, size=500, cluster="inse", source=["date", "maintitle", "url", "author"])
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
w.node("NewsArticle", hit["_id"], {"title": s.get("maintitle"), "date": s.get("date"), "url": s.get("url"), "author": s.get("author")})
resp = await elasticsearch.search(index="aktuell_openalex_topics", query={"terms": {"news_id.keyword": batch}}, size=10000, cluster="inse",
source=["news_id", "keyword", "topic_matches"])
for hit in resp.get("hits", {}).get("hits", []):
s = hit["_source"]
best = next((m for m in (s.get("topic_matches") or []) if m.get("rank") == 1), None)
tid = short_id((best or {}).get("topic_id"))
if tid and s.get("news_id"):
if tid not in st.seen_topics:
st.seen_topics.add(tid)
w.node("Topic", tid, {"name": best.get("topic_display_name"), "subfield": best.get("subfield"), "field": best.get("field"), "domain": best.get("domain")})
w.edge("NewsArticle", s["news_id"], "HAS_TOPIC", "Topic", tid, {"keyword": s.get("keyword")})
w.flush()
edges = 0
for name, ids in name_to_news.items():
for aid in st.cohort_names[name]:
for nid in ids:
edges += 1
w.edge("Author", aid, "MENTIONED_IN", "NewsArticle", nid, {"matching": "display_name", "ambiguous": len(st.cohort_names[name]) > 1})
w.flush()
logger.info("news: scanned %d post-processed articles, %d matched articles, %d mention edges for %d names", scanned, len(news_ids), edges, len(name_to_news))
async def phase_companies(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
sem = asyncio.Semaphore(args.concurrency)
results: list[tuple[str, Any]] = []
async def one(aid: str):
async with sem:
try:
return aid, await get_company_connections_by_author_id(aid)
except Exception as exc: # keep going, one researcher must not stop the phase
return aid, exc
done = 0
with_links = ambiguous = companies = 0
for batch in chunks(st.cohort_ids, 200):
for aid, resp in await asyncio.gather(*(one(a) for a in batch)):
done += 1
if isinstance(resp, Exception) or resp.company_count == 0:
continue
with_links += 1
if resp.common_name_warning and not args.include_ambiguous_companies:
ambiguous += 1
w.node("Author", aid, {"hr_company_matches": resp.company_count, "hr_common_name_warning": True}, mode="update")
continue
w.node("Author", aid, {"hr_company_matches": resp.company_count, "hr_common_name_warning": resp.common_name_warning}, mode="update")
for c in resp.connections:
cid = c.company_number or c.native_company_number or f"name:{c.company_name}"
companies += 1
w.node("Company", cid, {"name": c.company_name, "status": c.company_status, "registered_office": c.registered_office,
"register": " ".join(p for p in (c.register_art, c.register_nummer) if p) or None})
w.edge("Author", aid, "OFFICER_OF", "Company", cid, {"positions": [o.position for o in c.matched_officers if o.position],
"matching_method": resp.matching_method, "common_name_warning": resp.common_name_warning})
w.flush()
if done % 1000 < 200:
logger.info(" companies: %d/%d researchers checked", done, len(st.cohort_ids))
logger.info("companies: %d researchers with matches, %d skipped as common-name matches, %d company links written", with_links, ambiguous, companies)
async def phase_hierarchy(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
tree = await get_topic_hierarchy()
n = 0
for d in tree.domains:
did = short_id(d.id) or f"domain:{d.name}"
w.node("Domain", did, {"name": d.name})
for f in d.fields:
fid = short_id(f.id) or f"field:{f.name}"
w.node("Field", fid, {"name": f.name})
w.edge("Field", fid, "IN_DOMAIN", "Domain", did)
for sf in f.subfields:
sid = short_id(sf.id) or f"subfield:{sf.name}"
w.node("Subfield", sid, {"name": sf.name})
w.edge("Subfield", sid, "IN_FIELD", "Field", fid)
for t in sf.topics:
tid = short_id(t.id)
if not tid:
continue
n += 1
if tid not in st.seen_topics:
st.seen_topics.add(tid)
w.node("Topic", tid, {"name": t.display_name, "subfield": sf.name, "field": f.name, "domain": d.name})
w.edge("Topic", tid, "IN_SUBFIELD", "Subfield", sid)
w.flush()
logger.info("hierarchy: %d topics linked into %d domains", n, len(tree.domains))
async def phase_derive(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
cap = args.pair_cap
# Derived edges are rebuilt from scratch so the phase can be re-run safely.
for rel, pattern in (("CO_AUTHOR", "()-[c:CO_AUTHOR]->()"), ("FUNDED_BY", "(:Cohort)-[c:FUNDED_BY]->(:Funder)"), ("CONTRIBUTED_TO", "(:Cohort)-[c:CONTRIBUTED_TO]->(:Project)")):
r = w.run(f"MATCH {pattern} DELETE c")
if r.relationships_deleted:
logger.info("derive: removed %d existing %s edges", int(r.relationships_deleted), rel)
works = w.ro_all("MATCH (x:Work) RETURN x.id, x.year, x.authors_count ORDER BY x.id")
small = [wid for wid, _, n in works if (n or 0) <= cap]
big = [wid for wid, _, n in works if (n or 0) > cap]
logger.info("derive: CO_AUTHOR over %d works (all pairs) + %d works (cohort-anchored pairs)", len(small), len(big))
# Pairs are computed in Python from per-work author lists and aggregated in a temporary
# SQLite table (10M+ rows), then created with plain CREATE: FalkorDB's own
# MATCH ... MERGE ON MATCH over millions of pairs was measured at minutes per batch.
tmp = tempfile.NamedTemporaryFile(prefix="coauthor_", suffix=".sqlite", delete=False)
tmp.close()
con = sqlite3.connect(tmp.name)
con.execute("PRAGMA journal_mode=OFF"); con.execute("PRAGMA synchronous=OFF")
con.execute("CREATE TABLE pairs (a TEXT NOT NULL, b TEXT NOT NULL, y INTEGER)")
started = time.perf_counter()
instances = 0
def author_lists(work_ids: list[str]) -> list[tuple[str, int | None, list[str], list[bool]]]:
res = w.ro("UNWIND $ids AS wid MATCH (x:Work {id: wid})<-[:AUTHORED]-(a:Author) "
"RETURN x.id, x.year, collect(a.id), collect(a.seed = true)", {"ids": work_ids}).result_set
return [(r[0], r[1], r[2], r[3]) for r in res]
for i, batch in enumerate(chunks(small, 1000)):
rows: list[tuple[str, str, int | None]] = []
for _, year, authors, _seeds in author_lists(batch):
authors = sorted(set(authors))
for ai in range(len(authors)):
for bi in range(ai + 1, len(authors)):
rows.append((authors[ai], authors[bi], year))
con.executemany("INSERT INTO pairs VALUES (?, ?, ?)", rows)
instances += len(rows)
if i % 25 == 0:
logger.info(" co-author pairs (small works): batch %d/%d, %d pair instances, %.0fs", i, len(small) // 1000, instances, time.perf_counter() - started)
for i, batch in enumerate(chunks(big, 20)):
rows = []
for _, year, authors, seeds in author_lists(batch):
cohort_here = {a for a, is_seed in zip(authors, seeds) if is_seed}
others = set(authors)
pairs = {(min(c, o), max(c, o)) for c in cohort_here for o in others if o != c}
rows.extend((a, b, year) for a, b in pairs)
con.executemany("INSERT INTO pairs VALUES (?, ?, ?)", rows)
instances += len(rows)
if i % 100 == 0:
logger.info(" co-author pairs (large works): batch %d/%d, %d pair instances, %.0fs", i, len(big) // 20, instances, time.perf_counter() - started)
con.commit()
logger.info("derive: %d pair instances collected in %.0fs, aggregating ...", instances, time.perf_counter() - started)
create = ("UNWIND $rows AS r MATCH (x:Author {id: r.a}), (y:Author {id: r.b}) "
"CREATE (x)-[c:CO_AUTHOR {weight: r.n, first_year: r.fy, last_year: r.ly}]->(y)")
created = 0
buffer: list[dict] = []
for a, b, n, fy, ly in con.execute("SELECT a, b, COUNT(*), MIN(y), MAX(y) FROM pairs GROUP BY a, b"):
buffer.append({"a": a, "b": b, "n": n, "fy": fy, "ly": ly})
if len(buffer) >= 5000:
created += int(w.run(create, {"rows": buffer}).relationships_created or 0)
buffer = []
if created % 500000 < 5000:
logger.info(" co-author edges: %d created, %.0fs", created, time.perf_counter() - started)
if buffer:
created += int(w.run(create, {"rows": buffer}).relationships_created or 0)
con.close()
os.unlink(tmp.name)
logger.info("derive: %d CO_AUTHOR edges in %.0fs", created, time.perf_counter() - started)
ids = st.cohort_ids or [r[0] for r in w.ro_all("MATCH (a:Cohort) RETURN a.id ORDER BY a.id")]
funded = contributed = 0
for batch in chunks(ids, 20):
rows = w.ro("UNWIND $ids AS aid MATCH (a:Cohort {id: aid})-[:AUTHORED]->(x:Work)-[:FUNDED_BY]->(f:Funder) "
"RETURN a.id, f.id, count(DISTINCT x)", {"ids": batch}).result_set
if rows:
funded += int(w.run("UNWIND $rows AS r MATCH (a:Cohort {id: r.a}), (f:Funder {id: r.f}) "
"CREATE (a)-[:FUNDED_BY {publications: r.n}]->(f)",
{"rows": [{"a": a, "f": f, "n": n} for a, f, n in rows]}).relationships_created or 0)
rows = w.ro("UNWIND $ids AS aid MATCH (a:Cohort {id: aid})-[:AUTHORED]->(x:Work)-[:OUTPUT_OF]->(p:Project) "
"RETURN a.id, p.id, count(DISTINCT x)", {"ids": batch}).result_set
if rows:
contributed += int(w.run("UNWIND $rows AS r MATCH (a:Cohort {id: r.a}), (p:Project {id: r.p}) "
"CREATE (a)-[:CONTRIBUTED_TO {via: 'publication_doi', works: r.n}]->(p)",
{"rows": [{"a": a, "p": p, "n": n} for a, p, n in rows]}).relationships_created or 0)
logger.info("derive: %d Author-FUNDED_BY and %d Author-CONTRIBUTED_TO edges for the cohort", funded, contributed)
async def phase_profile(w: GraphWriter, st: State, args: argparse.Namespace) -> None:
"""Research profile of the institution as drawable edges:
(Institution)-[:ACTIVE_IN {works, researchers}]->(Topic | Subfield | Field | Domain),
counted over the works of the cohort. Rebuilt from scratch on every run."""
inst = st.institution_id
r = w.run("MATCH (:Institution {id: $i})-[r:ACTIVE_IN]->() DELETE r", {"i": inst})
if r.relationships_deleted:
logger.info("profile: removed %d existing ACTIVE_IN edges", int(r.relationships_deleted))
base = ("MATCH (:Institution {id: $i})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(a:Cohort)-[:AUTHORED]->(x:Work)"
"-[:HAS_TOPIC]->(t:Topic)")
levels = {
"Topic": base + " RETURN t.id AS id, count(DISTINCT x) AS works, count(DISTINCT a) AS researchers",
"Subfield": base + "-[:IN_SUBFIELD]->(n:Subfield) RETURN n.id AS id, count(DISTINCT x), count(DISTINCT a)",
"Field": base + "-[:IN_SUBFIELD]->()-[:IN_FIELD]->(n:Field) RETURN n.id AS id, count(DISTINCT x), count(DISTINCT a)",
"Domain": base + "-[:IN_SUBFIELD]->()-[:IN_FIELD]->()-[:IN_DOMAIN]->(n:Domain) RETURN n.id AS id, count(DISTINCT x), count(DISTINCT a)",
}
total = 0
for label, query in levels.items():
rows = w.ro(query, {"i": inst}).result_set
if len(rows) >= 10000:
logger.warning("profile: %s aggregation hit the result-set cap, counts incomplete", label)
created = 0
for chunk in chunks([{"id": rid, "works": works, "researchers": res} for rid, works, res in rows], 2000):
created += int(w.run(f"UNWIND $rows AS r MATCH (i:Institution {{id: $i}}), (n:{label} {{id: r.id}}) "
f"CREATE (i)-[:ACTIVE_IN {{level: '{label.lower()}', works: r.works, researchers: r.researchers}}]->(n)",
{"rows": chunk, "i": inst}).relationships_created or 0)
total += created
logger.info("profile: %d ACTIVE_IN edges to %s", created, label)
logger.info("profile: %d ACTIVE_IN edges for %s", total, inst)
PHASE_FUNCS = {
"cohort": phase_cohort, "works": phase_works, "institutions": phase_institutions, "affiliations": phase_affiliations,
"classifications": phase_classifications, "projects": phase_projects,
"patents": phase_patents, "news": phase_news, "companies": phase_companies, "hierarchy": phase_hierarchy, "derive": phase_derive,
"profile": phase_profile,
}
# --------------------------------------------------------------------------- main
def organization_name_for(institution_id: str) -> str:
try:
data = json.loads(PREDEFINED_ACCOUNTS.read_text(encoding="utf-8"))
for org in data.get("organizations", []):
if org.get("openalex_institution_id") == institution_id:
return org["name"]
except OSError:
pass
return institution_id
async def main(args: argparse.Namespace) -> None:
phases = [p for p in PHASES if p in set(args.phases or PHASES)]
st = State()
st.institution_id = short_id(args.institution)
st.organization_name = organization_name_for(st.institution_id)
w = GraphWriter(args.falkordb_host, args.falkordb_port, args.falkordb_password, args.graph, args.reset, args.batch_size)
w.ensure_indexes(["Organization", "Institution", "Author", "Work", "Topic", "Venue", "Funder", "Project", "EuOrganization",
"Patent", "NewsArticle", "Company", "Domain", "Field", "Subfield"],
extra=[("Author", "seed"), ("Work", "year"), ("Work", "authors_count"), ("Cohort", "id")])
logger.info("Graph %r on %s:%s, institution %s (%s), phases: %s", args.graph, args.falkordb_host, args.falkordb_port,
st.institution_id, st.organization_name, ", ".join(phases))
if "cohort" not in phases:
load_cohort_from_graph(w, st)
if "works" not in phases and any(p in phases for p in ("classifications", "projects")):
load_works_from_graph(w, st)
total_started = time.perf_counter()
for phase in phases:
started = time.perf_counter()
logger.info("=== phase %s ===", phase)
try:
await PHASE_FUNCS[phase](w, st, args)
except Exception:
logger.exception("phase %s failed; continuing with the next phase", phase)
w.flush()
logger.info("=== phase %s done in %.0fs (FalkorDB time so far %.0fs) ===", phase, time.perf_counter() - started, w.query_time)
nodes, rels = w.label_counts()
logger.info("Total %.0fs. Graph %r: nodes %s", time.perf_counter() - total_started, args.graph, {l: c for l, c in nodes})
logger.info("Relationships: %s", {t: c for t, c in rels})
try:
w.db.connection.execute_command("BGSAVE")
logger.info("BGSAVE requested, the RDB snapshot will be written in the background")
except Exception as exc:
logger.warning("BGSAVE failed: %s", exc)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--institution", default="I62318514", help="OpenAlex institution id of the organization (default UDE)")
parser.add_argument("--phases", nargs="+", choices=PHASES, help="run only these phases (default all, in order)")
parser.add_argument("--limit-authors", type=int, default=0, help="only the first N cohort researchers (smoke test)")
parser.add_argument("--limit-works", type=int, default=0, help="stop the works scan after N works (smoke test)")
parser.add_argument("--pair-cap", type=int, default=30, help="all co-author pairs for works with at most this many authors; larger works only cohort-anchored pairs")
parser.add_argument("--concurrency", type=int, default=8, help="parallel requests for per-researcher sources")
parser.add_argument("--include-ambiguous-companies", action="store_true", help="also write Handelsregister links flagged as common-name matches")
parser.add_argument("--falkordb-host", default=os.environ.get("FALKORDB_HOST", "localhost"))
parser.add_argument("--falkordb-port", type=int, default=int(os.environ.get("FALKORDB_PORT", "6379")))
parser.add_argument("--falkordb-password", default=os.environ.get("FALKORDB_PASSWORD") or None)
parser.add_argument("--graph", default=os.environ.get("FALKORDB_GRAPH", "ude"))
parser.add_argument("--reset", action="store_true", help="delete the graph before loading")
parser.add_argument("--batch-size", type=int, default=2000)
parser.add_argument("-v", "--verbose", action="store_true")
return parser.parse_args()
if __name__ == "__main__":
cli_args = parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S")
if not cli_args.verbose:
for handler in logging.getLogger().handlers:
handler.addFilter(lambda record: record.levelno >= logging.WARNING or record.name.startswith("falkordb"))
asyncio.run(main(cli_args))