alterlab-primekg

$npx mdskill add AlterLab-IEU/AlterLab-Academic-Skills/alterlab-primekg

Queries PrimeKG for multiscale biomedical relationships across genes, drugs, diseases.

  • Explores drug-disease or gene-disease links for drug repurposing and precision medicine.
  • Depends on local PrimeKG kg.csv file and Python with pandas.
  • Uses graph traversal to find neighbors, paths, and disease context.
  • Returns structured data via script output for agent consumption.

SKILL.md

.github/skills/alterlab-primekgView on GitHub ↗
---
name: alterlab-primekg
description: Queries the Precision Medicine Knowledge Graph (PrimeKG) for multiscale biomedical relationships across genes, drugs, diseases, phenotypes, pathways, and biological processes. Use when exploring drug-disease or gene-disease links, building disease-centric knowledge subgraphs, or sourcing relations for drug repurposing and precision-medicine analyses. Part of the AlterLab Academic Skills suite.
license: MIT
allowed-tools: Read Write Edit Bash(python:*) Bash(uv:*)
compatibility: "Runs under `uv run python` with pandas installed and the PrimeKG `kg.csv` available locally (set `PRIMEKG_DATA_PATH`); no API key or account required."
metadata:
    skill-author: AlterLab
    version: "1.0.0"
---

# PrimeKG Knowledge Graph Skill

## Overview

PrimeKG (Chandak, Huang & Zitnik, *Scientific Data* 2023; mims-harvard/PrimeKG) is a precision medicine knowledge graph integrating 20 primary resources. It contains 129,375 nodes and 4,050,249 edges across 30 edge types and 10 node types, including drug-target, disease-gene, and disease-phenotype associations.

**Key capabilities:**
- Search for nodes (genes, proteins, drugs, diseases, phenotypes)
- Retrieve direct neighbors (associated entities and clinical evidence)
- Analyze local disease context (related genes, drugs, phenotypes)
- Identify drug-disease paths (potential repurposing opportunities)

**Data access:** Programmatic access via `scripts/query_primekg.py`. Point the loader at the `kg.csv` released on Harvard Dataverse via the `PRIMEKG_DATA_PATH` environment variable (it defaults to `../data/kg.csv` relative to the script). All functions operate on the `x_*`/`y_*`/`relation`/`display_relation` columns of `kg.csv`.

## When to Use This Skill

This skill should be used when:

- **Knowledge-based drug discovery:** Identifying targets and mechanisms for diseases.
- **Drug repurposing:** Finding existing drugs that might have evidence for new indications.
- **Phenotype analysis:** Understanding how symptoms/phenotypes relate to diseases and genes.
- **Multiscale biology:** Bridging the gap between molecular targets (genes) and clinical outcomes (diseases).
- **Network pharmacology:** Investigating the broader network effects of drug-target interactions.

## Core Workflow

Run under `uv run python` from the skill directory (so `scripts/` is importable),
or add the `scripts/` dir to `sys.path`. Set `PRIMEKG_DATA_PATH` to your `kg.csv`.

### 1. Search for Entities

Find identifiers for genes, drugs, or diseases. Pass `node_type` using PrimeKG's
exact type strings (see node types below) — e.g. `"gene/protein"`, not `"gene"`.

```python
from scripts.query_primekg import search_nodes

# Search for Alzheimer's disease nodes
results = search_nodes("Alzheimer", node_type="disease")
# Returns: [{"id": <MONDO id>, "type": "disease", "name": "...",
#            "source": "MONDO" | "MONDO_grouped"}, ...]
# Disease ids are MONDO ids; PrimeKG groups diseases, so one name can map to
# several MONDO ids. Use the returned id with get_neighbors.
```

### 2. Get Neighbors (Direct Associations)

Retrieve all connected nodes and relationship types.

```python
from scripts.query_primekg import get_neighbors

# Get all neighbors of a specific disease ID (the MONDO id from search_nodes)
neighbors = get_neighbors(disease_id, relation_type="disease_protein")
# Returns: List of neighbors like
#   {"neighbor_name": "APOE", "neighbor_type": "gene/protein",
#    "relation": "disease_protein", "display_relation": "associated with", ...}
```

### 3. Analyze Disease Context

A high-level function to summarize associations for a disease.

```python
from scripts.query_primekg import get_disease_context

# Comprehensive summary for a disease
context = get_disease_context("Alzheimer")
# Access: context['associated_genes'], context['associated_drugs'],
#         context['phenotypes'], context['related_diseases']
```

### 4. Trace Drug-Disease Paths (Repurposing)

Find depth-2 paths (drug -> shared gene/protein target -> disease) as graph-based
repurposing evidence.

```python
from scripts.query_primekg import find_paths

# drug_id and disease_id come from search_nodes
paths = find_paths(drug_id, disease_id, max_depth=2)
# Each path is a list of edge dicts; a drug -> gene/protein -> disease path is a
# candidate new-indication hypothesis. For deeper traversal, load kg.csv into networkx.
```

## Node and Relation Types in PrimeKG

These are the exact strings used in `kg.csv` — match them verbatim when filtering.

**Node types** (`x_type`/`y_type`, 10 total): `gene/protein`, `drug`, `disease`,
`effect/phenotype`, `biological_process`, `molecular_function`, `cellular_component`,
`pathway`, `anatomy`, `exposure`. Note: genes use `gene/protein` (not `gene`) and
phenotypes use `effect/phenotype` (not `phenotype`).

**Key relations** (`relation`, 30 total). Edges are undirected; check both endpoints.
- `protein_protein`: physical PPIs
- `drug_protein`: drug target/mechanism associations
- `disease_protein`: disease-gene/protein associations (there is no `disease_gene`)
- `indication`, `contraindication`, `off-label use`: the three drug-disease relations
  (there is no single `drug_disease`)
- `disease_phenotype_positive` / `disease_phenotype_negative`: phenotype present/absent
- `bioprocess_protein`, `pathway_protein`, `molfunc_protein`, `cellcomp_protein`: GO /
  pathway annotations
- `anatomy_protein_present` / `anatomy_protein_absent`, `exposure_*`: anatomy/exposure links

## Best Practices

1. **Use specific IDs:** When using `get_neighbors`, ensure you have the correct ID from `search_nodes` (disease IDs are MONDO ids).
2. **Context first:** Use `get_disease_context` for a broad overview before diving into specific genes or drugs.
3. **Filter relationships:** Use the `relation_type` filter in `get_neighbors` to focus on specific evidence (e.g., only `drug_protein`, or `indication` for treatment links). Use exact relation strings from the list above.
4. **Mind disease grouping:** PrimeKG collapses ~22k MONDO concepts into ~17k grouped disease nodes, so one disease name may resolve to multiple MONDO ids that share a `node_index`.

## Resources

### Scripts
- `scripts/query_primekg.py`: Core functions — `search_nodes`, `get_neighbors`, `find_paths`, `get_disease_context`.

### Data Path
- Data: `kg.csv` (set `PRIMEKG_DATA_PATH`; default `../data/kg.csv`), from Harvard Dataverse (mims-harvard/PrimeKG).
- 129,375 nodes, 4,050,249 edges; 10 node types, 30 edge types.
- Loaded with pandas (`pd.read_csv`, `low_memory=True`). kg.csv is ~3 GB+ uncompressed — each function reloads it; for repeated queries, cache the DataFrame or use a real graph store.

More from AlterLab-IEU/AlterLab-Academic-Skills

SkillDescription
alterlab-abm-mesaBuilds agent-based models of social systems with Mesa 3 — the current AgentSet API (model.agents.shuffle_do('step'), auto-assigned unique_id, mandatory super().__init__(seed=...)), cell spaces (mesa.discrete_space OrthogonalMooreGrid / classic mesa.space grids), the DataCollector, batch_run parameter sweeps, and SolaraViz — for emergence, segregation, diffusion, opinion dynamics, and cooperation models. It uses the Mesa 3.x API (the old mesa.time schedulers like RandomActivation are removed) and treats the model as a generative theory to be validated, not just run. Use when the request mentions an agent-based model, Mesa, simulating interacting agents, or emergent macro behavior from micro rules. For discrete-event (queueing/process) simulation prefer alterlab-simpy; for reinforcement learning prefer alterlab-stable-baselines3. Part of the AlterLab Academic Skills suite.
alterlab-academic-careerPrepares academic career documents and professional-development materials for faculty and researchers. Use when drafting academic CVs, research statements, teaching philosophies, diversity statements, faculty-position cover letters, tenure dossiers, promotion narratives, academic portfolios, or mentorship statements, and when planning conference-networking strategy, building academic web presence, setting up ORCID profiles, or understanding impact metrics. Part of the AlterLab Academic Skills suite.
alterlab-accreditation-aolScaffolds program-level Assurance-of-Learning (AoL) documentation for AACSB (2020 Standard 5) and ABET (Criterion 3 Student Outcomes, Criterion 4 Continuous Improvement) accreditation — program learning outcomes / competency goals, curriculum-to-outcome mapping matrices, direct- and indirect-assessment plans, rubric design, and closing-the-loop continuous-improvement narratives — and validates the structure of an outcome-mapping matrix with scripts/aol_matrix.py. Use when the user needs AACSB or ABET assurance-of-learning material, a program-learning-outcomes set, a curriculum/outcome map or coverage matrix, a direct/indirect assessment plan, a closing-the-loop report, or accreditation self-study text. For single-course design or course rubrics prefer alterlab-teaching-design; for post-award grant reports prefer alterlab-grant-reporting. Part of the AlterLab Academic Skills suite.
alterlab-adaptyvSubmits and tracks protein-testing experiments on the Adaptyv Bio Foundry cloud lab (wet-lab validation), and optimizes protein sequences before submission with computational tools (NetSolP, SoluProt, SolubleMPNN, ESM). Use when designing proteins that need wet-lab validation - binding/affinity screening, expression testing, thermostability, or fluorescence assays - or when submitting experiments to the Foundry API, browsing the target catalog, tracking experiment status, retrieving results, or pre-screening sequences for solubility/expression. Triggers on "Adaptyv", "Foundry API", "cloud lab", "biolayer interferometry / BLI", "wet-lab validation". Part of the AlterLab Academic Skills suite.
alterlab-aeonRuns time series machine learning with the aeon library — classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search via scikit-learn compatible APIs. Use when working with temporal data, sequential patterns, or time-indexed observations (univariate or multivariate) that need specialized algorithms beyond standard ML approaches. Part of the AlterLab Academic Skills suite.
alterlab-akademik-tesvikComputes the annual Turkish academic-incentive (akademik teşvik) score for Devlet (state) university öğretim elemanı (academic staff) from a classified activity list, applying the verified Akademik Teşvik Ödeneği Yönetmeliği (2018/11834) Faaliyet Hesaplama Tablosu headline puanları (Proje 20, Araştırma 15, Yayın 30, Patent 30, Atıf 30, Tebliğ 20, Ödül 20) with the k (author-count), p (Q1 1/Q2 0.8/Q3 0.5/Q4 0.25), and r (project-role) coefficients via türü puanı = Σ(faaliyet oranları) × headline (MADDE 8/2), then enforcing the per-type headline ceilings, the 100 cap (MADDE 8/3), and the net-30 payment gate (MADDE 10/3) in a deterministic scripts/tesvik_score.py. Use when the user wants to calculate akademik teşvik puanı, check the en az 30 (net-30) threshold, apply TABLO 4 ceilings, or estimate teşvik eligibility; keeps its coefficients separate from doçentlik scoring. For doçentlik point eligibility prefer alterlab-docentlik-eligibility. Part of the AlterLab Academic Skills suite.
alterlab-alpha-vantageAccesses real-time and historical stock market data, forex rates, cryptocurrency prices, commodities, economic indicators, and 50+ technical indicators via the Alpha Vantage API (requires a free API key from alphavantage.co). Use when fetching stock prices (OHLCV), company fundamentals (income statement, balance sheet, cash flow), earnings, options data, market news/sentiment, insider transactions, GDP, CPI, treasury yields, gold/silver/oil prices, Bitcoin/crypto prices, forex exchange rates, or calculating technical indicators (SMA, EMA, MACD, RSI, Bollinger Bands). Part of the AlterLab Academic Skills suite.
alterlab-alphafoldPredict protein 3D structures with AlphaFold2 via ColabFold — MMseqs2-accelerated MSAs, monomer and AlphaFold2-Multimer complex folding, and confidence-based validation (pLDDT, pTM/ipTM, PAE). Use when folding a protein sequence or complex from FASTA, generating a predicted structure with confidence metrics, ranking models, or checking self-consistency of a design. For co-folding a protein WITH a small-molecule ligand or predicting binding affinity prefer alterlab-boltz; for antibody–antigen or one-FASTA multi-entity complexes prefer alterlab-chai; to LOOK UP an already-computed structure prefer alterlab-alphafold-db; for ESM embeddings or inverse folding prefer alterlab-esm. Part of the AlterLab Academic Skills suite.
alterlab-alphafold-dbAccess the AlphaFold DB of 200M+ AI-PREDICTED protein structures — retrieve models by UniProt accession, download PDB/mmCIF files, and analyze prediction confidence metrics (pLDDT, PAE). Use when a UniProt ID needs a computationally predicted 3D structure or when no experimental structure exists, for homology modeling, protein engineering, or structure-based drug discovery; for EXPERIMENTALLY determined structures (X-ray, cryo-EM, NMR) prefer alterlab-pdb, and for protein sequences, annotations, or accession ID mapping prefer alterlab-uniprot instead. Part of the AlterLab Academic Skills suite.
alterlab-anndataBuild, slice, concatenate, read, and write AnnData annotated data matrices (obs, var, X, layers, obsm, uns) — the scverse data STRUCTURE, not an analysis pipeline. Use when creating or wrangling .h5ad/zarr files, managing cell and gene annotations, concatenating batches, or handling layers/obsm/backed-mode; for the QC, normalization, clustering, UMAP, and differential-expression analysis pipeline prefer alterlab-scanpy instead, and for RNA velocity from spliced/unspliced layers prefer alterlab-scvelo instead. Part of the AlterLab Academic Skills suite.