llming / lookup-mesh-tree-numbers
CLAUDE.md0 starsChanged 3 months agoMITView on GitHub
This project contains a Python script (enrich_mesh_types.py) that enriches MeSH (Medical Subject Headings) identifiers from the CTD (Comparative Toxicogenomics Database) with hierarchical classification information from the NLM MeSH API. - Reads data/ctd-mesh-ids.tsv - a TSV file with MeSH identifiers in the format "MESH:D012345" or "MESH:C012345" - Original columns: CTD-ASSIGNED CONCEPT ID, CTD-ASSIGNED CONCEPT NAME, CTD-ASSIGNED CONCEPT CATEGORY - Creates data/ctd-mesh-ids-enriched.csv with five additional columns: 1. **MESH_LABEL**: Official concept name from MeSH API 2. **MESH_TREE_NUMBERS**: Full hierarchical tree positions (e.g., "D04.345.566;D12.644.641")…
In this repository9 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- settings/CLAUDE.mdCLAUDE.md
- skills/CLAUDE.mdCLAUDE.md
- copilot-reviewSkill
- github-issuesSkill
- github-milestonesSkill
- pr-updateSkill
- sync-docsSkill
- wrapSkill
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
13 rules. About 0 are common, 10 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈10
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 35
If that fails, tries the mappedTo field as a fallback
- Distinctive: line 97
Batch SPARQL Queries: Instead of querying each tree top code individually, collect all unique top-level codes and query them in a single …
- Very specific: line 101
Parallel Processing: Use concurrent.futures or asyncio to query multiple MeSH IDs simultaneously (respect rate limits)
- Very specific: line 109
Alternative Mappings: If preferredMappedTo fails, try mappedTo field (broader mappings)
- Distinctive: line 110
Descriptor Types: Add column indicating whether concept is a Descriptor, SCR_Chemical, SCR_Disease, etc.
- Distinctive: line 117
Retry Logic: Add exponential backoff for failed API calls
- Distinctive: line 118
Validation: Check that tree numbers follow expected patterns (e.g., letter followed by numbers and dots)
- Distinctive: line 120
Output Validation: Verify all rows were written, check for data corruption
- Distinctive: line 132
Type Hints: Add comprehensive type annotations throughout
- Distinctive: line 133
Unit Tests: Test label extraction, tree number parsing, SPARQL query building
- Distinctive: line 134
Documentation: Add docstring examples, improve inline comments
- Distinctive: line 146
Descriptor IDs: Start with D (e.g., D010456)
- Distinctive: line 147
Supplementary Concept IDs: Start with C (e.g., C471568)
≈ “Common” is an estimate: at least 1 in 5 of the 26,980 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CTD MeSH IDs Enrichment Project
Overview
This project contains a Python script (enrich_mesh_types.py) that enriches MeSH (Medical Subject
Headings) identifiers from the CTD (Comparative Toxicogenomics Database) with hierarchical
classification information from the NLM MeSH API.
What the Script Does
Input
- Reads
data/ctd-mesh-ids.tsv- a TSV file with MeSH identifiers in the format "MESH:D012345" or "MESH:C012345" - Original columns: CTD-ASSIGNED CONCEPT ID, CTD-ASSIGNED CONCEPT NAME, CTD-ASSIGNED CONCEPT CATEGORY
Output
- Creates
data/ctd-mesh-ids-enriched.csvwith five additional columns:- MESH_LABEL: Official concept name from MeSH API
- MESH_TREE_NUMBERS: Full hierarchical tree positions (e.g., "D04.345.566;D12.644.641")
- MESH_TREE_LABELS: Descriptor labels for those tree positions (e.g., "Peptides, Cyclic")
- MESH_TREE_TOP_CODES: Top-level category codes (e.g., "D04;D12")
- MESH_TREE_TOP_LABELS: Labels for top-level categories (e.g., "Polycyclic Compounds;Amino Acids, Peptides, and Proteins")
How It Works
- Primary Lookup: Queries the MeSH API at
https://id.nlm.nih.gov/mesh/{id}.jsonfor each identifier - Supplementary Concept Handling: Many CTD concepts are supplementary records (C-numbers) that
don't have tree numbers. For these, the script follows a fallback strategy:
- First tries the
preferredMappedTofield to find a preferred descriptor with tree numbers - If that fails, tries the
mappedTofield as a fallback - For
mappedTo, uses the mapped concept's label even if it has no tree numbers (tree fields will be empty)
- First tries the
- Tree Label Extraction: Tree numbers belong to descriptors; all tree numbers for a descriptor share that descriptor's label
- Top-Level Label Lookup: Uses SPARQL queries against
https://id.nlm.nih.gov/mesh/sparqlto find which descriptor exists at each top-level tree position
Technical Details
- Dependencies: requests, click, tqdm
- Rate Limiting: 0.2s delay between rows (configurable with
--delay) - Caching: Uses
@lru_cachefor tree descriptor labels to reduce API calls - Progress: tqdm progress bar with time estimates
- Logging: Configurable log levels (DEBUG, INFO, WARNING, ERROR)
- Performance: Processes ~2.9 rows/second, ~773 rows in ~4.5 minutes
Usage
# Basic usage
uv run enrich_mesh_types.py
# Custom output file
uv run enrich_mesh_types.py -o custom-output.tsv
# Adjust rate limiting (faster, but be respectful to API)
uv run enrich_mesh_types.py --delay 0.1
# Debug mode (see all API interactions)
uv run enrich_mesh_types.py --log-level DEBUG
# Quiet mode (only errors)
uv run enrich_mesh_types.py --log-level ERRORCurrent Results
On the current dataset (773 MeSH identifiers), per data/last-run.log:
- 675 enriched with tree numbers
- 96 resolved through
preferredMappedTo/mappedToto a descriptor that itself has no tree numbers — these get aMESH_LABELbut empty tree columns (found_mapped_label_only) - 2 failed outright (no concept record, no mapping)
- 496 rows in total went through a mapping, so the mapping fallback is doing most of the work
Known Issues & Limitations
- Supplementary Concepts: Many C-numbers have no tree numbers of their own. The mapping fallback finds a descriptor for nearly all of them, but ~96 of those descriptors have no tree numbers either, so the rows end up with a label and empty tree columns rather than an error
- API Response Formats: MeSH API returns data in multiple JSON-LD formats that require careful parsing
- Performance: SPARQL queries for tree top labels add significant overhead (~10s of API calls per row in worst case)
- Tree Number URIs: Tree numbers can be returned as full URIs
(
http://id.nlm.nih.gov/mesh/D04.345.566) or bare codes (D04.345.566) requiring normalization
Suggested Improvements for Future Sessions
Performance Optimizations
- Batch SPARQL Queries: Instead of querying each tree top code individually, collect all unique top-level codes and query them in a single SPARQL request
- Persistent Cache: Save tree label cache to disk (JSON/SQLite) to avoid re-querying across runs
- Parallel Processing: Use
concurrent.futuresorasyncioto query multiple MeSH IDs simultaneously (respect rate limits) - Resume Capability: Track processed IDs to allow resuming interrupted runs
Enhanced Functionality
- Full Tree Path: Extract complete hierarchical path with labels at each level (not just top-level)
- Alternative Mappings: If preferredMappedTo fails, try
mappedTofield (broader mappings) - Descriptor Types: Add column indicating whether concept is a Descriptor, SCR_Chemical, SCR_Disease, etc.
- Relationship Data: Extract broader/narrower terms, related concepts
- Historical Data: Track dateIntroduced, lastUpdated fields
Robustness
- Retry Logic: Add exponential backoff for failed API calls
- Validation: Check that tree numbers follow expected patterns (e.g., letter followed by numbers and dots)
- Output Validation: Verify all rows were written, check for data corruption
- Error Recovery: Save problem IDs to separate file for manual review
User Experience
- Dry Run Mode: Preview what will be enriched without making API calls
- Summary Report: Generate markdown/HTML report with statistics, charts of coverage by category
- Diff Mode: Compare two enrichment runs to see what changed
- Interactive Mode: Prompt for confirmation on ambiguous mappings
Code Quality
- Type Hints: Add comprehensive type annotations throughout
- Unit Tests: Test label extraction, tree number parsing, SPARQL query building
- Documentation: Add docstring examples, improve inline comments
- Configuration File: Support YAML/TOML config for default options
MeSH API Endpoints Reference
- Descriptor/Concept:
https://id.nlm.nih.gov/mesh/{id}.json - SPARQL Endpoint:
https://id.nlm.nih.gov/mesh/sparql?query={encoded_query}&format=JSON - Tree Number:
https://id.nlm.nih.gov/mesh/{tree_number}.json(returns TreeNumber object, not descriptor)
Data Notes
- Descriptor IDs: Start with D (e.g., D010456)
- Supplementary Concept IDs: Start with C (e.g., C471568)
- Tree Numbers: Hierarchical codes like "D04.345.566" where:
- First letter = top category (A=Anatomy, B=Organisms, C=Diseases, D=Chemicals, etc.)
- Numbers before first dot = second-level category
- Subsequent numbers = deeper hierarchy
Related Files
data/ctd-mesh-ids.tsv- Input file with CTD MeSH identifiersdata/ctd-mesh-ids-enriched.csv- Output file with enriched data (CSV format)enrich_mesh_types.py- Main enrichment script
Session Context
This script was developed to help understand and classify chemical entities and other biomedical concepts from CTD by mapping them to the standardized MeSH hierarchy. The enriched tree numbers enable:
- Grouping concepts by therapeutic/chemical class
- Understanding hierarchical relationships
- Filtering by specific branches of the MeSH tree
- Integration with other systems that use MeSH classifications
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

