Files
scientific-agent-skills/skills/primekg/scripts/query_primekg.py
T
Timothy Kassis 4fb7e0bc29 Test every script-bearing skill, and enforce that it stays that way
AGENTS.md has always said that a skill shipping scripts/ puts its tests in
tests/<name>/, but nothing checked it: 54 of the 100 such skills had no suite
at all, including docx, pptx, xlsx, pdf and scanpy. All 100 now do.

tests/_meta is the guard. It runs the shared structural contract across every
skill in a single process -- safe because it parses scripts with ast and never
imports them -- and fails when a skill ships scripts/ without a suite or
without a [skills.<name>] entry in skill-requirements.toml. It needs no
scientific packages and finishes in seconds, so skill-tests.yml blocks every
pull request on it, plus the packages=[] suites.

tests/_contract holds what the per-skill suites were each reimplementing:
frontmatter conformance, the 500-line limit, no tests or bytecode under
skills/, local links resolving, scripts parsing, no eval/exec/os.system, no
standard-library shadowing, no hardcoded local paths, valid shell scripts. Also
the --help contract, which skips when a skill's packages are absent and runs
for real under --isolated, and shared behaviour for the files docx/pptx/xlsx
and five schematic-shipping skills carry byte-identical copies of, with drift
detection so they cannot diverge silently.

67 new suites, 3325 test functions. The existing suites were retrofitted: 18
no longer pin an exact skill version, so a version bump no longer breaks a
test; 11 duplicated structural methods removed; 19 wired to the --help
contract; and 5 that failed collection without their packages now skip
cleanly. run_all.py in the bare project environment goes from 6 failures to 0.

Writing the tests surfaced 19 defects in the skills, fixed here with version
bumps. The ones that changed scientific output:

  - openpiv reported vorticity 0 for a rotating flow, from a sign error in
    openpiv's y-up coordinate relabelling; solid-body rotation now gives 2w
    exactly, on grids of either orientation
  - deepchem returned solubility predictions in z-scored space while labelling
    them log(mol/L), because it transformed a y-less dataset instead of
    untransforming the output
  - neuropixels-analysis had the Allen and IBL ISI thresholds swapped,
    contradicting its own references/QUALITY_METRICS.md and inverting the two
    standards' relative strictness
  - scanpy's summarize() raised TypeError on every AnnData under anndata 0.13,
    which reports an unnamed None key on .layers; scanpy convert was broken
  - experimental-design's Latin hypercube was never reproducible: pyDOE3 draws
    from its own default_rng and ignores numpy's global seed
  - primekg shipped a hardcoded path naming a person, which is why
    no_personal_paths is now a contract rule

The remainder is upstream API drift, each verified against the installed
package: retired symbols in bioservices 1.16, gget helpers that returned lists
where a string was written, ArviZ 1.x kwargs in pymc, a positional-only
factory in pymoo, ReduceLROnPlateau(verbose=) in torch 2.13, a removed scvelo
parameter, and PyPDF2 in scientific-slides.

Two manifest environments could not build and are pinned: gget, where an
unpinned scanpy walked back to 1.9.8 and pulled llvmlite 0.36 which does not
compile on 3.13, and pymatgen, pinned to the snapshot its own _common.py
enforces rather than loosening that check. deepchem gains torch, without which
no model class exists.

python tests/run_all.py --isolated: 101 passed, 0 failed.
2026-07-28 10:20:12 -07:00

129 lines
4.9 KiB
Python

import pandas as pd
import os
import json
from typing import List, Dict, Optional, Union
# Where kg.csv lives. Override with the PRIMEKG_DATA environment variable, or
# by assigning to DATA_PATH before calling any query function.
DATA_PATH = os.environ.get("PRIMEKG_DATA", "data/PrimeKG/kg.csv")
def _load_kg():
"""Internal helper to load the KG efficiently."""
if not os.path.exists(DATA_PATH):
raise FileNotFoundError(
f"PrimeKG data not found at {DATA_PATH}. Download kg.csv from "
"https://dataverse.harvard.edu/dataverse/primekg and set "
"PRIMEKG_DATA to its path."
)
# For very large files, we might want to use a database or specialized graph library.
# For now, we'll use pandas for simplicity but with low_memory=True.
return pd.read_csv(DATA_PATH, low_memory=True)
def search_nodes(name_query: str, node_type: Optional[str] = None) -> List[Dict]:
"""
Search for nodes in PrimeKG by name and optionally type.
Args:
name_query: String to search for in node names.
node_type: Optional type of node (e.g., 'gene/protein', 'drug', 'disease').
Returns:
List of matching nodes with their metadata.
"""
kg = _load_kg()
# Check both x and y columns for unique nodes
x_nodes = kg[['x_id', 'x_type', 'x_name', 'x_source']].drop_duplicates()
x_nodes.columns = ['id', 'type', 'name', 'source']
y_nodes = kg[['y_id', 'y_type', 'y_name', 'y_source']].drop_duplicates()
y_nodes.columns = ['id', 'type', 'name', 'source']
nodes = pd.concat([x_nodes, y_nodes]).drop_duplicates()
mask = nodes['name'].str.contains(name_query, case=False, na=False)
if node_type:
mask &= (nodes['type'] == node_type)
results = nodes[mask].head(20).to_dict(orient='records')
return results
def get_neighbors(node_id: Union[str, int], relation_type: Optional[str] = None) -> List[Dict]:
"""
Get all direct neighbors of a specific node.
Args:
node_id: The ID of the node (e.g., NCBI Gene ID or ChEMBL ID).
relation_type: Optional filter for specific relationship types.
Returns:
List of neighbors and the relationship metadata.
"""
kg = _load_kg()
node_id = str(node_id)
mask_x = (kg['x_id'].astype(str) == node_id)
mask_y = (kg['y_id'].astype(str) == node_id)
if relation_type:
mask_x &= (kg['relation'] == relation_type)
mask_y &= (kg['relation'] == relation_type)
neighbors_x = kg[mask_x][['relation', 'display_relation', 'y_id', 'y_type', 'y_name', 'y_source']]
neighbors_x.columns = ['relation', 'display_relation', 'neighbor_id', 'neighbor_type', 'neighbor_name', 'neighbor_source']
neighbors_y = kg[mask_y][['relation', 'display_relation', 'x_id', 'x_type', 'x_name', 'x_source']]
neighbors_y.columns = ['relation', 'display_relation', 'neighbor_id', 'neighbor_type', 'neighbor_name', 'neighbor_source']
results = pd.concat([neighbors_x, neighbors_y]).to_dict(orient='records')
return results
def find_paths(start_node_id: str, end_node_id: str, max_depth: int = 2) -> List[List[Dict]]:
"""
Find paths between two nodes (e.g., Drug to Disease) up to a certain depth.
Note: Simple BFS implementation.
"""
kg = _load_kg()
start_node_id = str(start_node_id)
end_node_id = str(end_node_id)
# Simplified path finding for depth 1 and 2
# Depth 1
direct = kg[((kg['x_id'].astype(str) == start_node_id) & (kg['y_id'].astype(str) == end_node_id)) |
((kg['y_id'].astype(str) == start_node_id) & (kg['x_id'].astype(str) == end_node_id))]
paths = []
for _, row in direct.iterrows():
paths.append([row.to_dict()])
if max_depth >= 2:
# Find neighbors of start
n1_x = kg[kg['x_id'].astype(str) == start_node_id]
n1_y = kg[kg['y_id'].astype(str) == start_node_id]
# This is computationally expensive in pure pandas for a large KG.
# Implementation skipped for brevity in this MVP, but suggested for full version.
pass
return paths
def get_disease_context(disease_name: str) -> Dict:
"""
Analyze the local graph around a disease: associated genes, drugs, and phenotypes.
"""
results = search_nodes(disease_name, node_type='disease')
if not results:
return {"error": "Disease not found"}
disease_id = results[0]['id']
neighbors = get_neighbors(disease_id)
summary = {
"disease_info": results[0],
"associated_genes": [n for n in neighbors if n['neighbor_type'] == 'gene/protein'],
"associated_drugs": [n for n in neighbors if n['neighbor_type'] == 'drug'],
"phenotypes": [n for n in neighbors if n['neighbor_type'] == 'phenotype'],
"related_diseases": [n for n in neighbors if n['neighbor_type'] == 'disease']
}
return summary