diff --git a/docs/thesis/README.md b/docs/thesis/README.md new file mode 100644 index 00000000..8531988e --- /dev/null +++ b/docs/thesis/README.md @@ -0,0 +1,116 @@ +# Master's thesis on the INSE knowledge graph: three research plans + +Status: proposal, 2026-09-17. Supersedes the engineering-oriented outline +(`~/.claude/plans/consider-the-context-of-robust-hopcroft.md`) as the basis for choosing a topic. + +Three alternative six-month theses, one per research community. Pick one; they share data and +infrastructure but differ in research question, method and evaluation. + +| | Plan | Community | One-line question | +|---|---|---|---| +| A | [Certain, possible, wrong](plan-a-knowledge-graphs.md) | Knowledge graphs / Semantic Web | What does identity-link error do to answers over a multi-source graph, and can answers carry that uncertainty? | +| B | [Learning when not to answer](plan-b-nlp.md) | NLP | Can reinforcement fine-tuning make a small model reliable at text-to-Cypher, including abstaining and qualifying, in German and English? | +| C | [Does the graph find the right people?](plan-c-information-retrieval.md) | Information retrieval | Does graph evidence improve expert and industry-partner retrieval when evaluated without temporal leakage? | + +## Why the original outline is no longer a research topic + +The original outline had five parts: build the graph, fix identities, write a benchmark, compare +retrieval setups, fine-tune text-to-Cypher. Two things changed. + +**The engineering is done.** `service/scripts/falkordb/bulk_load.py` builds the whole-university graph +in about 20 minutes: 6,176 active UDE researchers, 204,110 works, 693,487 authors, 26,246 institutions, +3,664 projects, 366 patents, 4,402 news articles, 547 companies and 10 million relationships, in 1.3 GB +of FalkorDB memory. A local LLM (LM Studio, qwen3-8b) already queries it through the FalkorDB MCP +server, and `service/scripts/falkordb/QUERIES.md` holds a tested query cookbook. + +**The obvious research questions are published.** Literature check, September 2026 (from search +results and abstracts; the student must read and verify each before citing): + +| Idea in the original outline | Already covered by | +|---|---| +| Fine-tune a small model for text-to-Cypher, also with RL and execution feedback | Text2Cypher (Ozsoy et al., GenAIK 2025); "Refining Text2Cypher on Small Language Model with Reinforcement Learning" (Applied Sciences 15(15):8206, 2025, GRPO); Multi-Agent GraphRAG text-to-Cypher (arXiv 2511.08274) | +| Generate training and test questions from the graph itself | CypherBench (ACL 2025); PIPE-Cypher (arXiv 2606.08481); KG2Cypher (arXiv 2606.27742); grounded KG data generation (arXiv 2606.14325) | +| Non-English text-to-Cypher | Text2Cypher Across Languages (arXiv 2506.21445; Spanish, Turkish); adapter combination (arXiv 2601.16097). German is still missing, but adding a language alone is incremental | +| Does the graph beat vector search, and on which question types | "When to use Graphs in RAG" / GraphRAG-Bench (ICLR 2026, arXiv 2506.05690); "RAG vs. GraphRAG" (arXiv 2502.11371); "Do We Still Need GraphRAG?" (arXiv 2604.09666); GraphRAG-Router (arXiv 2604.16401) | +| Agentic, multi-step graph retrieval trained with RL | Graph-R1 (arXiv 2507.21892); KG-R1 (arXiv 2509.26383) | +| Robustness of KG-augmented LLMs to a noisy graph | OKGQA-P (ACL 2025, arXiv 2410.08085); KG-RAG under incompleteness (2025); "Less is More: Denoising KGs for RAG" (arXiv 2510.14271). All use random perturbations or LLM-extracted graphs | + +## What is still open, and why this project is well placed + +Building and querying the `ude` graph produced five observations that the literature does not +address and that the project's data can test: + +1. **The links between sources are inferred, with structured error.** Patents carry no person IDs, so + `INVENTOR_OF` rests on name matching (`match_type` institution / name / both). Company officers and + news mentions are exact name matches (`common_name_warning`, `ambiguous`). One researcher named + Thomas Kaiser matches 92 companies. OpenAlex itself over-merges profiles: a cohort profile + "Róbert Langer" carries the MIT chemist's 251 industry partners. Prior robustness work perturbs + graphs at random; nobody measures what realistic identity error does to answers. +2. **Link semantics change numbers by a factor of six.** Industry co-publications of one researcher: + 61 with author-level affiliations, 10 when the affiliation must hold on the paper itself. Counting + and ranking answers are fragile in a way lookups are not. +3. **Observed and inferred edges sit side by side** (`DFG_ROLE` via ORCID is verified, `OFFICER_OF` is a + name match), and every inferred edge records its method. That is the raw material for confidence- + and provenance-aware answering, which exists in database theory (certain and possible answers, + identity-linkage uncertainty) but not in LLM-based graph question answering. +4. **A small local model fails silently.** Without the schema, qwen3-8b invented a property + (`a.institution`), got nulls, and told the user the information "is not available". Separately, the + server's 10,000-row result cap truncated a 206k-row read without any error. Neither failure is + visible to the user. Reliability (answer, qualify, or abstain) is unexplored for text-to-Cypher; + TrustSQL (arXiv 2403.15879) and GrailQAbility (ACL 2023) cover SQL and Freebase only, and + abstention-aware RL (TruthRL, arXiv 2509.25760) covers open-domain QA only. +5. **The graph has time.** Works, patents, projects and per-paper affiliations are dated up to 2026, so + "who will start working with industry" can be evaluated on events that happened after a language + model's knowledge cutoff, which is the only leakage-free way to evaluate LLM-based recommendation. + +## Assets every plan can use + +- The `ude` graph, loader (`bulk_load.py`, twelve idempotent phases), and query cookbook. +- Edge-level evidence: `INVENTOR_OF.match_type`, `OFFICER_OF.common_name_warning`, + `Author.hr_company_matches`, `MENTIONED_IN.ambiguous`, `DFG_ROLE.source`, `AUTHORED.institution_ids`, + `Work.primary_category` (LLM classification of 187k works). +- Existing evaluations to build on: `service/scripts/patents/data/author_patent_evaluation/` (three + experiments on author-patent matching), `llm_evaluations/news_ident_person/` (50 labelled news + articles), `analysis/career_stage/` (60 labelled researchers, 4.6% suspicious profiles), + `service/scripts/profiling/founding_potential/`, `llm_evaluations/sentence_transformer/`. +- LLM access through `inse.integrations.llm` (any OpenAI-compatible endpoint), a terminal harness that + drives an LLM through the FalkorDB MCP tools, and the e5 embedding model in the service image. + +## Fixed conditions (decided 2026-09-17) + +| | | +|---|---| +| Duration | 26 weeks | +| Annotation | Two annotators, about 40 hours each | +| Data release | Open sources only: OpenAlex (CC0), CORDIS, patent offices; DFG GEPRIS licence to be checked. Handelsregister and news-person links stay internal; results on them are reported in aggregate | +| Compute | One 80 GB GPU: QLoRA supervised fine-tuning and GRPO on 7 to 8B models are feasible | +| Tools | FalkorDB, Unsloth (as in the original outline) | +| Data protection | One agreed paragraph with the chair before week 3; a section in the thesis | + +## How to choose + +| | A: knowledge graphs | B: NLP | C: information retrieval | +|---|---|---|---| +| Core novelty | Realistic identity error, certain/possible answers, LLM pipelines that use link confidence | Reliability-aware RL for text-to-Cypher, infeasible and uncertain questions, German | Leakage-free evaluation of graph-augmented expert and partner retrieval, graph-supervised reranker | +| Main risk | Gold set quality; possible-worlds cost on aggregates | A close paper appears first; RL instability | Too few post-cutoff events; pooling depth | +| Fine-tuning share | Small (one supervised model) | Central (SFT and GRPO, several models) | Medium (reranker) | +| Annotation use | 500 to 600 identity links, answer-quality ratings | 400 question validations, German naturalness, error taxonomy | 1,500 to 2,000 relevance judgments | +| Value to INSE after the thesis | Confidence on every cross-source link, fixes the biggest data-quality problem | A local model that can be trusted in the UI | A measured answer to "should scouting use the graph" and a reusable test collection | +| Student profile | Data management, statistics, some ML | Deep learning, RL, NLP evaluation | IR evaluation, ranking, some graph ML | +| Venues | ISWC, ESWC, CIKM, K-CAP; Semantic Web Journal, TGDK | ACL / EMNLP / NAACL Findings; TrustNLP, UncertaiNLP, KnowledgeNLP, GenAIK; LREC-COLING for the dataset | SIGIR (short, resource), ECIR, CIKM, ICTIR; JCDL | + +Recommendation: Plan A is the most defensible against being scooped, because it depends on data only +this project has (measured cross-source identity error), and it turns the most valuable part of the +original outline (Part 2) into the research question. Plan B is the best fit if the student wants a +model-centric thesis and the 80 GB GPU should be used fully. Plan C has the most direct product value. + +Combining is possible but should be resisted: each plan fills 26 weeks. The one sensible overlap is +that Plan B may borrow Plan A's "uncertain evidence" question category, and Plan C may report +Plan A's robustness-to-identity-error as one ablation. + +## Common first four weeks + +1. Run INSE locally, obtain Elasticsearch read access, rebuild `ude` with `run.sh bulk --graph ude --reset`. +2. Read `service/scripts/falkordb/README.md`, `QUERIES.md`, the profiling READMEs. +3. Literature chapter skeleton from the reading list in the chosen plan; verify every citation. +4. Data-protection paragraph agreed; annotation guidelines drafted; annotators booked. diff --git a/docs/thesis/plan-a-knowledge-graphs.md b/docs/thesis/plan-a-knowledge-graphs.md new file mode 100644 index 00000000..582fbe1f --- /dev/null +++ b/docs/thesis/plan-a-knowledge-graphs.md @@ -0,0 +1,127 @@ +# Plan A (knowledge graphs): Certain, possible, wrong + +**Working title:** Certain, possible, wrong: question answering over a multi-source scholarly knowledge +graph with uncertain identity links + +**Target venues:** ISWC or ESWC (research or resources track), CIKM, K-CAP. Journal extension: Semantic +Web Journal or TGDK. + +## The problem in one paragraph + +The INSE graph joins researchers to patents, companies, news and projects. Only some of those joins +are observed (authorship, ORCID-verified DFG roles, DOI-linked project output). The rest are inferred +from names, and OpenAlex's own author identities are partly over-merged. Every question that crosses +a source boundary therefore rests on links that may be wrong, and counting or ranking questions can +flip on a single false merge. Current work on LLMs and knowledge graphs either assumes a clean graph +or perturbs it at random. This thesis measures real identity error, models how it propagates into +answers, and tests whether answers can carry that uncertainty instead of hiding it. + +## Gap and closest related work + +- Robustness of KG-augmented LLMs is studied with random node and edge perturbations (OKGQA-P, ACL 2025, + arXiv 2410.08085; KG-RAG under incompleteness, 2025) and denoising targets LLM-extracted graphs + ("Less is More", arXiv 2510.14271). Identity error is neither random nor local: it is concentrated on + common names and on hubs, and it changes aggregates. +- Database theory defines query answering under identity uncertainty (Moustafa et al., "Subgraph + pattern matching over uncertain graphs with identity linkage uncertainty", arXiv 1305.7006; + uncertainty-annotated databases, arXiv 1904.00234; combining entity resolution and query answering, + arXiv 2303.07469; provenance of result probabilities in uncertain KGs, arXiv 2108.07758). None of it + is connected to LLM-based question answering, and none is evaluated on a real multi-source graph of + this kind. +- Entity-resolution evaluation has matured (entity-centric evaluation for inventor disambiguation, + arXiv 2404.05622; OpenAlex author accuracy with an LLM-assisted benchmark, arXiv 2502.11610; LLMs for + entity matching, arXiv 2310.11244 and 2409.08185), but stops at precision and recall of the links. + What a link error costs downstream is not measured. +- A 2026 preprint names a "provenance gap" in incomplete KGQA (arXiv 2606.15833); the student should + read it first and position against it. + +## Research questions + +- **RQ1. How wrong are the links?** Precision, recall and calibration of four link types: author to + inventor, author to company officer, author to news mention, and OpenAlex over-merged author + profiles. Which evidence (name rarity, topic overlap between IPC classes and OpenAlex topics, + assignee match, temporal overlap, shared co-authors and co-inventors) predicts correctness? +- **RQ2. How does link error reach the answer?** For lookup, multi-hop, counting and ranking queries: + how much does the answer change per unit of link error, and does realistic error (sampled from the + RQ1 error model) behave differently from the random perturbation used in prior benchmarks? +- **RQ3. Can certain and possible answers be computed at interactive cost?** Monte Carlo sampling of + possible worlds over link confidence, giving intervals for counts and stable sets for rankings, + compared with exact computation on small subgraphs. +- **RQ4. Does exposing link confidence make LLM question answering more reliable?** Text-to-Cypher + and tool-using pipelines with and without access to confidence and provenance, including one + supervised fine-tuned model that writes confidence-aware queries and reports "confirmed" versus + "possible" results. + +## Method + +1. **Gold set (weeks 5 to 9).** About 550 candidate links, stratified by link type and by name + frequency so that common names are over-sampled. Two annotators label each link independently + using the evidence a human scout would check (ORCID, institutional pages, patent assignee, register + entry); disagreements are adjudicated. Report Cohen's kappa. Budget: about 60 of the 80 hours. +2. **Confidence model.** A small calibrated classifier (logistic regression and gradient boosting) + over evidence features, trained on the gold set with cross-validation; reliability diagrams and + expected calibration error. Output: a `confidence` and `method` on every inferred edge in the graph. +3. **Error model and injection toolkit.** Fit where errors occur (by name frequency, degree, source), + then generate corrupted graph variants three ways: uniformly random, degree-preserving, and + realistic (sampled from the fitted model), at error rates from 1 to 20 percent. +4. **Query set.** About 300 queries in the five types of the original outline (lookup, counting, + multi-step, summary, over time), each tagged with the link types it crosses. Gold answers come from + executing reference Cypher on a reference graph restricted to verified links. +5. **Possible-worlds answering.** Sample link sets according to confidence, execute, aggregate: + intervals for counts, inclusion probabilities for set answers, rank stability for top-k. Measure + interval coverage against the reference and the cost per query. +6. **LLM pipelines.** Four systems (schema-prompted text-to-Cypher, tool-using agent over MCP, the + same two with confidence exposed) across three models (local 8B, the fine-tuned 8B, one hosted + large model). The fine-tuned model is trained with Unsloth on graph-generated pairs whose target + queries filter or split by confidence. + +## Evaluation + +| Question | Measures | +|---|---| +| RQ1 | Pairwise and entity-centric precision, recall, F1 per link type; kappa; ECE and reliability diagrams; feature ablation | +| RQ2 | Answer change versus error rate per query type: exact match, Jaccard for sets, relative error for counts, Kendall tau for rankings; realistic versus random noise; with and without entity resolution (the ablation from the original outline) | +| RQ3 | Coverage of 90 percent intervals, interval width, agreement with exact computation on subgraphs up to a tractable size, latency versus number of sampled worlds | +| RQ4 | Execution accuracy; penalty-based reliability score in the style of TrustSQL; share of answers that correctly flag uncertain evidence; human rating of answer usefulness on 100 answers (remaining annotation hours); cost and latency | + +Statistics: bootstrap confidence intervals everywhere, paired tests between systems, three seeds for +anything trained. + +## What gets released (open sources only) + +- The author-to-inventor gold set (OpenAlex and patent-office data are public) with annotation guidelines. +- The noise-injection toolkit and the possible-worlds query layer for FalkorDB. +- The query set and reference answers over the open subgraph (OpenAlex, CORDIS, patents; DFG after a + licence check). Officer and news results are reported in aggregate only. + +## Schedule + +| Weeks | Work | +|---|---| +| 1 to 4 | Common start; literature; annotation guidelines | +| 5 to 9 | Gold set, agreement, RQ1 numbers | +| 10 to 12 | Confidence model, edges annotated in the graph, error model | +| 13 to 15 | Query set and reference answers | +| 16 to 18 | Injection experiments (RQ2) | +| 19 to 21 | Possible-worlds answering (RQ3) | +| 22 to 24 | LLM pipelines and fine-tuned model (RQ4) | +| 25 to 26 | Writing, paper draft | + +Cut order if late: drop the fine-tuned model in RQ4 first (keep prompting-only pipelines), then reduce +RQ3 to counts only. Never cut the gold set. + +## Risks + +- **Gold set too small for rare error types.** Mitigation: stratified sampling, and ORCID-verified + links as an additional silver standard. +- **Possible-worlds sampling too slow for aggregates over millions of edges.** Mitigation: restrict + sampling to the edges a query touches; FalkorDB executes the per-world query in milliseconds. +- **Reviewers ask for a second dataset.** Mitigation: run the injection experiments also on STaRK-MAG + (arXiv 2404.13207) or a CypherBench graph, where only synthetic error is possible; that contrast is + itself a result. + +## Reading list to start from + +arXiv 2410.08085, 2510.14271, 2606.15833, 1305.7006, 1904.00234, 2303.07469, 2108.07758, 2404.05622, +2502.11610, 2310.11244, 2409.08185, 2403.15879, 2506.05690. All identifiers come from a literature search +on 2026-09-17 and must be verified. diff --git a/docs/thesis/plan-b-nlp.md b/docs/thesis/plan-b-nlp.md new file mode 100644 index 00000000..0bf0d48c --- /dev/null +++ b/docs/thesis/plan-b-nlp.md @@ -0,0 +1,121 @@ +# Plan B (NLP): Learning when not to answer + +**Working title:** Learning when not to answer: reliability-aware reinforcement fine-tuning of small +language models for text-to-Cypher in German and English + +**Target venues:** ACL, EMNLP or NAACL Findings; workshops TrustNLP, UncertaiNLP, KnowledgeNLP, GenAIK; +LREC-COLING for the dataset. + +## The problem in one paragraph + +A local model that translates questions into Cypher fails in ways the user cannot see. In this +project, an 8B model without the schema invented a property, received nulls, and reported that the +information "is not available"; a server-side result cap silently truncated a count; and a question +about a researcher named Thomas Kaiser can only be answered over 92 name-matched companies. Accuracy +on answerable questions, which is what text-to-Cypher papers report, does not capture any of this. A +deployable model must do one of three things: answer, answer with a qualification, or decline. This +thesis builds the benchmark for that behaviour and tests whether reinforcement fine-tuning with +execution-verified, penalty-aware rewards can teach it to a small model, in two languages. + +## Gap and closest related work + +- Text-to-Cypher fine-tuning is established, including RL: Text2Cypher (GenAIK 2025), GRPO refinement + for small models (Applied Sciences 15(15):8206, 2025), multi-agent text-to-Cypher (arXiv 2511.08274), + automatic dataset generation (CypherBench, ACL 2025; arXiv 2606.08481, 2606.27742, 2606.14325). All + evaluate answerable questions only. +- Reliability with infeasible questions exists for SQL (TrustSQL, arXiv 2403.15879, penalty-based + scoring) and for Freebase KBQA (GrailQAbility, ACL 2023; RetinaQA, ACL 2024). Not for property graphs, + not for LLM-era text-to-Cypher. +- Abstention-aware RL exists for open-domain QA (TruthRL, arXiv 2509.25760, ternary reward; KARL, + arXiv 2604.22779; TIAR, arXiv 2605.25850; search agents, arXiv 2607.10738). There the reward needs a + judge or a gold string. Text-to-Cypher has a verifiable reward by execution, and a third outcome + these papers do not have: the correct answer exists but rests on uncertain evidence. +- Multilingual text-to-Cypher covers Spanish and Turkish (arXiv 2506.21445, 2601.16097). German is + missing, and German compounds plus English entity names make it a real test, not a translation + exercise. + +## Research questions + +- **RQ1. Benchmark.** What kinds of questions should a text-to-Cypher model not answer plainly over a + real graph? Proposed categories: schema element missing, value missing, beyond Cypher, ambiguous + entity (common names), outside the covered time span, aggregation over inferred links, and unsafe + aggregation (result cap or timeout would truncate). +- **RQ2. Training.** Does GRPO with an execution-verified, penalty-aware reward beat supervised + fine-tuning on reliability, and how does the reward shape (binary, ternary, penalty-weighted, + with a "qualified answer" outcome) trade accuracy against over-abstention? +- **RQ3. Language.** How large is the German to English gap before and after training; does training + in one language transfer; does translated training data suffice? +- **RQ4. Generalisation.** Held-out schema regions (patents and companies unseen in training), + compositional depth, paraphrases, and transfer to public graphs (a CypherBench graph extended with + infeasible questions) so that the main results are reproducible without INSE data. +- **RQ5. What changed?** Error taxonomy before and after RL; calibration of the decision to abstain. + +## Method + +1. **Dataset.** Templates filled from the graph, paraphrased by a larger model, in German and + English, about 6,000 training and 1,200 test items, half answerable. Test entities and templates + never occur in training. The open subgraph (OpenAlex, CORDIS, patents) is the release version; the + full graph adds company and news questions for internal results. +2. **Human validation (80 hours).** Two annotators validate about 400 test items for correctness of + the label, category and German naturalness (kappa reported), and later classify about 300 model + errors into the taxonomy. +3. **Public counterpart.** The same infeasibility categories constructed on one CypherBench graph, + which carries no real identity uncertainty; "aggregation over inferred links" is simulated there. +4. **Models.** Qwen3-4B and 8B, Llama-3.1-8B, one Gemma model. Baselines: zero-shot and few-shot, a + hosted large model, the public Neo4j text2cypher fine-tune, RL without abstention. +5. **Training.** Unsloth QLoRA supervised fine-tuning, then GRPO. Reward from execution: result-set + equivalence for answers, category match for abstentions, a graded reward for qualified answers + (correct result plus correct flag), and a penalty c for wrong answers. Sweep c. Three seeds each. + +## Evaluation + +| Aspect | Measures | +|---|---| +| Answerable questions | Execution accuracy by result-set equivalence, by question type and hop count | +| Reliability | TrustSQL-style score RS(c) for c in {0, 1, 10}; abstention precision, recall and F1 per category; over-abstention rate; risk-coverage curves | +| Qualification | Share of uncertain-evidence questions answered with the correct flag; human usefulness rating on a sample | +| Calibration | ECE of the answer-or-abstain decision; selective accuracy | +| Language | German minus English gap per model and training regime; transfer matrix | +| Generalisation | Held-out schema, depth, paraphrase; transfer to the CypherBench variant | +| Cost | Tokens, latency, GPU hours per point of RS gained; data-efficiency curves | + +Statistics: bootstrap intervals, McNemar between systems, three seeds, all prompts and decoding +settings released. + +## What gets released + +Benchmark on the open subgraph in two languages, the CypherBench extension, LoRA adapters, reward and +evaluation code. + +## Schedule + +| Weeks | Work | +|---|---| +| 1 to 4 | Common start; literature; category definitions | +| 5 to 9 | Dataset generation, German versions, human validation | +| 10 to 11 | Public counterpart on CypherBench | +| 12 to 14 | Baselines and supervised fine-tuning | +| 15 to 19 | GRPO, reward ablations, seeds | +| 20 to 22 | Language and generalisation experiments | +| 23 to 24 | Error taxonomy, calibration analysis | +| 25 to 26 | Writing, paper draft | + +Cut order if late: drop the third and fourth base model, then the qualified-answer outcome (keep +answer versus abstain). Never cut the public counterpart; without it the NLP community cannot +reproduce the main table. + +## Risks + +- **A close paper appears.** The space moves fast. Mitigation: the combination of uncertain-evidence + questions, a real multi-source graph and German is hard to replicate; submit a dataset paper early. +- **RL collapses into always abstaining or never abstaining.** Known from TruthRL-style training. + Mitigation: balanced batches, penalty sweep, KL control, report the failure honestly if it persists. +- **Template artefacts.** Models learn templates rather than semantics. Mitigation: paraphrase + diversity, template-held-out test split, human-written subset of 150 questions. + +## Reading list to start from + +arXiv 2403.15879, 2212.10189, 2403.10849, 2509.25760, 2604.22779, 2605.25850, 2607.10738, 2506.21445, +2601.16097, 2412.18702, 2511.08274, 2606.08481, 2606.27742, 2606.14325; Applied Sciences 15(15):8206; +"Why Uncertainty Estimation Methods Fall Short in RAG" (Findings of ACL 2025). All identifiers come from +a literature search on 2026-09-17 and must be verified. diff --git a/docs/thesis/plan-c-information-retrieval.md b/docs/thesis/plan-c-information-retrieval.md new file mode 100644 index 00000000..4828c1eb --- /dev/null +++ b/docs/thesis/plan-c-information-retrieval.md @@ -0,0 +1,129 @@ +# Plan C (information retrieval): Does the graph find the right people? + +**Working title:** Does the graph find the right people? A leakage-free evaluation of graph-augmented +expert and industry-partner retrieval for technology transfer + +**Target venues:** SIGIR (short or resource paper), ECIR, CIKM, ICTIR. Alternative: JCDL. + +## The problem in one paragraph + +INSE exists to help scouts find the right researcher for a topic and the right partner for a +researcher. Today that is keyword and vector search over profiles. The graph adds collaboration, +projects, patents, per-paper industry affiliations and time. Whether that improves ranking is an +empirical question, and the usual way to answer it with LLM-based rankers is broken: a model that has +read the web up to 2025 already "knows" who collaborated with whom, so evaluating on past events +measures memory, not retrieval. This thesis builds a test collection with two kinds of ground truth, +human relevance judgments and events that happened after the models' knowledge cutoff, and uses it to +compare text, graph and LLM rankers, including a reranker fine-tuned on supervision derived from the +graph itself. + +## Gap and closest related work + +- Partner and collaboration recommendation is studied with graph learning on single sources: + university-industry recommendation on a topic-institution graph (Scientometrics, 2025), technological + partner recommendation from patents with temporal heterogeneous graphs (Information Processing and + Management, 2025), hypergraph link prediction for collaboration (2026). They use one data source, + institutions rather than people, and no LLM. +- "Can LLMs Predict Academic Collaboration?" (arXiv 2604.01379) compares topology heuristics with LLM + link prediction on co-authorship only, and temporal leakage is the open issue. Work on LLM + backtesting shows how strongly leakage inflates results (arXiv 2602.17234, 2605.03762, 2605.18843). +- STaRK-MAG (NeurIPS D&B 2024, arXiv 2404.13207) evaluates retrieval over a scholarly graph with + synthetic queries for papers, not people, and without time. +- GraphRAG versus RAG comparisons (arXiv 2506.05690, 2502.11371, 2604.09666) use text corpora and + question answering, not ranking of people with graded relevance. +- Classic expert-finding test collections (W3C, CERC, academic collections) predate LLM rankers and + multi-source graphs. There is no current collection for expert finding in a German research setting. + +## Tasks + +- **T1 Expert finding.** Query: a topic or need as a scout would phrase it, in German or English. + Result: ranked UDE researchers. +- **T2 Partner recommendation.** Query: a researcher. Result: ranked companies (OpenAlex institutions + of type `company`) the researcher is likely to start working with. + +## Research questions + +- **RQ1.** Does graph evidence improve ranking beyond text? Which evidence (co-authorship, projects, + patents, per-paper industry affiliation, recency) carries the gain, for T1 and T2 separately? +- **RQ2.** Can a small reranker fine-tuned on supervision derived from the graph (future links as + positives, topic-similar non-links as hard negatives) match a large zero-shot LLM reranker at a + fraction of the cost? +- **RQ3.** How much of an LLM ranker's quality is parametric memory? Compare events before and after + the model's knowledge cutoff, and rankings with researcher names masked. +- **RQ4.** Who benefits? Exposure of early-career versus established researchers under each ranker, + and sensitivity of rankings to identity errors (junk company institutions, over-merged profiles). + +## Method + +1. **Temporal split.** Freeze the graph at a cut date T (end of 2023 for training signals). Test + events after T: first-time per-paper industry affiliations (`INVOLVES` to a company with no earlier + joint work), new patents, new CORDIS and DFG project participations. A second, smaller test set uses + only events after the newest evaluated model's knowledge cutoff. +2. **Topics.** 50 to 60 T1 topics drawn from real material: CORDIS call topics, IPC class + descriptions, news themes, and needs phrased by the chair's transfer contacts, each in German and + English. T2 uses about 300 researchers with at least one post-T event. +3. **Relevance judgments (80 hours).** Pooled top-20 of all systems per T1 topic, graded 0 to 3 by two + annotators with an overlap sample for agreement: about 1,500 to 2,000 judgments at two to three + minutes each. Profiles shown to annotators come from public OpenAlex data. +4. **Systems.** BM25 and dense e5 retrieval over researcher profiles (both exist in INSE), hybrid; + graph rankers (personalised PageRank, meta-path counts, a temporal graph neural network); LLM + listwise reranker with and without a verbalised evidence subgraph; the fine-tuned reranker + (Unsloth, 4 to 8B, trained on graph-derived pairs); an agentic system using the graph through MCP + as the high-cost reference. +5. **Leakage controls.** Name masking, pre- versus post-cutoff comparison, and a check that no + retrieval document postdates T. + +## Evaluation + +| Aspect | Measures | +|---|---| +| T1 effectiveness | nDCG@10, MAP, Recall@100 on human judgments; German versus English queries | +| T2 effectiveness | MRR, Hits@10, nDCG@10 on post-T events; separately on post-cutoff events | +| Evidence ablation | Drop one edge type at a time; recency decay on or off | +| Fine-tuning | Reranker versus zero-shot large LLM: effectiveness, tokens, latency, GPU hours; training-size curve | +| Leakage | Performance difference pre- versus post-cutoff and masked versus unmasked, per ranker | +| Exposure and robustness | Share of top-10 exposure by career stage; rank change after removing junk institutions and suspected merged profiles | + +Statistics: paired randomisation tests with Holm correction, confidence intervals by bootstrap over +topics, inter-annotator agreement (kappa, and Krippendorff's alpha for graded labels). + +## What gets released + +The test collection (topics in two languages, graded judgments on public OpenAlex author IDs, +post-T event lists from open sources), the temporal split protocol, reranker adapters and code. +Company-register and news evidence is used internally only. + +## Schedule + +| Weeks | Work | +|---|---| +| 1 to 4 | Common start; literature; temporal split and event extraction | +| 5 to 7 | Topics, annotation guidelines, text baselines | +| 8 to 11 | Graph rankers, first pooled runs | +| 12 to 15 | Relevance judgments (annotators), agreement | +| 16 to 19 | LLM rerankers and the fine-tuned reranker | +| 20 to 22 | Leakage, ablation, exposure and robustness analyses | +| 23 to 24 | Second pooling round for late systems, significance testing | +| 25 to 26 | Writing, paper draft | + +Cut order if late: drop the agentic reference system, then T2's graph neural network (keep PageRank +and meta-paths). Never cut the post-cutoff test set; it is the contribution. + +## Risks + +- **Too few post-cutoff events.** UDE alone yields a limited number of first-time industry links per + year. Mitigation: add the other two default organisations (Bochum, Dortmund) with the same loader, + which triples the cohort at no engineering cost. +- **Pooling bias against systems added late.** Mitigation: a second pooling round in weeks 23 to 24, + and report condensed-list metrics. +- **Identity errors contaminate ground truth.** A "new industry link" may be a mis-resolved + institution. Mitigation: per-paper affiliations only (not author-level), a manual check of a sample + of test events, and junk-institution filtering documented in the thesis. + +## Reading list to start from + +arXiv 2404.13207, 2604.01379, 2607.04529, 2602.17234, 2605.03762, 2605.18843, 2506.05690, 2502.11371, +2604.09666; "Recommending university-industry collaboration: a topic-institution graph-based solution" +(Scientometrics, 2025); "From patents to partners" (Information Processing and Management, 2025); +"Guiding retrieval using LLM-based listwise rankers" (ECIR 2025). All identifiers come from a +literature search on 2026-09-17 and must be verified. diff --git a/service/scripts/falkordb/QUERIES.md b/service/scripts/falkordb/QUERIES.md new file mode 100644 index 00000000..c271c8f1 --- /dev/null +++ b/service/scripts/falkordb/QUERIES.md @@ -0,0 +1,282 @@ +# Query cookbook for the `ude` graph + +Cypher examples for the whole-university graph built by `bulk_load.py` (FalkorDB Browser at +http://localhost:3000, graph `ude`, or `FalkorDB(host="localhost").select_graph("ude").ro_query(...)`). +Every example was run against the graph on 2026-09-15; timings are from that run. + +Conventions: + +- `Author` nodes of the university's own researchers carry the extra label `Cohort` (indexed). + Start queries there whenever you can. +- `CO_AUTHOR` edges are undirected in meaning (stored from the smaller to the larger author id); + match them without an arrow: `(a)-[c:CO_AUTHOR]-(b)`. +- Aggregations render as tables. To see a graph, return nodes and relationships (or paths). +- Queries that touch the whole graph take 2 to 20 s; raise the browser's timeout first + (`docker exec pensive_tu redis-cli GRAPH.CONFIG SET TIMEOUT 60000`). +- Results are capped at 10,000 rows by the server (`RESULTSET_SIZE`). + +## Overview + +```cypher +MATCH (n) RETURN labels(n), count(n) ORDER BY count(n) DESC +``` +```cypher +MATCH ()-[r]->() RETURN type(r), count(r) ORDER BY count(r) DESC +``` + +Everything around one researcher, for the canvas: + +```cypher +MATCH (a:Cohort {name: 'Nikolai Axmacher'})-[r]-(n) RETURN a, r, n LIMIT 300 +``` + +Source coverage of the cohort (works, projects, patents, news, companies): + +```cypher +MATCH (a:Cohort) +OPTIONAL MATCH (a)-[:AUTHORED]->(w:Work) WITH a, count(DISTINCT w) AS works +OPTIONAL MATCH (a)-[:CONTRIBUTED_TO|DFG_ROLE]->(p:Project) WITH a, works, count(DISTINCT p) AS projects +OPTIONAL MATCH (a)-[:INVENTOR_OF]->(pt:Patent) WITH a, works, projects, count(DISTINCT pt) AS patents +OPTIONAL MATCH (a)-[:MENTIONED_IN]->(n:NewsArticle) WITH a, works, projects, patents, count(DISTINCT n) AS news +OPTIONAL MATCH (a)-[:OFFICER_OF]->(c:Company) WITH a, works, projects, patents, news, count(DISTINCT c) AS companies +RETURN count(a) AS cohort, + sum(CASE WHEN works > 0 THEN 1 ELSE 0 END) AS with_works, + sum(CASE WHEN projects > 0 THEN 1 ELSE 0 END) AS with_projects, + sum(CASE WHEN patents > 0 THEN 1 ELSE 0 END) AS with_patents, + sum(CASE WHEN news > 0 THEN 1 ELSE 0 END) AS with_news, + sum(CASE WHEN companies > 0 THEN 1 ELSE 0 END) AS with_companies +``` + +## Topics, subfields, fields and domains of the institution + +The path from the institution: `Institution <-[:REPRESENTS]- Organization <-[:MEMBER_OF]- Cohort`. + +Domains with counts (2.1 s): + +```cypher +MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(:Cohort)-[:AUTHORED]->(w:Work) + -[:HAS_TOPIC]->(t:Topic)-[:IN_SUBFIELD]->(s:Subfield)-[:IN_FIELD]->(f:Field)-[:IN_DOMAIN]->(d:Domain) +RETURN d.name AS domain, count(DISTINCT f) AS fields, count(DISTINCT s) AS subfields, + count(DISTINCT t) AS topics, count(DISTINCT w) AS works +ORDER BY works DESC +``` + +Full hierarchy table, strongest topics first (2.4 s; drop `LIMIT` for all 4,336 topics): + +```cypher +MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(:Cohort)-[:AUTHORED]->(w:Work) + -[:HAS_TOPIC]->(t:Topic)-[:IN_SUBFIELD]->(s:Subfield)-[:IN_FIELD]->(f:Field)-[:IN_DOMAIN]->(d:Domain) +RETURN d.name AS domain, f.name AS field, s.name AS subfield, t.name AS topic, count(DISTINCT w) AS works +ORDER BY works DESC LIMIT 100 +``` + +Fields by number of researchers, using OpenAlex's author-level topics (0.1 s): + +```cypher +MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(a:Cohort)-[:WORKS_ON]->(t:Topic) + -[:IN_SUBFIELD]->(s:Subfield)-[:IN_FIELD]->(f:Field)-[:IN_DOMAIN]->(d:Domain) +RETURN d.name AS domain, f.name AS field, count(DISTINCT a) AS researchers, count(DISTINCT t) AS topics +ORDER BY researchers DESC +``` + +### Graph versions via the research profile edges + +The `profile` phase materialises `(Institution)-[:ACTIVE_IN {level, works, researchers}]->(Topic|Subfield|Field|Domain)`, +so the counts live on drawable edges. Set the node caption of Domain/Field/Subfield/Topic to `name`. + +Domains as a star around the institution, and domains with their fields: + +```cypher +MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN]->(d:Domain) RETURN i, r, d +``` +```cypher +MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN]->(f:Field)-[c:IN_DOMAIN]->(d:Domain) +RETURN i, r, f, c, d +``` + +Tree of the strongest topics attached to the institution (lower `800` to widen; add +`AND d.name = 'Physical Sciences'` for one domain): + +```cypher +MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN {level: 'topic'}]->(t:Topic) WHERE r.works >= 800 +MATCH (t)-[a:IN_SUBFIELD]->(s:Subfield)-[b:IN_FIELD]->(f:Field)-[c:IN_DOMAIN]->(d:Domain) +RETURN i, r, t, a, s, b, f, c, d +``` + +Fields by researchers: + +```cypher +MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN]->(f:Field) WHERE r.researchers >= 300 +RETURN i, r, f +``` + +Without materialised edges: aggregate in a `WITH`, keep the top nodes, match the hierarchy again +and return nodes and relationships (the counts are not shown, the institution is not connected): + +```cypher +MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(:Cohort)-[:AUTHORED]->(w:Work)-[:HAS_TOPIC]->(t:Topic) +WITH t, count(DISTINCT w) AS works ORDER BY works DESC LIMIT 40 +MATCH (t)-[a:IN_SUBFIELD]->(s:Subfield)-[b:IN_FIELD]->(f:Field)-[c:IN_DOMAIN]->(d:Domain) +RETURN t, a, s, b, f, c, d +``` + +## Collaboration + +Strongest collaborations inside the university: + +```cypher +MATCH (a:Cohort)-[c:CO_AUTHOR]->(b:Cohort) +RETURN a.name, b.name, c.weight, c.first_year, c.last_year ORDER BY c.weight DESC LIMIT 20 +``` + +Top external partner institutions (4 s): + +```cypher +MATCH (a:Cohort)-[:CO_AUTHOR]-(b:Author)-[:AFFILIATED_WITH]->(i:Institution) +WHERE NOT b:Cohort AND i.id <> 'I62318514' +RETURN i.name, i.country_code, count(DISTINCT b) AS partners ORDER BY partners DESC LIMIT 20 +``` + +## Industry collaborations + +OpenAlex types institutions as `education`, `healthcare`, `company`, `government`, `nonprofit`, +`facility`, `funder` or `other`; the value is stored as `Institution.type`. Industry means +`type = 'company'`. Two caveats: OpenAlex contains junk "companies" resolved from generic +affiliation strings (`Faculty (United Kingdom)`, `Signal Processing (United States)`, +`Engineering (Italy)`), and the author-level `AFFILIATED_WITH` edge is not tied to a paper, so a +co-author who was ever at a company counts on every shared work. The `affiliations` phase adds the +per-work view: `AUTHORED.institution_ids` and `(Work)-[:INVOLVES {authors}]->(Institution)`. +Prefer the per-work queries below; the author-level ones are kept as a quick approximation. + +How much it matters (validated 2026-09-15): for Daniel Erni the per-work view gives 10 industry +co-publications with 4 companies (IBM, CETC, CSEM, ID Quantique), the author-level view claims 61 +joint works with 8 companies. University-wide, 15,569 works involve 3,874 companies. A further +caveat is OpenAlex author disambiguation: a few cohort profiles are merged with namesakes +(`Róbert Langer` carries the MIT chemist's industry ties), so check `orcid` before trusting an outlier. + +### Per work (precise) + +Companies on the papers of one researcher, with the co-authors who were at the company on that paper: + +```cypher +MATCH (a:Cohort {name: 'Daniel Erni'})-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'}) +MATCH (w)<-[e:AUTHORED]-(b:Author) WHERE i.id IN e.institution_ids +RETURN i.name AS company, i.country_code AS country, count(DISTINCT w) AS works, + collect(DISTINCT b.name)[0..4] AS company_coauthors +ORDER BY works DESC +``` + +The same as a graph (researcher, shared works, companies): + +```cypher +MATCH (a:Cohort {name: 'Daniel Erni'})-[x:AUTHORED]->(w:Work)-[v:INVOLVES]->(i:Institution {type: 'company'}) +RETURN a, x, w, v, i +``` + +Industry partners of researchers from a field (author-level OpenAlex topics define the field): + +```cypher +MATCH (a:Cohort)-[:WORKS_ON]->(:Topic)-[:IN_SUBFIELD]->()-[:IN_FIELD]->(:Field {name: 'Engineering'}) +WITH DISTINCT a +MATCH (a)-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'}) +RETURN i.name AS company, i.country_code AS country, + count(DISTINCT a) AS ude_researchers, count(DISTINCT w) AS joint_works +ORDER BY ude_researchers DESC LIMIT 25 +``` + +Researchers of a field ranked by industry ties: + +```cypher +MATCH (a:Cohort)-[:WORKS_ON]->(:Topic)-[:IN_SUBFIELD]->()-[:IN_FIELD]->(:Field {name: 'Engineering'}) +WITH DISTINCT a +MATCH (a)-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'}) +RETURN a.name, count(DISTINCT i) AS companies, count(DISTINCT w) AS works, collect(DISTINCT i.name)[0..3] AS sample +ORDER BY companies DESC LIMIT 20 +``` + +Industry co-publications per year for one researcher: + +```cypher +MATCH (a:Cohort {name: 'Daniel Erni'})-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'}) +RETURN w.year, count(DISTINCT w) AS works, collect(DISTINCT i.name)[0..3] AS companies +ORDER BY w.year DESC +``` + +Graph view for a field: researchers, their industry co-authored works and the companies +(the `LIMIT` keeps the canvas readable): + +```cypher +MATCH (a:Cohort)-[:WORKS_ON]->(:Topic)-[:IN_SUBFIELD]->()-[:IN_FIELD]->(:Field {name: 'Engineering'}) +WITH DISTINCT a +MATCH (a)-[x:AUTHORED]->(w:Work)-[v:INVOLVES]->(i:Institution {type: 'company'}) +WITH a, x, w, v, i ORDER BY w.year DESC LIMIT 200 +RETURN a, x, w, v, i +``` + +### Author level (approximate, no `affiliations` phase needed) + +```cypher +MATCH (a:Cohort {name: 'Daniel Erni'})-[c:CO_AUTHOR]-(b:Author)-[:AFFILIATED_WITH]->(i:Institution {type: 'company'}) +RETURN i.name AS company, i.country_code AS country, collect(DISTINCT b.name)[0..3] AS coauthors, sum(c.weight) AS joint_works +ORDER BY joint_works DESC LIMIT 20 +``` +```cypher +MATCH (a:Cohort {name: 'Daniel Erni'})-[c:CO_AUTHOR]-(b:Author)-[f:AFFILIATED_WITH]->(i:Institution {type: 'company'}) +RETURN a, c, b, f, i +``` + +### Handelsregister links (founders and officers, not co-authorship) + +```cypher +MATCH (a:Cohort)-[r:OFFICER_OF]->(c:Company) +RETURN a.name, c.name, c.registered_office, r.positions ORDER BY a.name LIMIT 50 +``` +```cypher +MATCH (a:Cohort)-[r:OFFICER_OF]->(c:Company) RETURN a, r, c LIMIT 200 +``` + +## Projects, funders, patents, news + +Projects per source and link type: + +```cypher +MATCH (x)-[r:OUTPUT_OF|CONTRIBUTED_TO|DFG_ROLE|PARTICIPATES_IN]->(p:Project) +RETURN p.source, type(r), count(r) ORDER BY p.source, count(r) DESC +``` + +EU consortium partners of the university: + +```cypher +MATCH (:Institution {id: 'I62318514'})-[:PARTICIPATES_IN]->(p:Project)<-[:PARTICIPATES_IN]-(o:EuOrganization) +WHERE o.name <> 'UNIVERSITAET DUISBURG-ESSEN' +RETURN o.name, o.country, count(DISTINCT p) AS shared ORDER BY shared DESC LIMIT 20 +``` + +Funders of the cohort (author level): + +```cypher +MATCH (a:Cohort)-[r:FUNDED_BY]->(f:Funder) +RETURN f.name, count(a) AS researchers, sum(r.publications) AS publications ORDER BY researchers DESC LIMIT 20 +``` + +Patents with their OpenAlex topics: + +```cypher +MATCH (a:Author)-[:INVENTOR_OF]->(p:Patent) +OPTIONAL MATCH (p)-[:HAS_TOPIC]->(t:Topic) +RETURN a.name, p.source, p.year, left(p.title, 60), collect(t.name)[0..2] ORDER BY p.year DESC LIMIT 20 +``` + +News mentions with topics: + +```cypher +MATCH (a:Cohort)-[m:MENTIONED_IN]->(n:NewsArticle) OPTIONAL MATCH (n)-[:HAS_TOPIC]->(t:Topic) +RETURN a.name, n.title, n.date, m.ambiguous, collect(DISTINCT t.name)[0..3] ORDER BY n.date DESC LIMIT 20 +``` + +Work classifications (LLM): + +```cypher +MATCH (w:Work) WHERE w.primary_category IS NOT NULL +RETURN w.primary_category, count(w) ORDER BY count(w) DESC +``` diff --git a/service/scripts/falkordb/README.md b/service/scripts/falkordb/README.md new file mode 100644 index 00000000..60e08df8 --- /dev/null +++ b/service/scripts/falkordb/README.md @@ -0,0 +1,289 @@ +# FalkorDB example: a researcher graph from the INSE sources + +`load_graph.py` builds a small knowledge graph in [FalkorDB](https://www.falkordb.com/) around a +couple of researchers from the predefined ("default") organizations in +`src/data/predefined_accounts.json`, i.e. Universität Duisburg-Essen (`I62318514`), +Ruhr-Universität Bochum (`I904495901`) and TU Dortmund (`I200332995`). + +It does not talk to OpenAlex, EPO or CORDIS directly. Every fact comes from the backend's existing +source logic in `src/main/inse`, which reads the INSE Elasticsearch mirrors, so the graph shows +exactly what the REST API can already see: + +| Source | Backend function | Graph | +| --- | --- | --- | +| OpenAlex authors (profile, ORCID, metrics, affiliations, topics) | `authors.v2.service.search_authors` / `get_author_by_id_strict_or_raise` | `Author`, `Institution`, `Topic`, `AFFILIATED_WITH`, `WORKS_ON` | +| OpenAlex works incl. co-authors and their institutions | `works.v2.service.get_author_works` | `Work`, `AUTHORED`, `HAS_TOPIC`, co-author `Author`s | +| CORDIS (EU) and DFG projects, bridged through publication DOIs | `works.logic.get_publication_dois_of_author`, `projects.projects_search_client.get_cordis_eu_project_ids_by_dois` / `get_dfg_project_ids_by_dois`, `get_enriched_cordis_project_by_id`, `get_dfg_project_by_id` | `Project`, `CONTRIBUTED_TO` | +| EPO + USPTO patents (name matching with institution guard) | `patents.authors.logic.get_patents_by_author_id` | `Patent`, `INVENTOR_OF`, `HAS_TOPIC` | +| Funders of the author's funded publications | `funders.logic.get_funders_by_author_id` | `Funder`, `FUNDED_BY` (author and work level) | +| News mentions (UDE "aktuell", CC-News) | `news.logic.get_news_by_author` | `NewsArticle`, `MENTIONED_IN`, `HAS_TOPIC` | +| Handelsregister officer matches | `company_connections.logic.get_company_connections_by_author_id` | `Company`, `OFFICER_OF` | +| Predefined organizations | `src/data/predefined_accounts.json`, `institutions.v2.service.get_institution_by_id` | `Organization`, `REPRESENTS`, `MEMBER_OF` | + +Co-authorship is not computed in Python. After loading, one Cypher query derives +`(:Author)-[:CO_AUTHOR {weight, first_year, last_year}]->(:Author)` from the `AUTHORED` edges, +which is the part the in-service collaboration-graph API currently leaves to the client. + +## Prerequisites + +1. A FalkorDB server. The quickest way is the official image, which also serves a browser UI on + port 3000: + + ```bash + docker run -d --name falkordb -p 6379:6379 -p 3000:3000 falkordb/falkordb:latest + ``` + +2. The service image `inse-service:1.0.0` (built by `./gradlew :service:createImage`, and already + present if you ever ran `./gradlew :service:serve`). The script imports the `inse` package, whose + `util` module pulls in sentence-transformers/torch, so the image is the easiest runtime that has + every dependency. `src/main/inse/.env` must contain the Elasticsearch credentials as usual. + +## Run + +```bash +cd service +scripts/falkordb/run.sh # 2 researchers per default organization +scripts/falkordb/run.sh --reset --organization Duisburg --per-org 3 +scripts/falkordb/run.sh --author-id A5040796987 --author-id A5122994949 # explicit researchers, added incrementally +scripts/falkordb/run.sh --no-write --dump /scripts/falkordb/graph.json # collect only, inspect the JSON +scripts/falkordb/run.sh --help +``` + +`run.sh` starts a throwaway container from the service image, mounts `src/main`, `src/data` and +`scripts`, installs `falkordb` from `requirements.txt` and reaches the server on the host through +`host.docker.internal`. Override the target with `FALKORDB_HOST`, `FALKORDB_PORT`, +`FALKORDB_PASSWORD` and `FALKORDB_GRAPH` (default graph name `inse`). + +Loads are idempotent: every node and edge is `MERGE`d on its `id`, so re-running or adding +researchers with `--author-id` extends the same graph. `--reset` drops the graph right before +writing, after all sources were collected. One failing source is logged and skipped, it does not +abort the load. + +A default run (six researchers, 40 works each) takes a few minutes and ends with roughly 2,300 nodes +and 9,000 relationships. The slow parts are the DOI-to-project lookups (one detail query per hit) +and the EPO/USPTO scans for common names. + +### How the researchers are picked + +For each organization the script reuses the backend's active-cohort membership query +(`authors.institution_membership_query.build_institution_membership_query`, last known institution +plus an affiliation since the current year minus two) and then narrows the candidates so the graph +stays small and well disambiguated: + +- `works_count` within `--min-works`/`--max-works` (default 20 to 300) to skip hyper-authorship + profiles from large collaborations, +- an ORCID unless `--no-require-orcid` is given, +- every last known institution inside the organization's OpenAlex lineage, which drops merged + profiles that also "currently" belong to unrelated institutions, +- sorted by `works_count`, then `cited_by_count`. + +Works with more than `--max-authors-per-work` authors (default 30) keep their `Work` node but only +the seed researcher's own `AUTHORED` edge, so a single CERN paper cannot add a thousand co-authors. + +## Schema + +Node labels, all keyed by `id` (OpenAlex ids are stored without the `https://openalex.org/` prefix, +patents as `:`, projects as `cordis:` / `dfg:`): + +| Label | Properties | +| --- | --- | +| `Organization` | `name`, `openalex_institution_id` | +| `Institution` | `name`, `ror`, `country_code`, `type` | +| `Author` | `name`, `orcid`, `works_count`, `cited_by_count`, `h_index`, `i10_index`, `seed` (true for the selected researchers, false for co-authors) | +| `Work` | `title`, `year`, `type`, `language`, `cited_by_count`, `authors_count`, `hyperauthorship` | +| `Topic` | `name`, `subfield`, `field`, `domain` | +| `Project` | `source` (`cordis`/`dfg`), `source_id`, `title`, `acronym`, `start`, `end`, `funding_scheme`, `status`, `ec_max_contribution`, `url` | +| `Patent` | `patent_id`, `source` (EPO/USPTO), `title`, `year`, `publication_date`, `kind`, `status`, `country`, `ipc[]`, `assignees[]`, `inventors[]` | +| `Funder` | `name` | +| `NewsArticle` | `title`, `date`, `url` | +| `Company` | `name`, `status`, `registered_office`, `register` | + +Relationships: + +| Relationship | Properties | +| --- | --- | +| `(Organization)-[:REPRESENTS]->(Institution)` | | +| `(Author)-[:MEMBER_OF]->(Organization)` | | +| `(Author)-[:AFFILIATED_WITH]->(Institution)` | `years[]`, `last_known` (seed profiles only) | +| `(Author)-[:WORKS_ON]->(Topic)` | `score` | +| `(Author)-[:AUTHORED]->(Work)` | `position`, `corresponding` | +| `(Author)-[:CO_AUTHOR]->(Author)` | `weight`, `first_year`, `last_year` (derived in FalkorDB, `a.id < b.id`) | +| `(Work)-[:HAS_TOPIC]->(Topic)`, `(Patent)-[:HAS_TOPIC]->(Topic)`, `(NewsArticle)-[:HAS_TOPIC]->(Topic)` | `score` (works) | +| `(Author)-[:CONTRIBUTED_TO]->(Project)` | `via` = `publication_doi` | +| `(Author)-[:INVENTOR_OF]->(Patent)` | | +| `(Author)-[:FUNDED_BY]->(Funder)` | `publications` | +| `(Work)-[:FUNDED_BY]->(Funder)` | only for works that are in the graph | +| `(Author)-[:MENTIONED_IN]->(NewsArticle)` | `matching` = `display_name` | +| `(Author)-[:OFFICER_OF]->(Company)` | `positions[]`, `matching_method`, `common_name_warning` | + +## Example queries + +The queries for the whole-university graph `ude` are collected in [QUERIES.md](QUERIES.md). +The ones below target the small `inse` example graph. + +Paste these into the FalkorDB browser (http://localhost:3000, graph `inse`) or run them with the +Python client (`FalkorDB(host="localhost").select_graph("inse").ro_query(...)`). + +Everything around one researcher, for the visual explorer: + +```cypher +MATCH (a:Author {seed: true})-[r]-(n) WHERE a.name STARTS WITH 'Nikolai' RETURN a, r, n LIMIT 200 +``` + +Seed researchers per organization with counts per source: + +```cypher +MATCH (o:Organization)<-[:MEMBER_OF]-(a:Author) +OPTIONAL MATCH (a)-[:AUTHORED]->(w:Work) +OPTIONAL MATCH (a)-[:CONTRIBUTED_TO]->(p:Project) +OPTIONAL MATCH (a)-[:INVENTOR_OF]->(pt:Patent) +OPTIONAL MATCH (a)-[:OFFICER_OF]->(c:Company) +RETURN o.name, a.name, count(DISTINCT w) AS works, count(DISTINCT p) AS projects, + count(DISTINCT pt) AS patents, count(DISTINCT c) AS companies +ORDER BY o.name, a.name +``` + +Strongest co-authors and where they sit: + +```cypher +MATCH (s:Author {seed: true})-[c:CO_AUTHOR]-(o:Author)-[:AFFILIATED_WITH]->(i:Institution) +WITH s, o, c, collect(DISTINCT i.name) AS insts ORDER BY c.weight DESC +RETURN s.name, collect(o.name + ' (' + toString(c.weight) + ') @ ' + insts[0])[0..5] AS top +``` + +Topics shared by two of the selected researchers: + +```cypher +MATCH (a:Author {seed: true})-[:WORKS_ON]->(t:Topic)<-[:WORKS_ON]-(b:Author {seed: true}) +WHERE a.id < b.id RETURN a.name, b.name, collect(t.name) AS topics +``` + +Funders that several selected researchers share: + +```cypher +MATCH (a:Author {seed: true})-[:FUNDED_BY]->(f:Funder)<-[:FUNDED_BY]-(b:Author {seed: true}) +WHERE a.id < b.id +RETURN f.name, collect(DISTINCT a.name + ' & ' + b.name) AS pairs ORDER BY size(pairs) DESC LIMIT 5 +``` + +Projects per source and patents with their OpenAlex topics: + +```cypher +MATCH (a:Author)-[:CONTRIBUTED_TO]->(p:Project) RETURN p.source, count(DISTINCT p), collect(DISTINCT a.name) +``` + +```cypher +MATCH (a:Author)-[:INVENTOR_OF]->(p:Patent) +OPTIONAL MATCH (p)-[:HAS_TOPIC]->(t:Topic) +RETURN a.name, p.source, p.year, left(p.title, 60), collect(t.name)[0..2] ORDER BY p.year DESC LIMIT 10 +``` + +Company links, showing which ones rest on a common name: + +```cypher +MATCH (a:Author)-[r:OFFICER_OF]->(c:Company) +RETURN a.name, r.common_name_warning, count(c) AS companies, collect(c.name)[0..3] AS sample +``` + +Cross-organization paths through up to two co-authorship hops: + +```cypher +MATCH path = (o1:Organization)<-[:MEMBER_OF]-(:Author)-[:CO_AUTHOR*1..2]-(:Author)-[:MEMBER_OF]->(o2:Organization) +WHERE o1.name < o2.name RETURN o1.name, o2.name, count(path) +``` + +## Whole-university graph: `bulk_load.py` + +`load_graph.py` is the per-researcher example. `bulk_load.py` builds the graph for a whole +organization by scanning each Elasticsearch source once and streaming into FalkorDB: + +```bash +scripts/falkordb/run.sh bulk --graph ude --reset # full UDE cohort, all phases +scripts/falkordb/run.sh bulk --graph ude_test --reset --limit-authors 25 # smoke test, a few seconds +scripts/falkordb/run.sh bulk --graph ude --phases projects derive # re-run selected phases (idempotent) +``` + +Phases, in order (`--phases` selects a subset; later phases reload cohort and works from the graph): + +| Phase | Source | Adds | +| --- | --- | --- | +| `cohort` | active researchers via `build_institution_membership_query` (last known institution + affiliation in the last two years) | `Author` with extra label `Cohort`, `MEMBER_OF`, `AFFILIATED_WITH {years, last_known}`, `WORKS_ON`, `Institution` lineage as `PART_OF` | +| `works` | one `scan` of the works index for every work of every cohort researcher | `Work` (incl. `doi`, `is_oa`, `fwci`), every authorship as `AUTHORED`, co-author `Author`s, `AFFILIATED_WITH`, `HAS_TOPIC`, `Venue` + `PUBLISHED_IN`, `Funder` + `FUNDED_BY {awards}` | +| `institutions` | `openalex-institutions` index | names, countries and types for institutions that only appeared as lineage ancestors | +| `affiliations` | second, lighter scan of the works index | `AUTHORED.institution_ids` (institutions on that authorship) and `Work-[:INVOLVES {authors}]->Institution`, the per-work view that author-level `AFFILIATED_WITH` cannot give | +| `classifications` | `work-classifications` index (LLM) | `Work.primary_category`, `pasteur_quadrant`, `applied_orientation_score`, `classification_confidence` | +| `projects` | CORDIS publications and DFG project publications by DOI; CORDIS organisations and DFG institutes of the organization; DFG persons by ORCID; project details | `Project {source: cordis/dfg}`, `Work-[:OUTPUT_OF]->Project`, `Institution-[:PARTICIPATES_IN {role, ec_contribution}]->Project`, `Author-[:DFG_ROLE {role}]->Project`, `EuOrganization-[:PARTICIPATES_IN]->Project` (consortium partners) | +| `patents` | `org_patents` index (pre-matched by `index_org_patents.py`) | `Patent`, `Author-[:INVENTOR_OF {match_type}]->Patent`, `HAS_TOPIC` | +| `news` | `aktuell_postproc` author names matched exactly to cohort display names (the rule the news API uses), articles from `aktuell`, topics from `aktuell_openalex_topics` | `NewsArticle`, `MENTIONED_IN {ambiguous}`, `HAS_TOPIC {keyword}` | +| `companies` | `get_company_connections_by_author_id` per researcher, 8 in parallel | `Company`, `OFFICER_OF`; common-name matches are only counted on the Author (`hr_company_matches`, `hr_common_name_warning`) unless `--include-ambiguous-companies` | +| `hierarchy` | `get_topic_hierarchy()` | `Domain`, `Field`, `Subfield`, `IN_DOMAIN`, `IN_FIELD`, `IN_SUBFIELD` | +| `derive` | Cypher inside FalkorDB | `CO_AUTHOR {weight, first_year, last_year}`, `Author-[:FUNDED_BY {publications}]->Funder`, `Author-[:CONTRIBUTED_TO {works}]->Project` for cohort members | +| `profile` | aggregation over the cohort's works | `Institution-[:ACTIVE_IN {level, works, researchers}]->Topic/Subfield/Field/Domain`, the drawable research profile | + +Co-author policy: every authorship is an `AUTHORED` edge, including 5,000-author collaboration +papers. `CO_AUTHOR` pairs are derived for all author pairs on works with at most `--pair-cap` +authors (default 30) and, on larger works, only for pairs that involve a cohort member. All pairs +on the UDE cohort's works would be 2.9 billion edges; the anchored policy gives about 10 million. +Edges always point from the smaller to the larger author id, so treat them as undirected. + +Writes go through `GraphWriter`: rows are buffered per label / relationship type and flushed with +`UNWIND ... MERGE` in batches of 2,000, node buffers before edge buffers. Cohort profiles use +`SET`, co-author stubs use `ON CREATE SET`, so a researcher who is both keeps the full profile. +One failing phase is logged and the next phase still runs. The script ends with `BGSAVE`. + +### Result for Universität Duisburg-Essen (2026-09-15) + +Cohort of 6,176 active researchers, every work of every cohort member, no author cap. The load +ran in about 12 minutes of pipeline time (works scan 6.5 min, derive 100 s, everything else under +a minute each); FalkorDB holds it in 1.04 GB and the RDB snapshot is 264 MB. + +| Nodes | | Relationships | | +| --- | --- | --- | --- | +| Author | 693,487 (6,176 also `:Cohort`) | AUTHORED | 4,112,809 (2,376,034 with `institution_ids`) | +| Work | 204,110 | CO_AUTHOR | 3,782,011 | +| Institution | 26,246 | AFFILIATED_WITH / INVOLVES | 1,072,837 / 784,212 | +| Venue | 16,534 | HAS_TOPIC | 571,906 | +| Funder | 7,493 | FUNDED_BY (work + author level) | 229,219 | +| EuOrganization | 5,469 | PUBLISHED_IN | 173,495 | +| Topic | 4,516 | WORKS_ON | 27,255 | +| NewsArticle | 4,402 | PARTICIPATES_IN | 17,046 | +| Project | 3,664 | MENTIONED_IN | 11,251 | +| Company | 547 | PART_OF | 11,045 | +| Patent | 366 | OUTPUT_OF / CONTRIBUTED_TO | 8,292 / 6,723 | +| Subfield / Field / Domain | 252 / 26 / 4 | OFFICER_OF / DFG_ROLE / INVENTOR_OF | 700 / 548 / 367 | +| | | ACTIVE_IN (institution research profile) | 4,618 | + +Source coverage of the cohort: all 6,176 have works, 1,741 are linked to projects, 1,925 are +mentioned in news, 406 have unambiguous company links, 163 hold indexed patents, 164 were matched to +DFG persons through their ORCID. 187,000 works carry an LLM classification. + +Two server behaviours matter at this scale and are handled in the script: FalkorDB caps every +result set at `RESULTSET_SIZE` rows (10,000 in the default container), so whole-graph reads are +paged (`GraphWriter.ro_all`); and write queries ignore timeouts, which is why the co-author +derivation computes pairs in Python and bulk-creates edges instead of running +`MATCH ... MERGE` inside the graph (that took over a minute per 2,000 works). + + +## Caveats worth knowing + +- In the whole-university graph, common-name company matches are not written as edges by default + (406 researchers have unambiguous links, the rest only carry `hr_company_matches`). +- News and Handelsregister links are name matches, exactly as in the REST API. The `OFFICER_OF` + edge carries `common_name_warning`; a researcher named Thomas Kaiser gets 92 companies with the + flag set, Ahmet Karkar gets one without it. +- Patents are matched by inventor name with the institution guard from `patents.authors.logic`; + the backend logs `search_completeness=truncated_inconclusive` for common names. +- The project bridge is DOI based: a researcher is linked to every CORDIS/DFG project that lists one + of their publications, regardless of author position. +- OpenAlex profiles can be merged across institutions. The lineage filter above avoids most of + them for the automatic selection, `--author-id` takes whatever you give it. +- `Author.topics` in the mirror carry a `score` where OpenAlex has a `count`; the value is stored + as-is on `WORKS_ON`. + +## Running without Docker + +Create a Python 3.12 environment with the service dependencies (`pip install -e` is not set up, so +install `fastapi httpx pydantic pydantic-settings sqlmodel python-dotenv pyyaml pyjwt openai pandas +pypdf sentence-transformers torch` matching `pyproject.toml`) plus `falkordb`, then run +`python scripts/falkordb/load_graph.py` from `service/`. The script locates `src/main/inse` and its +`.env` relative to its own path. diff --git a/service/scripts/falkordb/bulk_load.py b/service/scripts/falkordb/bulk_load.py new file mode 100644 index 00000000..a74a7ba1 --- /dev/null +++ b/service/scripts/falkordb/bulk_load.py @@ -0,0 +1,1010 @@ +""" +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)) diff --git a/service/scripts/falkordb/load_graph.py b/service/scripts/falkordb/load_graph.py new file mode 100644 index 00000000..497524f8 --- /dev/null +++ b/service/scripts/falkordb/load_graph.py @@ -0,0 +1,636 @@ +""" +load_graph.py — Minimal FalkorDB example for the INSE backend. + +Builds a small knowledge graph around a couple of researchers from the predefined +("default") organizations in src/data/predefined_accounts.json, using only the +backend's existing data-source logic (everything reads the INSE Elasticsearch mirrors): + + OpenAlex authors, works, topics, institutions -> inse.authors.v2 / inse.works.v2 / inse.institutions.v2 + EPO + USPTO patents -> inse.patents.authors.logic + CORDIS (EU) + DFG projects, via publication DOIs -> inse.works.logic + inse.projects.* + Funders of the author's funded publications -> inse.funders.logic + News mentions (UDE "aktuell" + CC-News) -> inse.news.logic + Handelsregister company officer matches -> inse.company_connections.logic + +The collected nodes/edges are written to FalkorDB with batched UNWIND ... MERGE +queries, and CO_AUTHOR edges are then derived inside the graph with one Cypher query. + +Usage (see run.sh for running inside the service image): + python scripts/falkordb/load_graph.py # 2 researchers per default org + python scripts/falkordb/load_graph.py --organization "Duisburg" --per-org 3 + python scripts/falkordb/load_graph.py --author-id A5040796987 --author-id A5119657791 + python scripts/falkordb/load_graph.py --reset --dump /tmp/graph.json --skip news --skip companies + +FalkorDB connection: --falkordb-host/--falkordb-port/--falkordb-password or the +FALKORDB_HOST / FALKORDB_PORT / FALKORDB_PASSWORD environment variables. +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import os +import re +import sys +import time +from collections import Counter, defaultdict +from dataclasses import dataclass, field +from datetime import date, datetime +from pathlib import Path +from typing import Any + +# --- locate the backend package (works from the repo checkout and inside the service image) --- +_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) + +# inse.config reads the .env at import time, so these imports must come after load_dotenv. +from inse.authors.institution_membership_query import ( # noqa: E402 + build_institution_membership_query, + current_affiliation_year_cutoff, +) +from inse.authors.v2.service import get_author_by_id_strict_or_raise, search_authors # noqa: E402 +from inse.company_connections.logic import get_company_connections_by_author_id # noqa: E402 +from inse.funders.logic import get_funders_by_author_id # noqa: E402 +from inse.institutions.v2.service import get_institution_by_id # noqa: E402 +from inse.models.openalex.author import Author # noqa: E402 +from inse.news.logic import get_news_by_author # noqa: E402 +from inse.patents.authors.logic import get_patents_by_author_id # noqa: E402 +from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id # noqa: E402 +from inse.projects.projects_search_client import ( # noqa: E402 + get_cordis_eu_project_ids_by_dois, + get_dfg_project_by_id, + get_dfg_project_ids_by_dois, +) +from inse.works.logic import get_publication_dois_of_author # noqa: E402 +from inse.works.v2.service import get_author_works # noqa: E402 + +logger = logging.getLogger("falkordb.load_graph") + +OPENALEX_PREFIX = "https://openalex.org/" +PREDEFINED_ACCOUNTS = _src_main.parent / "data" / "predefined_accounts.json" +SOURCES = ("works", "projects", "patents", "funders", "news", "companies") +_IDENT = re.compile(r"^[A-Z][A-Za-z_]*$") + + +# --------------------------------------------------------------------------- helpers +def short_id(raw: str | None) -> str | None: + """'https://openalex.org/A123' -> 'A123' (OpenAlex ids are stored as URLs in ES).""" + if not raw: + return None + return raw.strip().removeprefix(OPENALEX_PREFIX) + + +def raw_doi(doi: str) -> str: + for prefix in ("https://doi.org/", "http://doi.org/", "http://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]) -> dict[str, Any]: + """FalkorDB properties must be scalars or lists of scalars; drop None/dicts.""" + cleaned: dict[str, Any] = {} + for key, value in props.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 + + +@dataclass +class GraphBatch: + """In-memory node/edge accumulator. First writer of a property wins, so seed + authors (hydrated first) keep their full profile when they reappear as co-authors.""" + + nodes: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict) + edges: dict[tuple[str, str, str, str, str], dict[str, Any]] = field(default_factory=dict) + + def node(self, label: str, node_id: str | None, **props: Any) -> None: + if not node_id: + return + props = clean_props(props) + existing = self.nodes.setdefault((label, node_id), {}) + for key, value in props.items(): + existing.setdefault(key, value) + + def edge(self, src_label: str, src: str | None, rel: str, dst_label: str, dst: str | None, **props: Any) -> None: + if not src or not dst: + return + props = clean_props(props) + existing = self.edges.setdefault((src_label, src, rel, dst_label, dst), {}) + for key, value in props.items(): + existing.setdefault(key, value) + + def has_node(self, label: str, node_id: str | None) -> bool: + return bool(node_id) and (label, node_id) in self.nodes + + def summary(self) -> tuple[Counter, Counter]: + return ( + Counter(label for label, _ in self.nodes), + Counter(rel for _, _, rel, _, _ in self.edges), + ) + + def to_json(self) -> dict[str, Any]: + return { + "nodes": [{"label": l, "id": i, "props": p} for (l, i), p in self.nodes.items()], + "edges": [ + {"src_label": sl, "src": s, "rel": r, "dst_label": dl, "dst": d, "props": p} + for (sl, s, r, dl, d), p in self.edges.items() + ], + } + + +def add_topic(batch: GraphBatch, topic: Any) -> str | None: + """Topic node from an OpenAlex WorkTopic-like object (works, authors, patents, news).""" + tid = short_id(getattr(topic, "id", None)) + if not tid: + return None + subfield = getattr(topic, "subfield", None) + field_ = getattr(topic, "var_field", None) or getattr(topic, "field", None) + domain = getattr(topic, "domain", None) + batch.node( + "Topic", + tid, + name=getattr(topic, "display_name", None), + subfield=getattr(subfield, "display_name", None), + field=getattr(field_, "display_name", None), + domain=getattr(domain, "display_name", None), + ) + return tid + + +# --------------------------------------------------------------------------- organizations +def load_default_organizations() -> list[dict[str, str]]: + """The predefined organizations seeded at startup (auth.service.create_predefined_accounts).""" + with open(PREDEFINED_ACCOUNTS, encoding="utf-8") as fh: + data = json.load(fh) + return [ + {"name": org["name"], "institution_id": org["openalex_institution_id"]} + for org in data.get("organizations", []) + if org.get("openalex_institution_id") + ] + + +def select_organizations(orgs: list[dict[str, str]], wanted: list[str]) -> list[dict[str, str]]: + if not wanted: + return orgs + selected = [] + for term in wanted: + term_l = term.lower() + matches = [o for o in orgs if term_l in o["name"].lower() or term_l == o["institution_id"].lower()] + if not matches: + raise SystemExit(f"No default organization matches {term!r}. Known: {[o['name'] for o in orgs]}") + selected.extend(m for m in matches if m not in selected) + return selected + + +async def ensure_organization_nodes(batch: GraphBatch, org: dict[str, str]) -> None: + """Organization (from predefined_accounts.json) + its OpenAlex institution.""" + if batch.has_node("Organization", org["name"]): + return + institution = await get_institution_by_id(org["institution_id"]) + batch.node("Organization", org["name"], name=org["name"], openalex_institution_id=org["institution_id"]) + batch.node( + "Institution", org["institution_id"], + name=getattr(institution, "display_name", None) or org["name"], + ror=getattr(institution, "ror", None), + country_code=getattr(institution, "country_code", None), + type=str(institution.type) if getattr(institution, "type", None) else None, + ) + batch.edge("Organization", org["name"], "REPRESENTS", "Institution", org["institution_id"]) + + +def organization_of(author: Author, orgs: list[dict[str, str]]) -> dict[str, str] | None: + """Default organization whose institution is among the author's last known institutions.""" + last_known = {short_id(i.id) for i in (author.last_known_institutions or []) if i.id} + return next((org for org in orgs if org["institution_id"] in last_known), None) + + +async def pick_seed_authors( + institution_id: str, per_org: int, min_works: int, max_works: int, require_orcid: bool +) -> list[Author]: + """Seed researchers of an institution. + + Reuses the backend's active-cohort membership query (last known institution plus an + affiliation since the current year minus two, the same rule the app uses for + "currently belongs to institution"), then narrows the candidates so the example graph + stays small and well disambiguated: + * works_count within [min_works, max_works] -> skips hyper-authorship profiles + * an ORCID (optional) -> better-disambiguated OpenAlex profiles + * every last-known institution inside the institution's OpenAlex lineage + -> drops merged profiles that also "currently" belong to unrelated institutions + """ + institution_url = f"{OPENALEX_PREFIX}{institution_id}" + filters: list[dict[str, Any]] = [ + build_institution_membership_query(institution_id, year_mode="from", year=current_affiliation_year_cutoff()), + {"range": {"works_count": {"gte": min_works, "lte": max_works}}}, + ] + if require_orcid: + filters.append({"exists": {"field": "orcid"}}) + page = await search_authors( + page=0, + size=max(20, per_org * 20), + query={"bool": {"filter": filters}}, + sort=[{"works_count": {"order": "desc"}}, {"cited_by_count": {"order": "desc"}}], + ) + + def within_lineage(author: Author) -> bool: + return all( + inst.id == institution_url or institution_url in (inst.lineage or []) + for inst in (author.last_known_institutions or []) + ) + + return [author for author in page.elements if within_lineage(author)][:per_org] + + +# --------------------------------------------------------------------------- collectors +def collect_author_profile(batch: GraphBatch, author: Author, org_name: str | None) -> str: + aid = short_id(author.id) + stats = author.summary_stats + batch.node( + "Author", + aid, + name=author.display_name, + orcid=author.orcid, + works_count=author.works_count, + cited_by_count=author.cited_by_count, + h_index=getattr(stats, "h_index", None), + i10_index=getattr(stats, "i10_index", None), + seed=True, + ) + if org_name: + batch.edge("Author", aid, "MEMBER_OF", "Organization", org_name) + + last_known = {short_id(i.id) for i in (author.last_known_institutions or []) if i.id} + for affiliation in author.affiliations or []: + inst = affiliation.institution + iid = short_id(inst.id) if inst else None + if not iid: + continue + batch.node("Institution", iid, name=inst.display_name, country_code=inst.country_code, type=inst.type, ror=inst.ror) + batch.edge( + "Author", aid, "AFFILIATED_WITH", "Institution", iid, + years=sorted(affiliation.years or []), + last_known=iid in last_known, + ) + for topic in author.topics or []: + tid = add_topic(batch, topic) + if tid: + batch.edge("Author", aid, "WORKS_ON", "Topic", tid, score=getattr(topic, "score", None)) + return aid + + +async def collect_works(batch: GraphBatch, aid: str, max_works: int, max_authors_per_work: int) -> int: + page = await get_author_works(aid, page=0, size=max_works) + for work in page.elements: + wid = short_id(work.id) + if not wid: + continue + authorships = work.authorships or [] + hyper = len(authorships) > max_authors_per_work + batch.node( + "Work", wid, + title=work.title or work.display_name, + year=work.publication_year, + type=work.type, + language=work.language, + cited_by_count=work.cited_by_count, + authors_count=len(authorships), + hyperauthorship=hyper, + ) + for topic in work.topics or []: + tid = add_topic(batch, topic) + if tid: + batch.edge("Work", wid, "HAS_TOPIC", "Topic", tid, score=topic.score) + for authorship in authorships: + author = authorship.author + cid = short_id(author.id) if author else None + if not cid or (hyper and cid != aid): + continue # for hyper-authorship works only keep the seed author's own edge + batch.node("Author", cid, name=author.display_name, orcid=author.orcid, seed=False) + batch.edge( + "Author", cid, "AUTHORED", "Work", wid, + position=authorship.author_position, + corresponding=authorship.is_corresponding, + ) + for inst in authorship.institutions or []: + iid = short_id(inst.id) + if iid: + batch.node("Institution", iid, name=inst.display_name, country_code=inst.country_code, type=inst.type) + batch.edge("Author", cid, "AFFILIATED_WITH", "Institution", iid) + return len(page.elements) + + +async def collect_projects(batch: GraphBatch, aid: str) -> int: + """Author -> project bridge used elsewhere in the backend: the author's publication DOIs + are looked up in the CORDIS publication index and in the DFG projects' publication lists.""" + dois = await get_publication_dois_of_author(aid) + if not dois: + return 0 + doi_variants = sorted({v for d in dois for v in (d, raw_doi(d), raw_doi(d).lower())}) + cordis_ids = await get_cordis_eu_project_ids_by_dois(dois) + dfg_ids = await get_dfg_project_ids_by_dois(doi_variants) + + for pid in cordis_ids: + node_id = f"cordis:{pid}" + details = await get_enriched_cordis_project_by_id(str(pid)) + batch.node( + "Project", node_id, + source="cordis", source_id=str(pid), + title=getattr(details, "title", None), + acronym=getattr(details, "acronym", None), + start=getattr(details, "start_date", None), + end=getattr(details, "end_date", None), + funding_scheme=getattr(details, "funding_scheme", None), + status=getattr(details, "status", None), + ec_max_contribution=getattr(details, "ec_max_contribution", None), + ) + batch.edge("Author", aid, "CONTRIBUTED_TO", "Project", node_id, via="publication_doi") + for pid in dfg_ids: + node_id = f"dfg:{pid}" + details = await get_dfg_project_by_id(str(pid)) + batch.node( + "Project", node_id, + source="dfg", source_id=str(pid), + title=getattr(details, "title_en", None) or getattr(details, "title_de", None), + start=getattr(details, "funding_start", None), + end=getattr(details, "funding_end", None), + funding_scheme=getattr(details, "funding_type_en", None) or getattr(details, "funding_type_de", None), + url=getattr(details, "page_url", None) or getattr(details, "link", None), + ) + batch.edge("Author", aid, "CONTRIBUTED_TO", "Project", node_id, via="publication_doi") + return len(cordis_ids) + len(dfg_ids) + + +async def collect_patents(batch: GraphBatch, aid: str) -> int: + response = await get_patents_by_author_id(aid) + for patent in response.patents: + pid = f"{patent.source}:{patent.patent_id}" + year = int(patent.publication_year) if patent.publication_year and patent.publication_year.isdigit() else None + batch.node( + "Patent", pid, + patent_id=patent.patent_id, source=patent.source, + title=patent.title or patent.title_en or patent.title_de, + year=year, publication_date=patent.publication_date, + kind=patent.kind, status=patent.status, country=patent.country, + ipc=patent.ipc, assignees=patent.assignees, inventors=patent.inventors, + ) + batch.edge("Author", aid, "INVENTOR_OF", "Patent", pid) + for tag in patent.openalex_topics: + tid = short_id(tag.topic_id) + if tid: + batch.node("Topic", tid, name=tag.topic_display_name, field=tag.field_name, domain=tag.domain_name) + batch.edge("Patent", pid, "HAS_TOPIC", "Topic", tid) + return response.patent_count + + +async def collect_funders(batch: GraphBatch, aid: str) -> int: + response = await get_funders_by_author_id(aid) + for funder in response.funders: + fid = short_id(funder.funder_id) or f"name:{funder.funder_name}" + batch.node("Funder", fid, name=funder.funder_name) + batch.edge("Author", aid, "FUNDED_BY", "Funder", fid, publications=funder.publication_count) + ids = funder.publication_ids + for wid_raw in ids.first + ids.middle + ids.last + ids.unknown: + wid = short_id(wid_raw) + if batch.has_node("Work", wid): # only link works we already loaded + batch.edge("Work", wid, "FUNDED_BY", "Funder", fid) + return response.funder_count + + +async def collect_news(batch: GraphBatch, aid: str, max_news: int) -> int: + page = await get_news_by_author(aid, page=1, page_size=max_news) + for article in page.results: + batch.node("NewsArticle", article.id, title=article.maintitle, date=article.date, url=article.url) + batch.edge("Author", aid, "MENTIONED_IN", "NewsArticle", article.id, matching="display_name") + for topic in article.topics or []: + tid = short_id(topic.id) + if tid: + batch.node("Topic", tid, name=topic.display_name, subfield=topic.subfield_name, field=topic.field_name, domain=topic.domain_name) + batch.edge("NewsArticle", article.id, "HAS_TOPIC", "Topic", tid) + return page.total + + +async def collect_companies(batch: GraphBatch, aid: str) -> int: + response = await get_company_connections_by_author_id(aid) + for company in response.connections: + cid = company.company_number or company.native_company_number or f"name:{company.company_name}" + batch.node( + "Company", cid, + name=company.company_name, status=company.company_status, + registered_office=company.registered_office, + register=" ".join(p for p in (company.register_art, company.register_nummer) if p) or None, + ) + batch.edge( + "Author", aid, "OFFICER_OF", "Company", cid, + positions=[o.position for o in company.matched_officers if o.position], + matching_method=response.matching_method, + common_name_warning=response.common_name_warning, + ) + return response.company_count + + +# --------------------------------------------------------------------------- FalkorDB sink +def _chunks(rows: list[dict[str, Any]], size: int): + for start in range(0, len(rows), size): + yield rows[start:start + size] + + +def write_to_falkordb(batch: GraphBatch, args: argparse.Namespace) -> None: + from falkordb import FalkorDB + from redis.exceptions import ResponseError + + db = FalkorDB(host=args.falkordb_host, port=args.falkordb_port, password=args.falkordb_password) + if args.reset and args.graph in db.list_graphs(): + db.select_graph(args.graph).delete() + logger.info("Deleted existing graph %r", args.graph) + graph = db.select_graph(args.graph) + + labels = sorted({label for label, _ in batch.nodes}) + for label in labels: + try: + graph.create_node_range_index(label, "id") + except ResponseError as exc: + if "already indexed" not in str(exc): + raise + + nodes_by_label: dict[str, list[dict[str, Any]]] = defaultdict(list) + for (label, node_id), props in batch.nodes.items(): + nodes_by_label[label].append({"id": node_id, "props": props}) + for label, rows in nodes_by_label.items(): + assert _IDENT.match(label), label + for chunk in _chunks(rows, args.batch_size): + graph.query(f"UNWIND $rows AS r MERGE (n:{label} {{id: r.id}}) SET n += r.props", {"rows": chunk}) + + edges_by_type: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list) + for (src_label, src, rel, dst_label, dst), props in batch.edges.items(): + edges_by_type[(src_label, rel, dst_label)].append({"src": src, "dst": dst, "props": props}) + for (src_label, rel, dst_label), rows in edges_by_type.items(): + assert _IDENT.match(src_label) and _IDENT.match(rel) and _IDENT.match(dst_label) + for chunk in _chunks(rows, args.batch_size): + graph.query( + f"UNWIND $rows AS r " + f"MATCH (a:{src_label} {{id: r.src}}), (b:{dst_label} {{id: r.dst}}) " + f"MERGE (a)-[e:{rel}]->(b) SET e += r.props", + {"rows": chunk}, + ) + + if not args.no_coauthor_edges: + # Derive co-authorship inside the graph instead of in Python (this is the part the + # in-service CollaborationGraph API currently leaves to the client). + result = graph.query( + "MATCH (a:Author)-[:AUTHORED]->(w:Work)<-[:AUTHORED]-(b:Author) " + "WHERE a.id < b.id " + "WITH a, b, count(DISTINCT w) AS n, min(w.year) AS first_year, max(w.year) AS last_year " + "MERGE (a)-[c:CO_AUTHOR]->(b) " + "SET c.weight = n, c.first_year = first_year, c.last_year = last_year" + ) + logger.info("CO_AUTHOR edges created: %d", int(result.relationships_created or 0)) + + stats = graph.ro_query( + "MATCH (n) WITH count(n) AS nodes MATCH ()-[r]->() RETURN nodes, count(r)" + ).result_set + logger.info("Graph %r now holds %s nodes and %s relationships", args.graph, *stats[0]) + + seeds = graph.ro_query( + "MATCH (s:Author {seed: true}) " + "OPTIONAL MATCH (s)-[c:CO_AUTHOR]-(o:Author) " + "WITH s, o, c ORDER BY c.weight DESC " + "WITH s, collect(o.name + ' (' + toString(c.weight) + ')')[0..3] AS top " + "RETURN s.id, s.name, top ORDER BY s.name" + ).result_set + for row in seeds: + logger.info(" %s %-32s strongest co-authors: %s", row[0], row[1], ", ".join(row[2]) or "-") + + +# --------------------------------------------------------------------------- main +async def run_source(name: str, coro, status: dict[str, str]) -> None: + started = time.perf_counter() + try: + count = await coro + status[name] = f"{count} ({(time.perf_counter() - started) * 1000:.0f}ms)" + except Exception as exc: # one failing source must not abort the whole load + logger.warning("source %-9s failed: %s: %s", name, type(exc).__name__, exc) + status[name] = "error" + + +async def main(args: argparse.Namespace) -> None: + batch = GraphBatch() + skipped = set(args.skip) + seeds: list[tuple[Author, str | None]] = [] + default_orgs = load_default_organizations() + + if args.author_id: + for raw in args.author_id: + author = await get_author_by_id_strict_or_raise(short_id(raw)) + org = organization_of(author, default_orgs) + if org: + await ensure_organization_nodes(batch, org) + seeds.append((author, org["name"] if org else None)) + else: + for org in select_organizations(default_orgs, args.organization): + await ensure_organization_nodes(batch, org) + authors = await pick_seed_authors( + org["institution_id"], args.per_org, args.min_works, args.max_works, args.require_orcid + ) + logger.info("%s (%s): %s", org["name"], org["institution_id"], ", ".join(f"{a.display_name} [{short_id(a.id)}]" for a in authors) or "no authors found") + seeds.extend((author, org["name"]) for author in authors) + + if not seeds: + raise SystemExit("No seed researchers selected.") + + seed_ids = [collect_author_profile(batch, author, org_name) for author, org_name in seeds] + + for (author, _), aid in zip(seeds, seed_ids): + logger.info("Collecting sources for %s [%s] ...", author.display_name, aid) + status: dict[str, str] = {} + if "works" not in skipped: + await run_source("works", collect_works(batch, aid, args.works, args.max_authors_per_work), status) + if "projects" not in skipped: + await run_source("projects", collect_projects(batch, aid), status) + if "patents" not in skipped: + await run_source("patents", collect_patents(batch, aid), status) + if "funders" not in skipped: + await run_source("funders", collect_funders(batch, aid), status) + if "news" not in skipped: + await run_source("news", collect_news(batch, aid, args.news), status) + if "companies" not in skipped: + await run_source("companies", collect_companies(batch, aid), status) + logger.info(" %s", " ".join(f"{k}={v}" for k, v in status.items())) + + node_counts, edge_counts = batch.summary() + logger.info("Collected nodes: %s", dict(node_counts)) + logger.info("Collected edges: %s", dict(edge_counts)) + + if args.dump: + Path(args.dump).write_text(json.dumps(batch.to_json(), ensure_ascii=False, indent=1), encoding="utf-8") + logger.info("Wrote %s", args.dump) + + if args.no_write: + return + write_to_falkordb(batch, args) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sel = parser.add_argument_group("researcher selection") + sel.add_argument("--organization", action="append", default=[], metavar="NAME_OR_ID", + help="restrict to default organization(s) by name substring or OpenAlex institution id (repeatable)") + sel.add_argument("--per-org", type=int, default=2, help="seed researchers per organization (default 2)") + sel.add_argument("--min-works", type=int, default=20, help="minimum works_count for seed selection") + sel.add_argument("--max-works", type=int, default=300, help="maximum works_count for seed selection (skips hyper-authorship profiles)") + sel.add_argument("--require-orcid", action=argparse.BooleanOptionalAction, default=True, + help="only seed researchers with an ORCID (default on)") + sel.add_argument("--author-id", action="append", default=[], metavar="OPENALEX_ID", + help="explicit seed researcher(s), e.g. A5040796987 (repeatable; overrides organization selection)") + src = parser.add_argument_group("sources") + src.add_argument("--works", type=int, default=40, help="max works per researcher (default 40)") + src.add_argument("--max-authors-per-work", type=int, default=30, help="skip co-author edges for works with more authors") + src.add_argument("--news", type=int, default=20, help="max news articles per researcher") + src.add_argument("--skip", action="append", default=[], choices=SOURCES, help="skip a source (repeatable)") + out = parser.add_argument_group("output") + out.add_argument("--falkordb-host", default=os.environ.get("FALKORDB_HOST", "localhost")) + out.add_argument("--falkordb-port", type=int, default=int(os.environ.get("FALKORDB_PORT", "6379"))) + out.add_argument("--falkordb-password", default=os.environ.get("FALKORDB_PASSWORD") or None) + out.add_argument("--graph", default=os.environ.get("FALKORDB_GRAPH", "inse"), help="graph name (default inse)") + out.add_argument("--reset", action="store_true", help="delete the graph before loading") + out.add_argument("--no-coauthor-edges", action="store_true", help="do not derive CO_AUTHOR edges") + out.add_argument("--batch-size", type=int, default=500) + out.add_argument("--dump", metavar="PATH", help="also write the collected nodes/edges as JSON") + out.add_argument("--no-write", action="store_true", help="collect only (useful with --dump), do not touch FalkorDB") + parser.add_argument("-v", "--verbose", action="store_true", help="show backend/httpx logs") + return parser.parse_args() + + +if __name__ == "__main__": + cli_args = parse_args() + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + if not cli_args.verbose: + # Some backend modules pin their own logger level, so filter at the handler instead. + for handler in logging.getLogger().handlers: + handler.addFilter(lambda record: record.levelno >= logging.WARNING or record.name.startswith("falkordb")) + asyncio.run(main(cli_args)) diff --git a/service/scripts/falkordb/requirements.txt b/service/scripts/falkordb/requirements.txt new file mode 100644 index 00000000..5001132d --- /dev/null +++ b/service/scripts/falkordb/requirements.txt @@ -0,0 +1,2 @@ +# Extra dependency for scripts/falkordb on top of the service image / pyproject. +falkordb~=1.7 diff --git a/service/scripts/falkordb/run.sh b/service/scripts/falkordb/run.sh new file mode 100755 index 00000000..c25288f5 --- /dev/null +++ b/service/scripts/falkordb/run.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Run load_graph.py inside the inse-service image, which already has every backend +# dependency (torch/sentence-transformers included), and talk to FalkorDB on the host. +# +# scripts/falkordb/run.sh # 2 researchers per default organization +# scripts/falkordb/run.sh --reset --organization Duisburg --per-org 3 +# scripts/falkordb/run.sh --author-id A5040796987 --author-id A5119657791 +# scripts/falkordb/run.sh bulk --graph ude --reset # whole-university graph (bulk_load.py) +# +# Env: INSE_IMAGE (default inse-service:1.0.0, built by ./gradlew :service:createImage), +# FALKORDB_HOST (default host.docker.internal), FALKORDB_PORT, FALKORDB_PASSWORD, FALKORDB_GRAPH. +set -euo pipefail + +SERVICE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +# First argument "bulk" selects the whole-university loader (bulk_load.py); otherwise load_graph.py runs. +SCRIPT="load_graph.py" +if [ "${1:-}" = "bulk" ]; then SCRIPT="bulk_load.py"; shift; fi +IMAGE="${INSE_IMAGE:-inse-service:1.0.0}" +TTY_FLAGS="" +if [ -t 0 ] && [ -t 1 ]; then TTY_FLAGS="-it"; fi +# Match the image's platform (the Gradle build targets amd64), avoiding Docker's mismatch warning on arm64 hosts. +PLATFORM="$(docker image inspect --format '{{.Os}}/{{.Architecture}}' "$IMAGE" 2>/dev/null || true)" +PLATFORM_FLAGS="" +if [ -n "$PLATFORM" ]; then PLATFORM_FLAGS="--platform $PLATFORM"; fi + +exec docker run --rm $TTY_FLAGS $PLATFORM_FLAGS \ + -v "$SERVICE_DIR/src/main:/home" \ + -v "$SERVICE_DIR/src/data:/data" \ + -v "$SERVICE_DIR/scripts:/scripts" \ + -w /home \ + --add-host host.docker.internal:host-gateway \ + -e FALKORDB_HOST="${FALKORDB_HOST:-host.docker.internal}" \ + -e FALKORDB_PORT="${FALKORDB_PORT:-6379}" \ + -e FALKORDB_PASSWORD="${FALKORDB_PASSWORD:-}" \ + -e FALKORDB_GRAPH="${FALKORDB_GRAPH:-inse}" \ + -e PRINT_ES_QUERIES=false -e PRINT_ES_TIMINGS=false \ + -e HF_HUB_DISABLE_PROGRESS_BARS=1 -e TQDM_DISABLE=1 \ + --entrypoint sh "$IMAGE" -c \ + 'pip install -q --root-user-action=ignore --disable-pip-version-check -r /scripts/falkordb/requirements.txt && exec python "/scripts/falkordb/$0" "$@"' \ + "$SCRIPT" "$@" diff --git a/service/scripts/profiling/multipliers/cache/authors_I62318514.jsonl.gz b/service/scripts/profiling/multipliers/cache/authors_I62318514.jsonl.gz new file mode 100644 index 00000000..12988d2d Binary files /dev/null and b/service/scripts/profiling/multipliers/cache/authors_I62318514.jsonl.gz differ diff --git a/service/scripts/profiling/multipliers/cache/build_summary_I62318514.json b/service/scripts/profiling/multipliers/cache/build_summary_I62318514.json new file mode 100644 index 00000000..dedac2cb --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/build_summary_I62318514.json @@ -0,0 +1,406 @@ +{ + "institution": "I62318514", + "cohort": [ + "I62318514", + "I4210119759", + "I4210161917", + "I127668822", + "I4210090139", + "I4210092428", + "I4210110714", + "I4210146441", + "I4210154243" + ], + "config_hash": "e56aa52d51c2", + "counts": { + "focal_authors_scored": 9474, + "nodes": 864646, + "edges": 5822006, + "works_used": 228103, + "works_capped": 9238, + "tags": { + "mentor": 161, + "bridger": 133, + "amplifier": 10 + }, + "suspicious_profiles": 400, + "es_docs_written": 9474, + "es_network_docs_written": 9474, + "founding": { + "in_population": 5712, + "timing_applicable": 6118, + "percentile_ge_90": 270, + "with_patents": 152 + } + }, + "timings": { + "extract_s": 0.4, + "load_cache_s": 33.3, + "founding_features_s": 2.6, + "build_graph_s": 74.6, + "metrics_s": 363.1, + "signals_s": 369.1, + "founding_s": 4.5, + "scoring_s": 0.1, + "index_s": 11.2, + "network_s": 93.6 + }, + "top_bridgers": [ + { + "author_id": "A5113304257", + "name": "Jan Egger", + "score": 0.9533, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5051904885", + "name": "Feyza Cansiz", + "score": 0.9436, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5015256836", + "name": "Giebel Bernd", + "score": 0.9403, + "bucket": "Early", + "active_years": 3, + "suspicious": false + }, + { + "author_id": "A5029568311", + "name": "S. Ugurel-Becker", + "score": 0.9395, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5039473892", + "name": "D. Schadendorf", + "score": 0.9329, + "bucket": "Early", + "active_years": 3, + "suspicious": false + }, + { + "author_id": "A5098748894", + "name": "Bahadır Eryılmaz", + "score": 0.927, + "bucket": "Early", + "active_years": 3, + "suspicious": false + }, + { + "author_id": "A5120610796", + "name": "Ulrich Sure", + "score": 0.9263, + "bucket": "Early", + "active_years": 2, + "suspicious": false + }, + { + "author_id": "A5007940140", + "name": "Amin Dada", + "score": 0.9262, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5101839832", + "name": "Mohammed-Ali Sheikh", + "score": 0.9243, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5074268016", + "name": "Anika Grüneboom", + "score": 0.922, + "bucket": "Emerging", + "active_years": 9, + "suspicious": false + } + ], + "top_mentors": [ + { + "author_id": "A5043495754", + "name": "Cornelius Deuschl", + "score": 0.9613, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5030635588", + "name": "Birte Möhlendick", + "score": 0.9582, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5029722705", + "name": "Freya Droege", + "score": 0.95, + "bucket": "Established", + "active_years": 14, + "suspicious": true + }, + { + "author_id": "A5062907808", + "name": "Wolfgang P. Fendler", + "score": 0.9437, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5048453026", + "name": "Alpaslan Tasdogan", + "score": 0.9436, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5063064952", + "name": "Nora Bruns", + "score": 0.9408, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5036496827", + "name": "Ramazan Jabbarli", + "score": 0.9336, + "bucket": "Established", + "active_years": 13, + "suspicious": false + }, + { + "author_id": "A5041276010", + "name": "Heiko Wende", + "score": 0.9291, + "bucket": "Senior", + "active_years": 31, + "suspicious": false + }, + { + "author_id": "A5110823011", + "name": "Dagmar Führer", + "score": 0.9285, + "bucket": "Senior", + "active_years": 32, + "suspicious": false + }, + { + "author_id": "A5047137012", + "name": "David Kersting", + "score": 0.9284, + "bucket": "Established", + "active_years": 12, + "suspicious": false + } + ], + "top_amplifiers": [ + { + "author_id": "A5007801159", + "name": "Jens Wiltfang", + "score": 0.9282, + "bucket": "Senior", + "active_years": 35, + "suspicious": false + }, + { + "author_id": "A5049577078", + "name": "Stefan Kleine", + "score": 0.9121, + "bucket": "Emerging", + "active_years": 6, + "suspicious": false + }, + { + "author_id": "A5055188384", + "name": "Benjamin Zingsem", + "score": 0.8991, + "bucket": "Established", + "active_years": 10, + "suspicious": false + }, + { + "author_id": "A5036507802", + "name": "Martin Schüler", + "score": 0.8934, + "bucket": "Senior", + "active_years": 47, + "suspicious": true + }, + { + "author_id": "A5123934012", + "name": "Karl Sebastian Lang", + "score": 0.8883, + "bucket": "Early", + "active_years": 1, + "suspicious": false + }, + { + "author_id": "A5016532166", + "name": "Adalbert Krawczyk", + "score": 0.8779, + "bucket": "Senior", + "active_years": 16, + "suspicious": false + }, + { + "author_id": "A5052587248", + "name": "Gabi Schierning", + "score": 0.8751, + "bucket": "Senior", + "active_years": 23, + "suspicious": false + }, + { + "author_id": "A5024191146", + "name": "Markus Kaiser", + "score": 0.868, + "bucket": "Senior", + "active_years": 30, + "suspicious": false + }, + { + "author_id": "A5044921528", + "name": "Annette Paschen", + "score": 0.862, + "bucket": "Senior", + "active_years": 29, + "suspicious": false + }, + { + "author_id": "A5107541231", + "name": "Raimund Erbel", + "score": 0.8519, + "bucket": "Senior", + "active_years": 52, + "suspicious": false + } + ], + "top_founder_potential": [ + { + "author_id": "A5039812973", + "name": "Hamza Kalisch", + "percentile": 99.9, + "probability_raw": 0.9974, + "p_within_3y_percentile": 99.6, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5084716913", + "name": "N Blase", + "percentile": 99.9, + "probability_raw": 0.9975, + "p_within_3y_percentile": 99.7, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5102237308", + "name": "Kelsey Hermann", + "percentile": 99.9, + "probability_raw": 0.9985, + "p_within_3y_percentile": 100.0, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5031388574", + "name": "HH-J Schmidt", + "percentile": 99.9, + "probability_raw": 0.9982, + "p_within_3y_percentile": 99.9, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5063433003", + "name": "H. H. Schmidt", + "percentile": 99.9, + "probability_raw": 0.9978, + "p_within_3y_percentile": 99.8, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5082880950", + "name": "Fabian Haut", + "percentile": 99.9, + "probability_raw": 0.9975, + "p_within_3y_percentile": 99.3, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5000155431", + "name": "K Herrmann", + "percentile": 99.9, + "probability_raw": 0.9978, + "p_within_3y_percentile": 99.9, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5069143867", + "name": "Michael Dominic Harr", + "percentile": 99.8, + "probability_raw": 0.9969, + "p_within_3y_percentile": 99.8, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5090109295", + "name": "Johannes Neuhaus", + "percentile": 99.8, + "probability_raw": 0.9965, + "p_within_3y_percentile": 99.9, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + }, + { + "author_id": "A5087082783", + "name": "Christopher J. Rastin", + "percentile": 99.8, + "probability_raw": 0.9965, + "p_within_3y_percentile": 99.5, + "publications": 4, + "patents": 0, + "bucket": "Early", + "tags": [] + } + ] +} \ No newline at end of file diff --git a/service/scripts/profiling/multipliers/cache/build_summary_I62318514.udeonly.json b/service/scripts/profiling/multipliers/cache/build_summary_I62318514.udeonly.json new file mode 100644 index 00000000..ef2c8928 --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/build_summary_I62318514.udeonly.json @@ -0,0 +1,269 @@ +{ + "institution": "I62318514", + "config_hash": "a49ddd388990", + "counts": { + "focal_authors_scored": 4921, + "nodes": 639544, + "edges": 4143499, + "works_used": 160396, + "works_capped": 4823, + "tags": { + "amplifier": 609, + "mentor": 91, + "bridger": 66 + }, + "suspicious_profiles": 225 + }, + "timings": { + "load_cache_s": 15.2, + "build_graph_s": 31.3, + "metrics_s": 112.2, + "scoring_s": 0.0 + }, + "top_bridgers": [ + { + "author_id": "A5113304257", + "name": "Jan Egger", + "score": 0.9488, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5015256836", + "name": "Giebel Bernd", + "score": 0.9379, + "bucket": "Early", + "active_years": 3, + "suspicious": false + }, + { + "author_id": "A5074268016", + "name": "Anika Grüneboom", + "score": 0.9277, + "bucket": "Emerging", + "active_years": 9, + "suspicious": false + }, + { + "author_id": "A5101839832", + "name": "Mohammed-Ali Sheikh", + "score": 0.9227, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5093725590", + "name": "Ahammed Suhail Odungat", + "score": 0.9178, + "bucket": "Early", + "active_years": 3, + "suspicious": false + }, + { + "author_id": "A5123321088", + "name": "Heiko Wende", + "score": 0.9166, + "bucket": "Early", + "active_years": 2, + "suspicious": false + }, + { + "author_id": "A5093128319", + "name": "Pascal Raszke", + "score": 0.9115, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5009410023", + "name": "Yossarian Liebsch", + "score": 0.9098, + "bucket": "Early", + "active_years": 4, + "suspicious": false + }, + { + "author_id": "A5038988072", + "name": "Ulrike Schara‐Schmidt", + "score": 0.9095, + "bucket": "Emerging", + "active_years": 6, + "suspicious": false + }, + { + "author_id": "A5092634227", + "name": "Abdelrahman Elwy", + "score": 0.9089, + "bucket": "Early", + "active_years": 4, + "suspicious": false + } + ], + "top_mentors": [ + { + "author_id": "A5043495754", + "name": "Cornelius Deuschl", + "score": 0.9533, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5063064952", + "name": "Nora Bruns", + "score": 0.9508, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5062907808", + "name": "Wolfgang P. Fendler", + "score": 0.9477, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5016126468", + "name": "Jassin Rashidi‐Alavijeh", + "score": 0.9338, + "bucket": "Established", + "active_years": 13, + "suspicious": false + }, + { + "author_id": "A5041276010", + "name": "Heiko Wende", + "score": 0.9314, + "bucket": "Senior", + "active_years": 31, + "suspicious": false + }, + { + "author_id": "A5036496827", + "name": "Ramazan Jabbarli", + "score": 0.9271, + "bucket": "Established", + "active_years": 13, + "suspicious": false + }, + { + "author_id": "A5090806187", + "name": "Ivana Kraiselburd", + "score": 0.9262, + "bucket": "Established", + "active_years": 12, + "suspicious": false + }, + { + "author_id": "A5030635588", + "name": "Birte Möhlendick", + "score": 0.9244, + "bucket": "Established", + "active_years": 14, + "suspicious": false + }, + { + "author_id": "A5052523213", + "name": "Ulrich Sure", + "score": 0.9229, + "bucket": "Senior", + "active_years": 32, + "suspicious": false + }, + { + "author_id": "A5016243200", + "name": "Ulf Dittmer", + "score": 0.9209, + "bucket": "Senior", + "active_years": 34, + "suspicious": false + } + ], + "top_amplifiers": [ + { + "author_id": "A5001941348", + "name": "Matthias Rinke", + "score": 1.0, + "bucket": "Senior", + "active_years": 25, + "suspicious": false + }, + { + "author_id": "A5026928109", + "name": "Nicole Stracke", + "score": 1.0, + "bucket": "Emerging", + "active_years": 6, + "suspicious": false + }, + { + "author_id": "A5072469617", + "name": "Stefan Esser", + "score": 1.0, + "bucket": "Established", + "active_years": 10, + "suspicious": false + }, + { + "author_id": "A5045156629", + "name": "Mirrasoul J. Mousavi", + "score": 0.9991, + "bucket": "Senior", + "active_years": 20, + "suspicious": false + }, + { + "author_id": "A5102956234", + "name": "Tanja Trarbach", + "score": 0.9988, + "bucket": "Emerging", + "active_years": 6, + "suspicious": false + }, + { + "author_id": "A5108819622", + "name": "Andreas Roos", + "score": 0.9982, + "bucket": "Senior", + "active_years": 15, + "suspicious": true + }, + { + "author_id": "A5060245622", + "name": "Heidi Wiehler", + "score": 0.9978, + "bucket": "Established", + "active_years": 12, + "suspicious": true + }, + { + "author_id": "A5005113935", + "name": "C. L. Munch", + "score": 0.9977, + "bucket": "Emerging", + "active_years": 7, + "suspicious": true + }, + { + "author_id": "A5014449031", + "name": "Boris S. Kerner", + "score": 0.9973, + "bucket": "Senior", + "active_years": 51, + "suspicious": false + }, + { + "author_id": "A5034381567", + "name": "Yannick Beckmann", + "score": 0.9965, + "bucket": "Emerging", + "active_years": 9, + "suspicious": false + } + ] +} diff --git a/service/scripts/profiling/multipliers/cache/m3_run.log b/service/scripts/profiling/multipliers/cache/m3_run.log new file mode 100644 index 00000000..5b609043 --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/m3_run.log @@ -0,0 +1,34 @@ +Cohort (9 institutions, affiliation years >= 2023): + I62318514 University of Duisburg-Essen + I4210119759 Essen University Hospital + I4210161917 West German Heart and Vascular Center Essen + I127668822 Erwin L. Hahn Institute for Magnetic Resonance Imaging + I4210090139 Rhein-Ruhr Institut für Sozialforschung und Politikberatung + I4210092428 Deutsches Textilforschungszentrum Nord-West + I4210110714 Institute for Advanced Study in the Humanities Essen + I4210146441 The Hydrogen and Fuel Cell Center + I4210154243 Institut für Energie- und Umwelttechnik +Reusing cached extract (use --force-extract to refresh). +Loaded 267467 works, 9475 focal authors (19.0s) +Graph: 864646 nodes, 5822006 edges, 228103 works used, 9238 capped, ref_year=2026 (46.6s) +Metrics for 9474 focal authors (326.0s) +Signals: patents scored for 55 authors (name-only evidence: 17), news mentions for 1369 (ambiguous names skipped: 839), CORDIS projects for 1342 +Signal joins done (522.1s) +Scores -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/scores_I62318514.jsonl.gz (0.1s) +Deleted 9474 existing docs for I62318514 +Indexed 9474 docs into multiplicators_v1 (count for I62318514: 9474) (46.8s) +{ + "focal_authors_scored": 9474, + "nodes": 864646, + "edges": 5822006, + "works_used": 228103, + "works_capped": 9238, + "tags": { + "mentor": 161, + "bridger": 133, + "amplifier": 10 + }, + "suspicious_profiles": 400, + "es_docs_written": 9474 +} +Summary -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/build_summary_I62318514.json diff --git a/service/scripts/profiling/multipliers/cache/m4_network_run.log b/service/scripts/profiling/multipliers/cache/m4_network_run.log new file mode 100644 index 00000000..8c4c6b78 --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/m4_network_run.log @@ -0,0 +1,37 @@ +Cohort (9 institutions, affiliation years >= 2023): + I62318514 University of Duisburg-Essen + I4210119759 Essen University Hospital + I4210161917 West German Heart and Vascular Center Essen + I127668822 Erwin L. Hahn Institute for Magnetic Resonance Imaging + I4210090139 Rhein-Ruhr Institut für Sozialforschung und Politikberatung + I4210092428 Deutsches Textilforschungszentrum Nord-West + I4210110714 Institute for Advanced Study in the Humanities Essen + I4210146441 The Hydrogen and Fuel Cell Center + I4210154243 Institut für Energie- und Umwelttechnik +Reusing cached extract (use --force-extract to refresh). +Loaded 267467 works, 9475 focal authors (18.8s) +Graph: 864646 nodes, 5822006 edges, 228103 works used, 9238 capped, ref_year=2026 (45.0s) +Metrics for 9474 focal authors (319.0s) +Signals: patents scored for 55 authors (name-only evidence: 17), news mentions for 1369 (ambiguous names skipped: 839), CORDIS projects for 1342 +Signal joins done (389.7s) +Scores -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/scores_I62318514.jsonl.gz (0.1s) +Deleted 9474 existing docs for I62318514 +Indexed 9474 docs into multiplicators_v1 (count for I62318514: 9474) (11.4s) +Deleted 0 existing docs for I62318514 +Indexed 9474 network docs into multiplicator_networks_v1 (92.7s) +{ + "focal_authors_scored": 9474, + "nodes": 864646, + "edges": 5822006, + "works_used": 228103, + "works_capped": 9238, + "tags": { + "mentor": 161, + "bridger": 133, + "amplifier": 10 + }, + "suspicious_profiles": 400, + "es_docs_written": 9474, + "es_network_docs_written": 9474 +} +Summary -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/build_summary_I62318514.json diff --git a/service/scripts/profiling/multipliers/cache/patents_named_I62318514.json.gz b/service/scripts/profiling/multipliers/cache/patents_named_I62318514.json.gz new file mode 100644 index 00000000..389d1b65 Binary files /dev/null and b/service/scripts/profiling/multipliers/cache/patents_named_I62318514.json.gz differ diff --git a/service/scripts/profiling/multipliers/cache/scores_I62318514.jsonl.gz b/service/scripts/profiling/multipliers/cache/scores_I62318514.jsonl.gz new file mode 100644 index 00000000..1d05fca3 Binary files /dev/null and b/service/scripts/profiling/multipliers/cache/scores_I62318514.jsonl.gz differ diff --git a/service/scripts/profiling/multipliers/cache/spike_report_I62318514.json b/service/scripts/profiling/multipliers/cache/spike_report_I62318514.json new file mode 100644 index 00000000..55bc5fa9 --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/spike_report_I62318514.json @@ -0,0 +1,99 @@ +{ + "institution": { + "id": "https://openalex.org/I62318514", + "short_id": "I62318514", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen" + }, + "cohort": [ + { + "id": "I62318514", + "display_name": "University of Duisburg-Essen" + }, + { + "id": "I4210119759", + "display_name": "Essen University Hospital" + }, + { + "id": "I4210161917", + "display_name": "West German Heart and Vascular Center Essen" + }, + { + "id": "I127668822", + "display_name": "Erwin L. Hahn Institute for Magnetic Resonance Imaging" + }, + { + "id": "I4210090139", + "display_name": "Rhein-Ruhr Institut für Sozialforschung und Politikberatung" + }, + { + "id": "I4210092428", + "display_name": "Deutsches Textilforschungszentrum Nord-West" + }, + { + "id": "I4210110714", + "display_name": "Institute for Advanced Study in the Humanities Essen" + }, + { + "id": "I4210146441", + "display_name": "The Hydrogen and Fuel Cell Center" + }, + { + "id": "I4210154243", + "display_name": "Institut für Energie- und Umwelttechnik" + } + ], + "reproduction": { + "author_count": 6583, + "work_count": 221603, + "group_breakdown": { + "backend_compatible": 6360, + "empty_last_known_recent": 223 + } + }, + "field_coverage": { + "authorships_total": 4365638, + "author_position_pct": 100.0, + "is_corresponding_pct": 100.0, + "institutions_total": 3934359, + "institution_type_pct": 99.9, + "company_institutions": 82976 + }, + "scale": { + "works": 221603, + "authors_per_work": { + "p50": 5, + "p90": 18, + "p99": 174, + "max": 4839 + }, + "hyperauthorship_works_gt_100": 3179, + "pair_instances_at_cap": { + "20": 4921446, + "50": 10209552, + "100": 17642513 + } + }, + "career_quality": { + "authors_with_works": 6583, + "suspicious_profile_count": 302, + "suspicious_profile_pct": 4.59, + "active_years": { + "p50": 4, + "p90": 24, + "max": 63, + "mean": 8.61 + } + }, + "signals": { + "org_patents_for_institution": 462, + "match_type_breakdown": { + "name": 339, + "both": 65, + "institution": 58 + } + }, + "permissions": { + "skipped": "pass --probe-writes to test index create/bulk/delete" + } +} diff --git a/service/scripts/profiling/multipliers/cache/spike_report_I62318514.udeonly.json b/service/scripts/profiling/multipliers/cache/spike_report_I62318514.udeonly.json new file mode 100644 index 00000000..0293d445 --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/spike_report_I62318514.udeonly.json @@ -0,0 +1,61 @@ +{ + "institution": { + "id": "https://openalex.org/I62318514", + "short_id": "I62318514", + "ror": "https://ror.org/04mz5ra38", + "display_name": "University of Duisburg-Essen" + }, + "reproduction": { + "author_count": 4921, + "work_count": 183661, + "group_breakdown": { + "backend_compatible": 4740, + "empty_last_known_recent": 181 + } + }, + "field_coverage": { + "authorships_total": 3805507, + "author_position_pct": 100.0, + "is_corresponding_pct": 100.0, + "institutions_total": 3482939, + "institution_type_pct": 99.91, + "company_institutions": 67131 + }, + "scale": { + "works": 183661, + "authors_per_work": { + "p50": 5, + "p90": 17, + "p99": 144, + "max": 4839 + }, + "hyperauthorship_works_gt_100": 2459, + "pair_instances_at_cap": { + "20": 3912695, + "50": 7962611, + "100": 13897380 + } + }, + "career_quality": { + "authors_with_works": 4921, + "suspicious_profile_count": 225, + "suspicious_profile_pct": 4.57, + "active_years": { + "p50": 4, + "p90": 25, + "max": 60, + "mean": 8.94 + } + }, + "signals": { + "org_patents_for_institution": 436, + "match_type_breakdown": { + "name": 313, + "both": 65, + "institution": 58 + } + }, + "permissions": { + "create_index": 403 + } +} diff --git a/service/scripts/profiling/multipliers/cache/validate_m3.log b/service/scripts/profiling/multipliers/cache/validate_m3.log new file mode 100644 index 00000000..9fa9ade6 --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/validate_m3.log @@ -0,0 +1,79 @@ +Sample: 60 people, matched in scores: 51, missing: 9 + MISSING: Peter Bayer (A5060566345) + MISSING: Richard Kosinski (A5014403509) + MISSING: Alexandra Dmitrienko (A5042835341) + MISSING: Wilhelm Koop (A5019228221) + MISSING: Venkata Marella (A5082156768) + MISSING: Miriam Böhm (A5037448457) + MISSING: Katrin Schuldt (A5002003996) + MISSING: Friedrich Scheller (A5072565080) + MISSING: Lara Altenstädter (A5070117981) + +=== mentor sub-score by known status === + Professor n=29 median=0.740 mean=0.691 range=[0.153, 0.921] + Researcher n=22 median=0.494 mean=0.514 range=[0.242, 0.958] + +=== bridger sub-score by known status === + Professor n=29 median=0.629 mean=0.618 range=[0.291, 0.856] + Researcher n=22 median=0.469 mean=0.509 range=[0.224, 0.796] + +=== amplifier sub-score by known status === + Professor n=29 median=0.612 mean=0.584 range=[0.357, 0.840] + Researcher n=22 median=0.450 mean=0.529 range=[0.363, 0.772] + +M1 exit check — professors' median mentor score (0.74) > researchers' (0.494): PASS + +=== per-person (sorted by mentor score) === + 0.958 Researcher Established juniors= 30 laj= 6 Birte Möhlendick (Medicine) + 0.921 Professor Senior juniors=110 laj= 11 Oliver Witzke (Medicine) + 0.908 Professor Senior juniors= 56 laj= 12 Daniel Hoffmann (Biology) + 0.903 Professor Senior juniors= 92 laj= 7 Matthias Gunzer (Medicine) + 0.898 Professor Senior juniors= 41 laj= 16 Gerd Bacher (Engineering) + 0.891 Professor Senior juniors= 48 laj= 23 Ulrike Bingel (Medicine) + 0.888 Professor Senior juniors= 70 laj= 27 Bernd Sures (Biology) + 0.879 Professor Senior juniors=116 laj= 6 Boris Hadaschik (Medicine) + 0.862 Professor Senior juniors=128 laj= 2 Stephan Lang (Medicine) + 0.848 Professor Senior juniors= 40 laj= 25 Daniel Hering (Biology) + 0.833 Professor Senior juniors= 28 laj= 31 Stefan Schneegaß (Computer Science) + 0.786 Professor Senior juniors= 19 laj= 27 Torben Weis (Computer Science) + 0.781 Professor Senior juniors= 18 laj= 23 Pedro José Marrón (Computer Science) + 0.777 Professor Senior juniors= 29 laj= 4 Corina Andronescu (Engineering) + 0.762 Professor Senior juniors= 14 laj= 7 Barbara Saccà (Biology) + 0.740 Professor Senior juniors= 8 laj= 15 Lucas Davi (Computer Science) + 0.735 Professor Senior juniors= 13 laj= 24 Burak Atakan (Engineering) + 0.723 Researcher Senior juniors= 67 laj= 0 Farnusch Kaschani (Biology) + 0.722 Professor Senior juniors= 12 laj= 11 Barbara König (Computer Science) + 0.712 Professor Senior juniors= 12 laj= 21 Gregor Schiele (Computer Science) + 0.707 Professor Senior juniors= 10 laj= 11 Volker Gruhn (Computer Science) + 0.679 Researcher Senior juniors= 16 laj= 1 Marcus Handte (Computer Science) + 0.659 Professor Senior juniors= 45 laj= 0 Hartmut Schmidt (Medicine) + 0.654 Researcher Senior juniors= 22 laj= 0 Daniel Grabner (Biology) + 0.612 Professor Senior juniors= 13 laj= 0 Tienush Rassaf (Medicine) + 0.605 Professor Senior juniors= 6 laj= 8 Jens Krüger (Computer Science) + 0.601 Professor Senior juniors= 9 laj= 3 Andreas Metzger (Computer Science) + 0.513 Professor Senior juniors= 4 laj= 5 Andreas Vogelsang (Computer Science) + 0.500 Professor Senior juniors= 3 laj= 2 Frank Kleemann (Sociology) + 0.494 Researcher Early juniors= 0 laj= 0 Bianca Kamba (Biology) + 0.494 Researcher Early juniors= 0 laj= 0 Carina Liebers (Computer Science) + 0.494 Researcher Early juniors= 0 laj= 0 Jonas Keppel (Computer Science) + 0.494 Researcher Early juniors= 0 laj= 0 Carlos Medina Sánchez (Computer Science) + 0.494 Researcher Early juniors= 0 laj= 0 Christian Scholz (Computer Science) + 0.494 Researcher Early juniors= 0 laj= 0 Tobias Mikolas (Engineering) + 0.494 Researcher Early juniors= 0 laj= 0 Julia Schwichtenberg (Medicine) + 0.494 Researcher Early juniors= 0 laj= 0 Antonia Görtz (Sociology) + 0.494 Researcher Early juniors= 0 laj= 0 Lisa Mansfeld (Sociology) + 0.488 Researcher Emerging juniors= 0 laj= 0 Simon Janzon (Computer Science) + 0.488 Researcher Emerging juniors= 0 laj= 0 Christian Niesler (Computer Science) + 0.488 Researcher Emerging juniors= 0 laj= 0 Pascal Winkler (Computer Science) + 0.488 Researcher Emerging juniors= 0 laj= 0 Soheil Salighe (Engineering) + 0.488 Researcher Emerging juniors= 0 laj= 0 Sabrina Guckenbiehl (Medicine) + 0.488 Researcher Emerging juniors= 0 laj= 0 Zülal Cibir (Medicine) + 0.418 Researcher Senior juniors= 6 laj= 0 Stefan Hanenberg (Computer Science) + 0.377 Professor Senior juniors= 2 laj= 0 Ute Klammer (Sociology) + 0.251 Researcher Senior juniors= 1 laj= 0 Kathrin Januschke (Biology) + 0.242 Researcher Established juniors= 0 laj= 0 Andreas Jansen (Sociology) + 0.240 Professor Senior juniors= 1 laj= 0 Helen Baykara-Krumme (Sociology) + 0.227 Professor Senior juniors= 1 laj= 0 Marcel Erlinghagen (Sociology) + 0.153 Professor Senior juniors= 0 laj= 0 Gregor Bongaerts (Sociology) + +Report -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/validation_I62318514.json diff --git a/service/scripts/profiling/multipliers/cache/validation_I62318514.json b/service/scripts/profiling/multipliers/cache/validation_I62318514.json new file mode 100644 index 00000000..094b3f3b --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/validation_I62318514.json @@ -0,0 +1,62 @@ +{ + "missing": [ + "Peter Bayer (A5060566345)", + "Richard Kosinski (A5014403509)", + "Alexandra Dmitrienko (A5042835341)", + "Wilhelm Koop (A5019228221)", + "Venkata Marella (A5082156768)", + "Miriam Böhm (A5037448457)", + "Katrin Schuldt (A5002003996)", + "Friedrich Scheller (A5072565080)", + "Lara Altenstädter (A5070117981)" + ], + "by_status": { + "Professor": { + "mentor": { + "n": 29, + "median": 0.74, + "mean": 0.691, + "min": 0.153, + "max": 0.921 + }, + "bridger": { + "n": 29, + "median": 0.629, + "mean": 0.618, + "min": 0.291, + "max": 0.856 + }, + "amplifier": { + "n": 29, + "median": 0.612, + "mean": 0.584, + "min": 0.357, + "max": 0.84 + } + }, + "Researcher": { + "mentor": { + "n": 22, + "median": 0.494, + "mean": 0.514, + "min": 0.242, + "max": 0.958 + }, + "bridger": { + "n": 22, + "median": 0.469, + "mean": 0.509, + "min": 0.224, + "max": 0.796 + }, + "amplifier": { + "n": 22, + "median": 0.45, + "mean": 0.529, + "min": 0.363, + "max": 0.772 + } + } + }, + "m1_exit_mentor_check": "PASS" +} \ No newline at end of file diff --git a/service/scripts/profiling/multipliers/cache/validation_I62318514.udeonly.json b/service/scripts/profiling/multipliers/cache/validation_I62318514.udeonly.json new file mode 100644 index 00000000..5582a159 --- /dev/null +++ b/service/scripts/profiling/multipliers/cache/validation_I62318514.udeonly.json @@ -0,0 +1,70 @@ +{ + "missing": [ + "Barbara Saccà (A5075803366)", + "Peter Bayer (A5060566345)", + "Richard Kosinski (A5014403509)", + "Alexandra Dmitrienko (A5042835341)", + "Christian Niesler (A5069184110)", + "Pascal Winkler (A5081189339)", + "Wilhelm Koop (A5019228221)", + "Venkata Marella (A5082156768)", + "Miriam Böhm (A5037448457)", + "Soheil Salighe (A5041884757)", + "Tobias Mikolas (A5002909977)", + "Oliver Witzke (A5087456839)", + "Ulrike Bingel (A5002281474)", + "Katrin Schuldt (A5002003996)", + "Helen Baykara-Krumme (A5010111732)", + "Friedrich Scheller (A5072565080)", + "Lara Altenstädter (A5070117981)" + ], + "by_status": { + "Professor": { + "mentor": { + "n": 25, + "median": 0.715, + "mean": 0.663, + "min": 0.153, + "max": 0.921 + }, + "bridger": { + "n": 25, + "median": 0.603, + "mean": 0.598, + "min": 0.229, + "max": 0.849 + }, + "amplifier": { + "n": 25, + "median": 0.655, + "mean": 0.604, + "min": 0.173, + "max": 0.957 + } + }, + "Researcher": { + "mentor": { + "n": 18, + "median": 0.493, + "mean": 0.503, + "min": 0.153, + "max": 0.924 + }, + "bridger": { + "n": 18, + "median": 0.508, + "mean": 0.521, + "min": 0.181, + "max": 0.804 + }, + "amplifier": { + "n": 18, + "median": 0.413, + "mean": 0.543, + "min": 0.161, + "max": 0.971 + } + } + }, + "m1_exit_mentor_check": "PASS" +} diff --git a/service/scripts/profiling/multipliers/cache/works_I62318514.jsonl.gz b/service/scripts/profiling/multipliers/cache/works_I62318514.jsonl.gz new file mode 100644 index 00000000..58f87b5b Binary files /dev/null and b/service/scripts/profiling/multipliers/cache/works_I62318514.jsonl.gz differ diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index a49ebae6..eee7e1d6 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -1,5 +1,5 @@ LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/ -LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212 +LLM_API_KEY=5fc19eb764207e7bec592b3f415ecce650c16ec64344a4db92f74c19ef581154 LLM_MODEL=gemma4-e4b # Patent search (EPO + USPTO) @@ -7,10 +7,10 @@ PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic -ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ +ELASTICSEARCH_API_KEY=SVZLSzhhQUIyOHNDLXhyNmh3M3g6R3dlTVlnaTBHM1dnbW1sX0JMQmludw== ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic -ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +ELASTICSEARCH_INSE_API_KEY=Yl9pSjhhQUJPZ3FnTGZCZVljMEI6Q2N5NDlGX3AzdkNTOHo4c1lfT25QZw== # Debugging: Log every outgoing Elasticsearch query (index + payload) PRINT_ES_QUERIES=false